<?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 Hillary kipkemoi on Medium]]></title>
        <description><![CDATA[Stories by Hillary kipkemoi on Medium]]></description>
        <link>https://medium.com/@hillaryke?source=rss-5307439e4de2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nDXxfb1fmZiv6I5OULyzLw.jpeg</url>
            <title>Stories by Hillary kipkemoi on Medium</title>
            <link>https://medium.com/@hillaryke?source=rss-5307439e4de2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:28:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hillaryke/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[Semantic Image and Text Alignment: Automated Storyboard Synthesis for Digital Advertising]]></title>
            <link>https://medium.com/@hillaryke/semantic-image-and-text-alignment-automated-storyboard-synthesis-for-digital-advertising-175768d2576d?source=rss-5307439e4de2------2</link>
            <guid isPermaLink="false">https://medium.com/p/175768d2576d</guid>
            <dc:creator><![CDATA[Hillary kipkemoi]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 09:07:01 GMT</pubDate>
            <atom:updated>2024-07-18T05:35:17.259Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Online advertising has been growing more complex, and we can agree that reaching to modern audiences and capturing their attention is key. This would require more than just compelling visuals; it demands a deep understanding of user behavior, preferences, and the ever-evolving digital landscape.</p><p>In this project, we are going to look at how we can automate the creation of storyboards for digital ads. We’ll be using a variety of tools and techniques, including machine learning, computer vision, and natural language processing. Our goal is to create a system that can take a simple text description of an ad (with assets) and turn it into a visually compelling storyboard that accurately reflects the intended user flow and narrative.</p><h4>Business Objective</h4><p>The business objective of this project, as defined by Adludio, is to leverage machine learning, image and text generation, and LLM-based agents to automate the storyboard creation process. This automation aims to expedite the ad creation process, reduce turnaround time, and enhance the conceptualization of digital campaigns. The ultimate objective is develop a machine learning framework that can seamlessly convert textual ad descriptions into detailed, visually compelling storyboards that accurately reflect the intended user flow and narrative of an advertising campaign.</p><h3>The Approach</h3><p>This challenge is divided into four main tasks:</p><ol><li><strong>EDA &amp; Workflow Strategy:</strong> I started this by exploring the data and figuring out which CV models to use.</li><li><strong>Task 2: Critic/Grading Agent:</strong> Create an AI agent that acts like a critic. It will analyze our images and text, giving us feedback on whether our ads are visually appealing and effective. It will also offer suggestions on how to position the ads for a visually appealing AD frame.</li><li><strong>Task 3: Image Composition Agent:</strong> This agent will take the images and text we give it and arrange them into beautiful and engaging ad frames.</li><li><strong>Task 4: Building the Storyboard:</strong> The final step! We’ll put all the frames together to create a complete storyboard that tells the story of our ad.</li></ol><h3>Understanding the Data (EDA)</h3><p>Before we jump into the technical stuff, let’s take a look at the data we’ll be working with. We have:</p><ol><li><strong>Assets Folder: </strong>This is a collection images used in past ads. Each folder represents a different ad, and inside, we find images for the start, end, and other key moments of the ad.</li><li><strong>Sample Concepts (JSON):</strong> This file gives us a sneak peek into how creatives think. It outlines different ad ideas, step-by-step instructions for each scene, and even suggestions for what kind of images or text to use.</li><li><strong>Storyboard Examples:</strong> This showcases how the final product should look as a storyboard.</li><li><strong>Performance Data (CSV):</strong> This file is all about numbers. It tells us how well different ads performed in terms of engagement rate (how much people interacted with the ad) and click-through rate (how often people clicked on the ad).</li></ol><p>To understand the data I did some Exploratory Data Analysis (EDA). I found that:</p><ul><li>Engagement rates and click-through rates vary a lot across different ads.</li><li>Some ads are super engaging, while others, not so much.</li><li>This tells us there’s a lot of room to improve ad performance.</li></ul><h4><strong>Looking at the performance data of the past ads:</strong></h4><p>An initial look at the data reveals the following insights:</p><ul><li>The average engagement rate is 14%, but the median is 12%, suggesting that the distribution is skewed by some high-performing ads.</li><li>The average click-through rate is only 3%, with a median of 2%, indicating that most ads have relatively low CTR.</li><li>There’s a wide range in both ER (0–52%) and CTR (0–30%), highlighting the variability in ad performance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*icQqxESH7_u4eNCc" /><figcaption>Histogram of Click-Through Rate (CTR)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*JRa6Ol5YIDmCFPhu" /><figcaption>histogram of Engagement Rate (ER)</figcaption></figure><p>These findings suggest that there’s significant room for improvement in ad performance. By building a tool to automate storyboard creation, we aim to help advertisers identify the elements that contribute to successful ads and create more engaging and effective campaigns.</p><h3>Image analysis and feature Extractions — Computer Vision tools</h3><p><strong>Locating Assets within Creatives: </strong>I implemented a function called locate_image_on_image that uses template matching to pinpoint the exact location of specific image elements within a larger advertisement image. This allowed me to extract features like the size, position, and area covered by each element, providing valuable data for understanding the composition of existing ads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*2_VXZzJJDSakV8APQ4IMzQ.png" /><figcaption>The text in being extracted</figcaption></figure><p><strong>Extracting Colors: </strong>I utilized the extcolors library to identify the dominant colors present in various ad images. By analyzing the color composition, I could determine the background and text colors, assess contrast and saturation levels, and gain insights into the overall visual appeal of the ads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/0*UAIeawiW56VJ15mG" /><figcaption>color extraction</figcaption></figure><p><strong>Extracting Text:</strong> To extract text embedded within images, I employed Pytesseract, an Optical Character Recognition (OCR) tool. By converting image text into machine-readable text, I could analyze the textual content of ads, including taglines, calls to action, and other relevant information.</p><h4><strong>Object Detection with YOLO (fine-tuned)</strong></h4><p>I explored the capabilities of YOLOv8 (You Only Look Once), a real-time object detection algorithm. This state-of-the-art model allowed me to detect and classify objects within images, providing information about the types of objects present and their locations. This information is crucial for understanding the content and focus of each ad.</p><p>The objective was to enhance the object detection capabilities of YOLOv8 to accurately identify and locate key elements (logos, text, products, etc.) within digital advertisements.</p><p><strong>Dataset:</strong></p><ul><li><strong>Source:</strong> Images from the Assets folder were used for training and validation.</li><li><strong>Size:</strong> 30 training images, 9validation images.</li><li><strong>Annotation:</strong> Images were manually annotated with bounding boxes and labels for the following 23 categories:</li></ul><p>Background Image, Logo, Call-To-Action (CTA) Button, Icon, Product Image, Text Elements, Infographic, Banner, Illustration, Photograph, Mascot, Testimonial Quotes, Social Proof, Seal or Badge, Graphs and Charts, Decorative Elements, Interactive Elements, Animation Frames, Coupon or Offer Code, Legal Disclaimers or Terms, Contact Information, Map or Location Image, QR Code</p><p><strong>Model and Training:</strong></p><ul><li><strong>Model:</strong> YOLOv10s (a smaller, faster variant of YOLOv10)</li><li><strong>Epochs:</strong> 25</li><li><strong>Batch Size:</strong> 16</li><li><strong>Input Image Size:</strong> 800x800 pixels</li><li><strong>Optimizer:</strong> AdamW (learning rate = 0.000625, momentum = 0.9)</li><li><strong>Loss Function:</strong> Combination of box loss, class loss, and DFL (dynamic filter learning) loss</li></ul><p><strong>Training Progress:</strong></p><ul><li>Each epoch processed the entire training dataset.</li><li>Model weights were adjusted based on calculated losses.</li><li>Periodic validation was performed on the validation dataset.</li></ul><p>Progress was logged, including:</p><ul><li>GPU memory usage</li><li>Box loss, class loss, DFL loss</li><li>Number of instances detected</li></ul><p><strong>Performance Evaluation:</strong></p><ul><li><strong>Metrics:</strong> Precision, recall, mAP50 (mean Average Precision at IoU threshold of 0.5), and mAP50–95.</li><li><strong>Evaluation:</strong> Calculated for each class and overall on the validation dataset.</li></ul><p><strong>Outcomes for fine-tuned YOLOv10 for object detection</strong></p><p>The fine-tuned YOLOv8 model demonstrated improved accuracy in detecting and classifying objects within ad images compared to the base model. This enhanced object detection capability will be a valuable asset for the image composition and critic agents in the automated storyboard generation system.</p><h3>Building image Composition agent</h3><p>One of the core tasks in creating a storyboard is image composition — the art of arranging different elements (images, text, etc.) to create visually appealing and effective ads. Here I used a Python function that leverages the Pillow library for image manipulation:</p><p>This is how the function would look like, see <a href="https://github.com/hillaryke/Automated-Storyboard-Synthesis-Digital-Advertising/blob/main/src/image_composition.py">here</a> for the full code implementation.</p><pre>def compose_ad_frame(frame_width: int, frame_height: int, elements: list, output_path: str = &#39;composed_image_frame.jpg&#39;) -&gt; Image:<br>    &quot;&quot;&quot;<br>    Composes an advertisement frame using multiple image elements.<br><br>    Args:<br>        frame_width (int): Width of the desired frame.<br>        frame_height (int): Height of the desired frame.<br>        elements (list): List of dictionaries, each containing:<br>            - image_path (str): Path to the image file.<br>            - position (tuple): (x, y) coordinates of the top-left corner.<br>            - size (tuple, optional): (width, height) to resize to (maintaining aspect ratio).<br>            - has_background (bool): Whether the image has a background (True) or is transparent (False).<br><br>    Returns:<br>        PIL.Image: The composed ad frame.<br>    &quot;&quot;&quot;<br><br>    # Create a new blank RGBA image<br>    composed_frame = Image.new(&#39;RGBA&#39;, (frame_width, frame_height))<br><br>    for element in elements:<br>        # Load and convert image to RGBA<br>        img = Image.open(element[&#39;image_path&#39;]).convert(&#39;RGBA&#39;)<br><br>        # Resize if size is provided<br>        ## implementation to resize is done here<br><br>        # Paste the image onto the frame<br>        if element.get(&#39;has_background&#39;, True):  # Default to True if not specified<br>            composed_frame.paste(img, element[&#39;position&#39;])<br>        else:<br>            composed_frame.alpha_composite(img, element[&#39;position&#39;])<br><br>    # Convert to RGB<br>    new_img = composed_frame.convert(&#39;RGB&#39;)<br>    <br>    # Save the image<br>    new_img.save(output_path)<br>    <br>    return new_img</pre><p>Below is what the compose image functionality works:</p><p><strong>Image Loading and Preparation:</strong></p><ul><li>Each image defined in the elements list is loaded using Image.open() and converted to RGBA mode (Image.convert(&#39;RGBA&#39;)) to handle potential transparency.</li><li>If a desired size is provided in the element’s dictionary, the image is resized to that size while maintaining its aspect ratio. This ensures that images fit within the frame without being stretched or distorted.</li></ul><p><strong>Composing the Frame:</strong></p><ul><li>A new image (composed_frame) is created with the specified frame_width and frame_height in RGBA mode (to support transparency). This image serves as the canvas for composing all the elements.</li><li>The function iterates through the list of elements:</li><li>If an element has a background (has_background is True), it is pasted directly onto the composed_frame using Image.paste().</li><li>If an element is transparent (has_background is False), it is blended onto the composed_frame using Image.alpha_composite(). This method ensures that the transparent areas of the image blend seamlessly with the underlying layers.</li><li>The final composed frame is converted to RGB mode (removing the alpha channel for compatibility with image formats like JPEG) before being saved to the specified output_path or returned as a Pillow Image object.</li></ul><h4><strong>Setting up autogen agent for image composition</strong></h4><p>After having the image composition function, the next step was to setup the Autogen agent that runs this function intelligently.<br>The code for the agent implementation can be found here. It utilizes the AutoGen framework to create an assistant agent capable of composing advertisement frames from multiple image assets. The process involves using the assistant agent to generate function calls to the compose_ad_frame function, which leverages the Pillow library for image manipulation.</p><p><strong>Key Features:</strong></p><ul><li><strong>Automation:</strong> The code automates the process of composing ad frames based on user instructions.</li><li><strong>Flexibility:</strong> You can easily customize the frame dimensions, assets, and positions by modifying the message. This is useful later for so that the critica agent will be the one providing the message on how the assets will be compose optimally</li><li><strong>Integration with AutoGen:</strong> The code demonstrates how to leverage the AutoGen framework to create agents that can understand instructions and execute functions.</li></ul><h4><strong>Code Structure:</strong></h4><p>This is the details of the code implementation for image composition agent. The configuration and settings can be found here</p><ol><li><strong>Configuration:</strong></li></ol><ul><li>config_list: Defines the LLM (Large Language Model) configuration, specifying the model to use (gpt-4o).</li><li>llm_config_assistant: Configures the assistant agent with the specified LLM, temperature, and available functions.</li><li>compose_ad_frame function:</li></ul><p>Parameters:</p><ul><li>frame_width (int): Width of the desired frame.</li><li>frame_height (int): Height of the desired frame.</li><li>elements (list): List of dictionaries, each defining an image element:</li><li>image_path (str): Path to the image file.</li><li>position (tuple): (x, y) coordinates of the top-left corner.</li><li>size (tuple, optional): (width, height) to resize the image to (maintaining aspect ratio).</li><li>has_background (bool): Whether the image has a background (True) or is transparent (False).</li><li>output_path (str, optional): Path to save the composed ad frame. Defaults to &#39;composed_image_frame.jpg&#39;.</li></ul><p>Functionality:</p><ul><li>Creates a blank RGBA image with the specified frame dimensions.</li><li>Loads each image element, resizes if needed, and pastes it onto the frame.</li><li>Handles transparent images using alpha compositing.</li><li>Saves the composed image (if output_path is provided) and returns it.</li></ul><p><strong>2. Agent Initialization:</strong></p><ul><li>assistant: Creates an ConversableAgent called &quot;Assistant&quot; with the specified LLM configuration and the compose_ad_frame function. The assistant agent is responsible for understanding the user&#39;s request and generating the appropriate function call to compose_ad_frame.</li><li>user_proxy: Creates a ConversableAgent called &quot;User&quot; to interact with the assistant agent. It executes the function calls generated by the assistant and handles termination messages.</li></ul><p><strong>3. User Interaction and Frame Composition:</strong></p><ul><li>message: A string containing the user&#39;s request to compose an ad frame with specific dimensions, assets, and positions.</li><li>user_proxy.initiate_chat(assistant, message, max_turns=2): Initiates a chat between the user_proxy and the assistant. The user&#39;s message is sent to the assistant, which generates a function call to compose_ad_frame based on the request. The user_proxy then executes this function call, creating the ad frame.</li></ul><p><strong>How to Use:</strong></p><ol><li><strong>Prepare Assets:</strong> We ensure we have the image assets (header.jpg, engagement_instruction_1.png, thumbnail.jpg) in the specified directory (/home/hillary_kipkemoi/Automated-Storyboard-Synthesis-Digital-Advertising/data/Assets/0a22f881b77f00220f2034c21a18b854/).</li><li><strong>Modify the </strong><strong>message Variable:</strong> Customize the message to include the desired frame dimensions, asset names, and positions. You can add or remove elements as needed.</li><li><strong>Running the Code:</strong> Execute the code. The assistant agent will generate a function call to compose_ad_frame, and the user_proxy will execute it, creating the composed image and saving it to &#39;composed_image_frame.jpg&#39; in the assets folder.</li></ol><h4>Results on image composition</h4><p>This is how the conversation between the user_proxy agent and the image composition assistant agent. The assistant agent will generate a function call to compose_ad_frame and user_proxy executes, then the assistant terminates once it recieved the expected result which is Image object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7bbZeICqfwptsYgKWXHV1A.png" /><figcaption>image composition agent with user proxy composing ad frame</figcaption></figure><p>And below is the image generated. The image seems to be close to what is expected, however there needs to be some improvement in aligning the engagement instruction text with the logo and slogan. Also adding more spacing between them could be beneficial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*RzJKSDORorQzcGVErpnJdA.png" /></figure><p>For the critic agent to notice these improvements, it uses the different tools as mentioned earlier which will enable it identify the text and object alignments.<br>It would then suggest the new positions for composing an improved image to the composition agent.</p><h3>Challenges encountered</h3><ul><li><strong>Integration of Tesseract OCR</strong>: One of the initial challenges was integrating Tesseract OCR into the project. The primary issue was the failure in building the wheel for tesseract-ocr due to missing dependencies, specifically the Leptonica library.</li><li><strong>Machine Learning Model Training (YOLOv10)</strong>: The project’s core functionality relies heavily on machine learning models to analyze and synthesize storyboards. Training these models to achieve high accuracy and efficiency was a significant challenge.</li><li><strong>Text Extraction Challenges:</strong> Pytesseract struggled to accurately capture stylized or complex text, hindering the critic agent’s ability to assess text alignment with the ad’s message and design.</li></ul><h3>Future improvements</h3><ul><li><strong>Making the storyboard from the composed ad frames. </strong>This would be crucial, however it is missing now since the implementation and understanding were challenging.</li><li><strong>Advanced Image Composition Techniques:</strong> The current image composition method is relatively simple. Exploring more advanced techniques, such as using generative AI models to create new images or incorporating user feedback to refine the composition, could lead to more creative and effective storyboards.</li><li><strong>Exploring other options for text extraction.</strong> I would explore more robust OCR techniques or specialized models like YOLOv10 trained on detecting text in the adverts.</li></ul><h3>Conclusion</h3><p>In conclusion, this project has laid the foundation for an AI-driven system capable of transforming textual ad descriptions into visual storyboards. By utilizing computer vision tools like Pillow, OpenCV, and Pytesseract, we’ve extracted essential features from existing ads, informing the development of a preliminary image composition agent. While challenges remain, such as limitations in text extraction accuracy, the progress made demonstrates the feasibility of automating this creative process. Future development will focus on refining the image composition and critic agents, incorporating more advanced techniques, and addressing the identified limitations to create a robust system to automate storyboard creation process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=175768d2576d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Contract Analysis RAG: A Retrieval-Augmented Generation (RAG) Approach to Legal Q&A]]></title>
            <link>https://medium.com/@hillaryke/contract-analysis-rag-a-retrieval-augmented-generation-rag-approach-to-legal-q-a-cdfca428efba?source=rss-5307439e4de2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdfca428efba</guid>
            <dc:creator><![CDATA[Hillary kipkemoi]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 20:00:33 GMT</pubDate>
            <atom:updated>2024-07-08T17:21:24.706Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Business challenge</strong></h3><p>Contracts are fundamental to business operations, yet their intricate nature can lead to misunderstandings, delays, and disputes. Traditional keyword-based search methods often prove inadequate due to the inherent ambiguity and context-dependent meaning of legal language. A more sophisticated solution was required — one that could grasp the subtleties of legal text and deliver accurate responses to user inquiries.</p><h3>Project Implementation</h3><ol><li><strong>Knowledge Base:</strong> The knowledge base consisted of the contract document given.</li><li><strong>Query Processing:</strong> User queries are initially processed to identify key terms and entities. This step involves natural language understanding techniques to extract the core intent of the query.</li><li><strong>Retrieval:</strong> Leveraging advanced retrieval mechanisms, the system identifies and extracts relevant passages from the knowledge base that are most likely to contain the answer to the user’s query.</li><li><strong>Generation:</strong> The extracted passages, along with the original query, are fed into a fine-tuned LLM. This model, trained on a vast corpus of legal text, generates a concise and accurate response that incorporates the retrieved contextual information.</li></ol><h3>Text Chunking for Optimized Retrieval</h3><p>To enhance the efficiency and effectiveness of the retrieval process, I implemented a text chunking strategy. Large legal documents can contain vast amounts of information, making it computationally expensive to compare a query against the entire document. By dividing the documents into smaller, more manageable chunks, we significantly improved the speed and accuracy of the retrieval process.</p><p><strong>RecursiveCharacterTextSplitter:</strong></p><p>I utilized LangChain’s RecursiveCharacterTextSplitter to divide our legal documents into chunks. This splitter intelligently breaks down text based on natural language boundaries, ensuring that chunks are semantically meaningful and coherent. I configured the splitter with a chunk_size of 400 characters and no overlap between chunks. Additionally, I added a start_index to each chunk, allowing me to track the original position of the chunk within the document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*yqKY6EEEW0TFnWIf" /></figure><h4>Semantic Chunking with OpenAIEmbeddings</h4><ul><li>From Langchain documentation on <a href="https://python.langchain.com/v0.1/docs/modules/data_connection/document_transformers/semantic-chunker/">semantic chunking</a>, I found out that we can break “break apart” sentences by looking for differences in embeddings between any two sentences.</li><li>When that difference is past some threshold, then they are split.</li></ul><p>The results from semantic chunking OpenAIembeddings revealed that it was not the most appropriate chunking strategy as some text were broken down where they were not supposed as seen in the image below.</p><ul><li>We can notice that the advisor name “Mr. ..” was cut off which was critical for identifying the parties involved in the agreement.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*Uh0yay4_Y0f7zaVxMZ12EA.png" /></figure><p>I also planned on testing out other chunking methods such as agent chunking which can be referred <a href="https://github.com/FullStackRetrieval-com/RetrievalTutorials/blob/main/tutorials/LevelsOfTextSplitting/5_Levels_Of_Text_Splitting.ipynb">here</a>.</p><h3><strong>Evaluation with RAGAS</strong></h3><p>To ensure the accuracy and reliability of our RAG-based Q&amp;A system, I conducted a comprehensive evaluation using the RAGAS (Retrieval-Augmented Generation Assessment Suite) framework. RAGAS provides a suite of metrics specifically designed to assess the performance of retrieval-augmented systems.</p><h4>Evaluation Dataset:</h4><p>I was provided with an evaluation dataset consisting of two contracts (one short, one long) along with 10 questions and their corresponding ground truth answers for each contract. This dataset allowed us to test the system’s ability to handle both concise and complex legal documents.</p><h4>Evaluation Metrics:</h4><p>I employed the following RAGAS metrics to assess the system’s performance:</p><ul><li><strong>Answer Correctness:</strong> Measures the factual accuracy of the generated answers.</li><li><strong>Faithfulness:</strong> Evaluates whether the answer is supported by the retrieved context. That is the answer is consistent factually to the context.</li><li><strong>Context Precision:</strong> Assesses the relevance of the retrieved context to the query.</li><li><strong>Context Recall:</strong> Measures how much of the relevant information in the document was retrieved.</li><li><strong>Context Relevancy:</strong> Determines the overall relevance of the retrieved context to the query.</li><li><strong>Answer Relevancy:</strong> Evaluates the relevance of the generated answer to the query.</li></ul><h4>Evaluation Pipeline:</h4><ol><li><strong>Data Preparation:</strong> We extracted question-answer pairs from our evaluation dataset and converted them into a format suitable for RAGAS.</li><li><strong>Inference:</strong> We ran our RAG system on the evaluation questions, retrieving relevant context and generating answers.</li><li><strong>Evaluation:</strong> We used RAGAS to compute the aforementioned metrics, comparing the system’s answers to the ground truth.</li></ol><pre>def evaluate_metrics(dataset):<br>  # evaluating dataest on listed metrics<br>  result = evaluate(<br>      dataset=dataset,<br>      metrics=[<br>          answer_correctness,<br>          faithfulness,<br>          context_precision,<br>          context_recall<br>      ]<br>  )<br><br><br>  df_results = result.to_pandas()<br><br>  return df_results<br><br>def run_evaluation(retriever,<br>                   file_path=&quot;data/evaluation_sets/Robinson_Q&amp;A.docx&quot;,<br>                    llm=None,<br>                   test_size=None):  # Replace with your actual file path<br>  df = extract_qa_pairs_to_df(file_path)<br><br>  if test_size:<br>    df = df.head(test_size)<br>    <br>  # Change the df columns to list<br>  questions = df[&quot;question&quot;].tolist()<br>  ground_truths = df[&quot;ground_truths&quot;].tolist()<br><br><br>  answers = []<br>  contexts = []<br>  # Inference<br>  for query in questions:<br>      documents = retriever.get_relevant_documents(query)<br>      contexts.append(<br>          [docs.page_content for docs in documents]<br>      )<br>      context_text = format_docs_to_text(documents)<br><br>      answers.append(generate_answer(query, context_text, llm=llm))<br>      <br>  # To dict<br>  data = {<br>      &quot;question&quot;: questions,<br>      &quot;answer&quot;: answers,<br>      &quot;contexts&quot;: contexts,<br>      &quot;ground_truth&quot;: ground_truths,<br>  }<br><br>  # Convert dict to dataset<br>  dataset = Dataset.from_dict(data)<br>  <br>  results = evaluate_metrics(dataset)<br>  return results</pre><p>This is what the code above for the Ragas pipeline does:</p><ol><li><strong>evaluate_metrics(dataset):</strong></li></ol><ul><li><strong>Purpose:</strong> Evaluates question-answering performance using various metrics.</li><li><strong>Input:</strong> Dataset of questions, answers, ground_truths and contexts.</li><li><strong>Output:</strong> DataFrame with evaluation results.</li></ul><p><strong>2. </strong><strong>run_evaluation(retriever, file_path, llm, test_size):</strong></p><ul><li><strong>Purpose:</strong> Loads data, generates answers using a retriever and LLM (if provided), and evaluates the answers.</li><li><strong>Input:</strong> Retriever object, file path to question-answer pairs, optional LLM, optional test size.</li><li><strong>Output:</strong> DataFrame with evaluation results.</li></ul><h4>Results and Analysis when using RAG simple implementation</h4><ul><li>Starting with RecursiveCharacterTextSplitter with 200 characters chunk size, I saw a poor performance with mostly every metric from answer_correctness, to faithfulness and then to answer similarity.</li><li>This indicated that the chunking strategy may not be the best choice and that the context retrieval is poor, where the required context was not retrieved.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6zsXUZMcIoZqgmUw" /></figure><p><strong>Key Observations:</strong></p><ul><li><strong>Faithfulness:</strong> The system consistently demonstrated high faithfulness, indicating that its answers were well-grounded in the retrieved context. This underscores the effectiveness of the RAG approach in ensuring that responses are supported by the underlying legal documents.</li><li><strong>Answer Correctness:</strong> While faithfulness was consistently high, answer correctness varied across questions. This suggests that while the system generally locates relevant information, there is potential for improvement in the language model’s ability to interpret and synthesize that information into precise answers.</li><li><strong>Context Precision/Utilization:</strong> For certain questions, the system achieved high context precision and utilization, indicating that it successfully retrieved and utilized the most relevant passages. However, there were instances where the system could benefit from retrieving a wider range of relevant context.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m3MDgDfI4kuL9NQl" /></figure><h4><strong>LangChain’s RetrievalQA Chain</strong></h4><p>I leveraged LangChain’s RetrievalQA chain to streamline the implementation of our Q&amp;A engine. This chain provides a structured approach to combining a language model with a retrieval mechanism. In my case, I used the “stuff” chain type, which simply inserts all retrieved documents into the context and passes them to the language model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/0*RDXwS1Wf1SK-JykN" /></figure><p><strong>Code Implementation:</strong></p><p>The provided code snippet demonstrates the initialization of the RetrievalQA chain. It sets up the language model (ChatOpenAI), the retrieve, and the prompt template. The query_rag_pipeline function then takes a user query, invokes the chain to get a response, and extracts the answer from the response.</p><p>This engine is the core of the RAG-based system, enabling users to interact with legal contracts</p><p><strong>Prompt Engineering:</strong></p><p>To guide the language model’s response generation, I employed prompt engineering. I crafted a template (GENERATOR_TEMPLATE) that instructs the model to consider both the user’s query and the retrieved context when formulating its answer. This ensures that the model’s response is grounded in the relevant legal information and tailored to the specific question asked.</p><h3>Enhanced Retrieval with Cohere Reranking</h3><p>In my pursuit of optimizing the retrieval phase of our RAG pipeline, I integrated Cohere’s reranking capabilities. While my initial retrieval mechanism effectively identified relevant passages from the knowledge base, I sought to further refine the selection process to ensure the highest quality context was presented to the LLM for answer generation.</p><p>Cohere’s reranking model leverages advanced natural language understanding to assess the semantic relevance of retrieved passages to the user’s query. By incorporating this reranking step, I was able to prioritize passages that not only contained relevant keywords but also exhibited a deeper semantic alignment with the query’s intent. This enhancement led to a noticeable improvement in the precision and relevance of the information presented to the LLM, ultimately contributing to more accurate and informative answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*PEiHQEIyZhpjimug" /></figure><p>I integrated Cohere’s reranking model into the Langchain-based RAG pipeline. The retriever initially fetches a set of candidate passages from the knowledge base. These passages are then passed to the Cohere reranking model, which scores them based on their semantic relevance to the query. The highest-scoring passages are then selected as the final context for the LLM.</p><p>I observed a reduction in instances where the LLM generated responses based on less relevant or partially relevant information. This translated to increased accuracy, as the system consistently provided more precise and contextually appropriate answers.</p><h4>Results after using cohere reranking</h4><ul><li>The performance improved especially given the context_recall, context precision and the context precision, however the answer correctness is still low.</li><li>This implies that the llm generation still needs improvement.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVlWzOrsiA-XGoI-uPQM6A.png" /></figure><h3>AutoGen Implementation: Enhancing User Interaction</h3><p>To further enhance the user experience, I integrated AutoGen, a framework for creating conversational AI agents. AutoGen enables dynamic and interactive conversations between the user and the Q&amp;A system. This facilitates a more natural and intuitive way for users to explore and understand complex legal documents.</p><p>Below we have the retriever use proxy agent which</p><ul><li>The task is defined as “qa” (question answering), suggesting that the system is tailored for answering questions about legal contracts.</li><li>The knowledge base for the legal contracts is located at “data/content/Robinson Advisory.docx,” indicating the source of information the agent will draw upon to answer queries.</li><li>The “all-mpnet-base-v2” embedding model is used to convert text into numerical representations, facilitating semantic search and retrieval of relevant information.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*iJJkgSdkxinsgn0kTze_vQ.png" /></figure><h3>Challenges encountered</h3><ul><li><strong>Suboptimal Chunking:</strong> The chunking strategy for .docx files proved less than ideal, resulting in fragmented lines and potentially impacting the retrieval of relevant information.</li><li><strong>AutoGen Learning Curve:</strong> The initial understanding and effective utilization of the AutoGen framework posed a significant challenge, requiring substantial time investment and impacting project timelines.</li><li><strong>WebSocket API Integration:</strong> Building the API with WebSockets necessitated a deeper understanding of AutoGen’s communication mechanisms, adding complexity to the development process.</li></ul><h3>Future improvements</h3><p>The areas for improvement identified in the evaluation, such as enhancing answer correctness and expanding context retrieval, will guide my future efforts to refine and optimize the system.</p><p>I plan to address these by:</p><ul><li><strong>Fine-tuning the language model:</strong> I will continue to fine-tune the LLM on a larger corpus of legal text to enhance its understanding of legal nuances and improve its ability to generate accurate answers.</li><li><strong>Refining retrieval mechanisms:</strong> I will explore advanced retrieval techniques, such as more query expansion techniques and semantic search, to ensure that the system captures a broader range of relevant context.</li></ul><h4>More ranking options to be considered:</h4><ul><li><a href="https://github.com/PrithivirajDamodaran/FlashRank">Flash Rank</a>: Super-fast Python library to add re-ranking to the existing search &amp; retrieval pipelines. It is based on SoTA LLMs and cross-encoders.</li></ul><h3><strong>Conclusion</strong></h3><p>The development of this high-precision, RAG-based contract Q&amp;A system marks a significant stride in the application of artificial intelligence to the legal domain. While I have demonstrated the effectiveness of my approach in enhancing contract analysis, the intricate nature of legal language and the imperative for accuracy in this field highlight the need for continued refinement. I am committed to further research and development, focusing on expanding the knowledge base, enhancing retrieval mechanisms, and exploring innovative techniques to improve the precision and reliability of the system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdfca428efba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Scalable Backtesting Infrastructure for Crypto Trading: A Data Engineering and Machine…]]></title>
            <link>https://medium.com/@hillaryke/building-a-scalable-backtesting-infrastructure-for-crypto-trading-a-data-engineering-and-machine-fb0c13db57a5?source=rss-5307439e4de2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb0c13db57a5</guid>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[backtesting]]></category>
            <dc:creator><![CDATA[Hillary kipkemoi]]></dc:creator>
            <pubDate>Wed, 26 Jun 2024 16:31:41 GMT</pubDate>
            <atom:updated>2024-06-30T15:27:53.802Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Scalable Backtesting Infrastructure for Crypto Trading: A Data Engineering and Machine Learning Approach</h3><p>This blog post details the design and implementation of a backtesting infrastructure, specifically tailored for crypto trading and stock exchanges. We’ll delve into the data engineering and machine learning techniques employed to create a system that can handle large-scale data processing, automate backtesting workflows, and facilitate the development and evaluation of sophisticated trading strategies.</p><h4>Business objective</h4><p>Mela, a financial technology company aims to simplify cryptocurrency investing and provide reliable investment strategies while minimizing the risks associated with crypto trading. The project focuses on developing a robust data pipeline to enable comprehensive backtesting of trading strategies, simulating various market scenarios to gain insights into potential trends and risks. The ultimate goal is to create a scalable infrastructure capable of executing diverse backtests and storing valuable artifacts, empowering the company to offer informed investment solutions in the cryptocurrency space.</p><h3><strong>Project Objectives</strong></h3><p>The primary objectives of this project were to:</p><ol><li><strong>Develop a Scalable Data Pipeline:</strong> Establish a reliable pipeline to ingest, process, and store historical and real-time cryptocurrency market data from various sources. This pipeline should be capable of handling large volumes of data and adapting to changing market conditions.</li><li><strong>Create a Flexible Backtesting Engine:</strong> Build a backtesting engine that can accommodate a wide range of trading strategies, from simple rule-based approaches to complex machine learning models. The engine should provide comprehensive performance metrics and allow for parameter optimization.</li><li><strong>Facilitate Strategy Development:</strong> Enable the creation, storage, and management of custom trading strategies, fostering experimentation and innovation.</li><li><strong>Leverage Machine Learning:</strong> Explore the potential of machine learning models to enhance trading strategies by predicting market trends, identifying patterns, or generating trading signals.</li><li><strong>Ensure Scalability and Reliability:</strong> Design the infrastructure to be scalable, handling increasing data volumes and backtest requests efficiently. The system should also be reliable, with robust error handling and monitoring mechanisms.</li></ol><h3>Backtesting</h3><h3>The services:</h3><p>The base-image-gold:latest image is built locally using Dockerfile.base and serves as the foundation for several of these services.</p><p><strong>Overview of the app services</strong></p><ul><li><strong>PostgreSQL Database (</strong><strong>postgres)</strong>: Stores all financial data, including historical prices, user information, backtest results, and trading strategies.</li><li><strong>Adminer:</strong> Provides a web-based interface for managing the PostgreSQL database.</li><li><strong>Kafka (</strong><strong>kafka)</strong>: A distributed event streaming platform for real-time data streaming and communication between microservices.</li><li><strong>ZooKeeper (</strong><strong>zookeeper)</strong>: Manages coordination and configuration for the Kafka cluster.</li><li><strong>API Service (</strong><strong>api)</strong>: The primary interface for users to interact with the platform, built using FastAPI.</li><li><strong>Kafka Consumer (</strong><strong>kafka-consumer)</strong>: Consumes messages from Kafka topics and forwards them to the appropriate services.</li><li><strong>Database Service (</strong><strong>database-service)</strong>: Acts as a bridge between the Kafka consumer and the PostgreSQL database, handling data validation and storage.</li><li><strong>Backtest Service (</strong><strong>backtest-service)</strong>: Executes backtests based on received parameters and stores the results.</li><li><strong>Topic Creator (</strong><strong>topic_creator)</strong>: Ensures the existence of required Kafka topics during initialization and setup.</li></ul><h4><strong>Building the Application Services</strong></h4><p><strong>Common Service (</strong>x-common-service<strong>)</strong></p><p>This section defines a set of common configurations (image, volumes, environment variables, dependencies) that are shared by multiple services (api, kafka-consumer, database-service, and backtest-service). This promotes consistency and reduces redundancy in your Docker Compose file.</p><ol><li>api<strong>:</strong> This service represents your FastAPI backend application. It extends from the x-common-service definition, inheriting the base image and shared volumes. It&#39;s built from the ./api directory and runs the Uvicorn server to handle API requests. The command section specifies the command to start the server after waiting for Kafka to be ready using the wait-for-it.sh script.</li><li>kafka-consumer<strong>:</strong> This service is responsible for consuming messages from Kafka topics. It also extends from x-common-service and is built from the ./kafka_consumer directory. The command section defines how the consumer script is executed, using entr to automatically restart the consumer if the script changes.</li><li>database-service<strong>:</strong> This service provides an API for interacting with the PostgreSQL database. It extends from x-common-service and is built from the ./database-service directory. It runs a Uvicorn server to handle API requests related to database operations.</li><li>backtest-service<strong>:</strong> This service is responsible for executing backtests. It extends from x-common-service and is built from the ./backtest_service directory. It also runs a Uvicorn server to handle requests for initiating and managing backtests.</li><li>topic_creator<strong>:</strong> This service is a utility that creates Kafka topics if they don&#39;t exist. It uses the base-image-gold:latest image and runs a Python script (topic_creator.py) to create the topics specified in the TOPIC_NAMES environment variable. The restart: &quot;no&quot; setting ensures that it runs only once during the initial setup.</li></ol><h4><strong>The Kafka Producer’s Role</strong></h4><p>As a critical component of our backtesting infrastructure, the kafka_producer.py module facilitates the efficient and reliable transmission of data within the system. It serves as the backbone for sending messages to Kafka topics, enabling communication between various microservices and streamlining the flow of information throughout the pipeline.</p><p>The module defines two core functions:</p><ul><li>create_kafka_producer(kafka_bootstrap_servers, extra_config)<strong>:</strong> This function initializes and configures a Kafka producer, which is a key element for sending messages to Kafka topics. It accepts the kafka_bootstrap_servers parameter, which specifies the address of the Kafka broker, and an optional extra_config dictionary for additional producer settings. The function returns an initialized Producer object along with a boolean flag indicating whether the creation was successful, incorporating error handling for robustness.</li><li>send_message_to_kafka(topic_name, message, key)<strong>:</strong> This function encapsulates the logic for sending a JSON-serialized message to a specified Kafka topic. It receives the topic_name to which the message is destined, the message payload (which can be any Python object), and an optional key for partitioning the data within the topic. The function handles the serialization of the message into JSON format and leverages the producer to send the message, ensuring reliable delivery through the flush() method. Furthermore, it incorporates logging to track successful message transmission and potential errors that may arise during this process. Notably, the producer is a globally available object, which is instantiated when the module is imported. Upon a failed initialization of the producer object, the script will terminate.</li></ul><h3>The Kafka Consumer service</h3><p>The kafka_consumer.py script under the kafka-consumer service plays a pivotal role in our backtesting infrastructure by acting as the bridge between the Kafka message broker and the database service. It&#39;s responsible for consuming messages from various Kafka topics, processing them, and forwarding them to the appropriate endpoints in the database service for storage and further analysis.</p><p><strong>Core Functionalities:</strong></p><ol><li><strong>Topic Subscription and Message Consumption:</strong> The script subscribes to a list of Kafka topics (stock_data, user_registrations, backtest_results, and scenes_topic). It continuously polls these topics for new messages using the create_and_consume_messages function, which is an asynchronous generator that yields deserialized messages as they arrive.</li><li><strong>Message Forwarding:</strong> For each consumed message, the script determines the appropriate WebSocket endpoint in the database service based on the topic name using the endpoint_mapping dictionary. It then forwards the message to the corresponding endpoint using the forward_message_to_service function.</li><li><strong>Error Handling and Retries:</strong> The forward_message_to_service function includes robust error handling and retry mechanisms. If sending a message fails (e.g., due to a network issue or the database service being temporarily unavailable), the function will retry the operation up to a maximum number of times, with an exponentially increasing delay between retries. This ensures that messages are not lost and are eventually delivered to the database service and other services.</li><li><strong>Asynchronous Operation:</strong> The script leverages asyncio to handle message consumption and forwarding asynchronously. This allows it to efficiently process messages from multiple topics concurrently, improving the overall throughput and responsiveness of the system.</li></ol><h3>Choice of Schema creation model (using Kimball model)</h3><ul><li>We opted for a Kimball dimensional model for our data warehouse due to its simplicity and wide adoption in the industry. This model, characterized by fact and dimension tables, is optimized for Online Analytical Processing (OLAP) and facilitates efficient querying and reporting.</li></ul><h4>Why use Kimball Model</h4><ul><li>In contrast, the Data Vault model, while robust for data auditing and tracking, introduces complexity that might not be necessary for our backtesting use case.</li><li>Similarly, other models like 3NF (Third Normal Form) prioritize data integrity but can lead to slower query performance compared to the denormalized structure of a Kimball model.</li></ul><h3>Defining the Data Schema</h3><p>The models.py file defines the SQLAlchemy models that represent the structure of the database tables. These models are crucial for interacting with the PostgreSQL database using an Object-Relational Mapping (ORM) approach.</p><h4><strong>Key Models and Relationships:</strong></h4><p><strong>Dimension Tables:</strong></p><ul><li>Dim_Date: Stores information about dates (DateKey, Date, Year, Quarter, Month, Day).</li><li>Dim_Users: Stores user information (UserID, UserName, Email, PasswordHash).</li><li>Dim_Assets: Stores details about assets (AssetID, AssetName, AssetType, TickerSymbol).</li><li>Dim_Strategy: Stores information about trading strategies (StrategyID, StrategyName, StrategyDescription, ParametersNames).</li><li>Dim_Scene: Stores specific backtest scenarios, linking strategies to assets and timeframes (SceneID, Symbol, StartDate, EndDate, StrategyID, Parameters).</li></ul><p><strong>Fact Tables:</strong></p><ul><li>Fact_Trades: Records individual trades (TradeID, DateKey, UserID, AssetID, StrategyID, TradeType, Quantity, PricePerUnit).</li><li>Fact_Backtests: Stores the results of backtests (BacktestID, CreatedAt, UserID, SceneID, MaxDrawdown, SharpeRatio, Return, TradeCount, WinningTrades, LosingTrades, StartPortfolio, FinalPortfolio).</li><li>Fact_StockPrices: Stores historical stock prices (StockPriceID, DateKey, AssetID, Open, High, Low, Close).</li><li>Fact_CryptoPrices: Stores historical cryptocurrency prices (CryptoPriceID, DateKey, AssetID, Open, High, Low, Close).</li><li><strong>Relationships:</strong> The models define relationships between tables using foreign keys (e.g., Fact_Trades.DateKey references Dim_Date.DateKey). These relationships are crucial for maintaining data integrity and enabling efficient querying.</li></ul><h4><strong>Alembic Integration:</strong></h4><p>We used alembic to run the migration when making changes to the schema. You can refer <a href="https://simplyprashant.medium.com/how-to-use-alembic-for-your-database-migrations-d3e93cacf9e8">here</a> on how to use alembic to run migrations</p><p>The models.py file also imports Base from base.py, which is the declarative base for the SQLAlchemy models. This base class is used by Alembic to track changes to your models and generate migration scripts.</p><p>Updating Models with Alembic — When the models are modifed (e.g., add a new column), we use Alembic to manage the schema changes:</p><ol><li><strong>Generate Migration:</strong> Run alembic revision --autogenerate -m &quot;msg&quot;.</li><li><strong>Review and Edit:</strong> Review the generated script to ensure accuracy.</li><li><strong>Apply Migration:</strong> Run alembic upgrade head to apply the migration.</li></ol><h3>The Heart of User Interaction: Our FastAPI API Service</h3><p>The api/main.py script is the heart of our backend, providing a modern and efficient RESTful API built with FastAPI. This API serves as the primary interface for users and other services to interact with our backtesting infrastructure. Let&#39;s delve into its key functionalities:</p><ol><li><strong>Authentication (Login and Registration):</strong></li></ol><ul><li><strong>User Model:</strong> The User model defines the structure for user data during registration. It specifies the required fields (username, email, password) along with validation constraints to ensure data integrity. We&#39;ve made sure to use Pydantic for robust data validation and serialization.</li><li><strong>Password Security:</strong> To protect sensitive user data, we’ve incorporated passlib, a powerful password hashing library. The pwd_context object is initialized with the secure &quot;bcrypt&quot; hashing scheme, which ensures that passwords are never stored in plain text. Instead, they are transformed into irreversible hashes.</li><li><strong>Login Endpoint (</strong>/token<strong>)</strong>: This endpoint handles user login requests. It receives a username and password, verifies them against the hashed password stored in the database (using the get_user_by_username utility function), and generates a JSON Web Token (JWT) if authentication is successful. The JWT acts as a secure token for subsequent authorized access to the API&#39;s functionalities. We have ensured to include comprehensive error handling, using HTTP exceptions and logging, to manage invalid credentials and unexpected errors during login.</li><li><strong>Registration Endpoint (</strong>/register<strong>)</strong>: This endpoint handles user registration. It receives user data, including the password, hashes the password, and sends the user&#39;s information (including the hashed password) to a Kafka topic called user_registrations for further processing and storage in the database.</li></ul><ol><li><strong>Backtesting Endpoint (</strong>/backtest_scene<strong>)</strong>:</li></ol><ul><li><strong>Parameters Model:</strong> The Parameters model defines the structure and validation rules for the parameters required to run a backtest. This includes the symbol, start_date , end_date of the period, the starting cash , commission rate, the strategy to use (e.g., &quot;SMA Crossover&quot;), and the specific parameters for that strategy (e.g., moving average periods).</li><li><strong>Request Handling:</strong> This endpoint receives a POST request containing the Parameters data. It first converts this data into a JSON-serializable format, ensuring compatibility with Kafka. Then, it sends this serialized data to the scenes_topic Kafka topic, where it will be picked up by other components of the backtesting pipeline for further processing.</li></ul><p><strong>Utilities (</strong>utils.py<strong>)</strong></p><ul><li>The utils.py module contains helper functions for database interaction and user authentication. Notably, the get_user_by_username function fetches user data from the database based on the provided username, leveraging SQLAlchemy for database operations.</li></ul><h4>Testing the API endpoints using Postman</h4><p>This Postman screenshot illustrates a POST request to the /register endpoint of a FastAPI backend. The request body includes the user&#39;s details (username, email, and password), and the response confirms successful registration with the hashed password for added security.</p><h3>Airflow for orchestration</h3><ul><li>We used airflow to schedule the fetching of stock and Crypto data. This allowed us to have an automated collection of data and that our data warehouse is up to data with new trades each data in the trading market.</li><li>The script uses yfinance library to collect stock data and python-binance library to fetch crypto data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1mic4nTGU6ukcER7" /></figure><h3>Time Series forecasting</h3><h4>Using LSTM for time-series forecasting</h4><ul><li>We implemented LSTM time-series forecasting. The script uses TensorFlow and Keras to build a Long Short-Term Memory (LSTM) neural network model to predict cryptocurrency prices based on historical price data fetched from Yahoo Finance</li><li>MinMaxScaler and sklearn.preprocessing are used to normalize the closing price data between 0 and 1 separately for training and testing data</li><li>Two LSTM layers are added with dropout to prevent overfitting. The model is trained with a batch size of 32 and for 50 epochs.</li><li>After training, the model is used to predict prices for the test set</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*6t3jr-pouTf0UzTD" /></figure><h4>Time Series forecasting using ARIMA models</h4><ul><li>ARIMA (AutoRegressive Integrated Moving Average) is a statistical model that uses a combination of autoregressive (AR), integrated (I), and moving average (MA) processes to analyze and forecast time series data. It’s a popular choice for modeling financial data, like stock prices, due to its ability to capture trends, seasonality, and other patterns.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ikagxLL8yGtriCwY" /><figcaption>simple implementation of ARIMA for time series forecasting</figcaption></figure><ul><li><strong>Data Preparation:</strong> The code downloads the “GOOGL” stock data for the past 50 days and extracts the “Adj Close” prices.</li><li><strong>Model Creation:</strong> It creates an ARIMA model with order=(5, 1, 0), meaning it has 5 autoregressive terms, 1 degree of differencing, and 0 moving average terms.</li><li><strong>Model Fitting:</strong> The model is fitted to the historical data.</li><li><strong>Forecasting:</strong> The model generates forecasts for the next 5 business days.</li><li><strong>Result Creation:</strong> A dictionary is created that combines the dates, actual prices, and forecasted prices.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*i7OhG79SnBuix6VF" /><figcaption>The results from the prediction of GOOGL stock price using ARIMA</figcaption></figure><h3>Creating and Index fund</h3><ul><li>We created an Index of the 10 biggest crypto coins by market capitalization by excluding stable coins.</li><li>Uses a free API KEY for fetching cryptocurrency data from the CoinMarketCap API</li><li>The code uses python libraries like requests for API calls, and pandas for data manipulation</li><li>The code filters out stablecoins, sorts by market capitalization, and selects the top 10 cryptocurrencies</li></ul><p>This were the results and insights obtained:</p><ul><li><strong>Bitcoin Dominance:</strong> Bitcoin (BTC) holds a commanding lead in market capitalization, representing over 50% of the total market cap of the top 10 cryptocurrencies. This indicates its significant influence on the overall crypto market.</li></ul><p><strong>Note:</strong> The chart indicates market capitalization based on data from CoinMarketCap, which may not be a perfect reflection of the entire market. However, it provides valuable insights into the relative sizes and dominance of major cryptocurrencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/0*puNY4gtBmJW_PIrl" /><figcaption>Top 10 Cryptocurrencies by Market Cap</figcaption></figure><h3>Portfolio optimization</h3><p>We automated the process of portfolio construction based on historical data to achieve specific goals i.e minimize risk or maximize risk-adjusted returns and allow investors make informed decisions.</p><p>The approach we used is as follows:</p><ul><li>Define cryptocurrencies then define historical data using finance</li><li>Calculate log returns for portfolio returns over time.</li><li>Calculate Covariance Matrix — helps in understanding how the returns of the cryptocurrencies move together and assess portfolio risk.</li><li>Define optimization functions — standard deviation, sharpe ratio, return.</li></ul><p>These are the results obtained from the approach:</p><ul><li>The graphs show optimal portfolio weights for two different objectives: maximizing Sharpe ratio (risk-adjusted return) and minimizing volatility (risk).</li><li>Bitcoin (BTC) is a dominant asset in both portfolios, suggesting its importance for both returns and risk reduction.</li><li>The specific asset allocations differ significantly between the two objectives, highlighting the trade-off between risk and return.</li><li>Diversification is evident in both portfolios, with a mix of assets included to balance risk and reward.</li><li>The “best” portfolio depends on individual investor preferences and risk tolerance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*098-7EX4YiApyN-3" /><figcaption>Result on portfolio optimization with the selected cryptocurrencies.</figcaption></figure><h3>Frontend user experience</h3><p>Our frontend application prioritizes a seamless and intuitive user experience. Upon entering the platform, users are greeted with a login page where they can securely authenticate themselves using their credentials. Successful login generates a JSON Web Token (JWT), which is stored securely and used for subsequent interactions, ensuring a protected and personalized experience.</p><p>Once logged in, users are presented with a dedicated “Backtest a Strategy” page, designed to streamline the backtesting process. The page features a well-structured form that allows users to input essential parameters for their backtests:</p><ul><li><strong>Asset:</strong> Users can choose the financial instrument they wish to backtest (e.g., AAPL, GOOGL) from a dropdown menu.</li><li><strong>Strategy:</strong> A dropdown menu provides a selection of pre-defined trading strategies or allows users to upload their custom strategies.</li><li><strong>Date Range:</strong> Users can specify the start and end dates for the backtesting period.</li><li><strong>Cash:</strong> The initial capital to be used in the simulation is entered here.</li><li><strong>Commission:</strong> Users input the commission rate applied to each trade.</li><li><strong>Strategy-Specific Parameters:</strong> Depending on the chosen strategy, additional parameters (e.g., moving average periods, RSI thresholds) can be configured.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQd4DLaQzKZ1jZEHbS-RdQ.png" /><figcaption>login page for the user</figcaption></figure><p>Upon submitting the form by clicking “Run Backtests,” the frontend establishes a WebSocket connection with our API. This connection enables real-time communication, allowing the backend to stream backtest results directly to the frontend as they become available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpLnwHnvc_WVxE1QuoMNVQ.png" /><figcaption>backtest results displayed once user clicks run backtests</figcaption></figure><p>The “Backtest Results” section of the page dynamically displays the results in a tabular format. Each row represents a backtest run with a specific set of parameters, showing key performance metrics like Sharpe ratio, total return, maximum drawdown, and trade statistics.</p><h3>Challenges faced</h3><ul><li>Getting an understanding of the business objective and what the user wants.</li><li>Integrating all the components together, especially since everyone had a different task or component to work on.</li><li>Relaying results to the frontend, including backtests, plot images and index fund portfolio.</li><li>Understanding the concept on portfolio optimization including other trading concepts was a bit challenging.</li><li>Communication with the team was slow and hindered some part of the progress.</li></ul><h4>Future improvements</h4><ul><li>Adding more strategies</li><li>Use event streaming to get backtest results and other data like index fund capitalization real-time i.e by using websockets to relay backtest results to frontend by consumer</li><li>Use notifications i.e email notifications to notify user of the backtest results that are being sent</li><li>Adding MLflow to track the backtest results.</li><li>Exploring other time series forecasting language models and revisiting chronos and moirai language models</li><li>Automating backtest runs with airflow, given indicator and the indicators parameters ranges, meanwhile we could start the script manually.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb0c13db57a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Causal Inference for Logistic optimization: Delivery drivers location optimization ️]]></title>
            <link>https://medium.com/@hillaryke/causal-inference-for-logistic-optimization-delivery-drivers-location-optimization-%EF%B8%8F-c913cdbd77ca?source=rss-5307439e4de2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c913cdbd77ca</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[Hillary kipkemoi]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 18:47:52 GMT</pubDate>
            <atom:updated>2024-06-15T18:56:01.367Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we will embark on a data-driven journey to tackle this challenge head-on. We’ll delve into the world of causal inference, a powerful statistical framework that goes beyond correlation to uncover the true cause-and-effect relationships behind Gokada’s delivery issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-Wce45otpk6L6OBN.jpg" /></figure><h3>Business Objective</h3><p>Gokada, Nigeria’s leading last-mile delivery service, has experienced phenomenal growth in recent years. However, with this growth came a major challenge: a significant number of unfulfilled delivery requests. These unfulfilled requests not only impact customer satisfaction but also pose a threat to Gokada’s operational efficiency and revenue.</p><h4><strong>Understanding the Problem</strong></h4><p>Before we dive into the technical details, let’s understand the problem at hand. Gokada receives a large number of delivery requests every day. However, not all of these requests are fulfilled due to various factors. Some of the possible reasons for unfulfilled requests include:</p><ul><li><strong>Driver Unavailability:</strong> There might not be enough drivers available in a particular area to handle all the requests.</li><li><strong>Long Distances:</strong> Drivers might be located far away from the pickup or drop-off locations, making it time-consuming and inefficient to complete the deliveries.</li><li><strong>Traffic Congestion:</strong> Lagos, being a bustling city, often experiences heavy traffic, which can significantly delay deliveries.</li><li><strong>External Factors:</strong> Weather conditions, special events, or other unforeseen circumstances can also disrupt the delivery process.</li></ul><p>To address this multifaceted problem, we need to identify the key drivers of unfulfilled requests and develop strategies to mitigate their impact. This is where causal inference comes into play.</p><h4><strong>The Data</strong></h4><p>We have access to two valuable datasets:</p><ol><li>completed_orders.csv<strong>:</strong> This dataset contains records of successfully completed orders, including the origin and destination coordinates of each trip, as well as the start and end times.</li><li>drivers_location_during_request.csv<strong>:</strong> This dataset provides information on drivers&#39; locations at the time of receiving a delivery request, along with whether they accepted or rejected the request.</li></ol><p>These datasets offer a wealth of information that we can leverage to understand the dynamics of Gokada’s delivery operations. However, to glean meaningful insights, we need to clean, preprocess, and transform the data into a suitable format for analysis.</p><p><strong>Exploratory Data Analysis (EDA): Unveiling the Data’s Secrets</strong></p><p>Our first step is to load the datasets into Pandas DataFrames and take a closer look at their structure and contents. We use the df.head() method to display the first few rows of each DataFrame and df.info() to get a summary of the columns and their data types.</p><pre>import pandas as pd<br><br># Load the datasets<br>completed_orders = pd.read_csv(&#39;completed_orders.csv&#39;)<br>drivers_location = pd.read_csv(&#39;drivers_location_during_request.csv&#39;)<br><br># Display the first 5 rows<br>print(&quot;Completed Orders Data:&quot;)<br>print(completed_orders.head().to_markdown(index=False, numalign=&quot;left&quot;, stralign=&quot;left&quot;))<br><br>print(&quot;\nDrivers Location Data:&quot;)<br>print(drivers_location.head().to_markdown(index=False, numalign=&quot;left&quot;, stralign=&quot;left&quot;))</pre><p>Upon inspecting the data, we notice a few things:</p><ul><li>The completed_orders dataset has columns like Trip ID, Trip Origin, Trip Destination, Trip Start Time, and Trip End Time.</li><li>The drivers_location_during_request dataset has columns such as order_id, driver_id, driver_action, lat, lng, created_at, and updated_at</li><li>There are some missing values and columns that need to be renamed or dropped.</li></ul><h4><strong>Data Preprocessing: Cleaning and Preparing the Data</strong></h4><p>Before we can proceed with our analysis, we need to preprocess the data. This involves several steps:</p><ul><li><strong>Merging DataFrames:</strong> We merge the completed_orders and drivers_location_during_request DataFrames based on the order_id column. This allows us to link driver information with the corresponding trip details.</li><li><strong>Data Cleaning:</strong> We handle missing values (e.g., by imputation) and convert relevant columns to appropriate data types (e.g., converting timestamps to datetime objects).</li><li><strong>Feature Engineering:</strong> We extract additional features that may be relevant for our analysis, such as the day of the week, hour of the day, and the duration of the trip.</li></ul><pre>    def preprocess_data(self):<br>        &quot;&quot;&quot;Performs all cleaning and preprocessing steps.&quot;&quot;&quot;<br><br>        # Rename &#39;Trip ID&#39; to &#39;order_id&#39; in completed_orders<br>        self.completed_orders = self.completed_orders.rename(columns={&#39;Trip ID&#39;: &#39;order_id&#39;})<br>        <br>        # Convert &#39;order_id&#39; to string in both DataFrames<br>        self.completed_orders[&#39;order_id&#39;] = self.completed_orders[&#39;order_id&#39;].astype(str)<br>        self.drivers_location[&#39;order_id&#39;] = self.drivers_location[&#39;order_id&#39;].astype(str)<br>        <br>        # Drop unnecessary columns<br>        self.drivers_location.drop(columns=[&#39;created_at&#39;, &#39;updated_at&#39;], inplace=True)<br><br>        # Rename &#39;lat&#39; and &#39;lon&#39; in drivers_location<br>        self.drivers_location = self.drivers_location.rename(columns={&#39;lat&#39;: &#39;drivers_lat&#39;, &#39;lng&#39;: &#39;drivers_lon&#39;})<br><br>        # Merge DataFrames<br>        self.merged_df = self.completed_orders.merge(self.drivers_location, on=&#39;order_id&#39;, how=&#39;left&#39;)<br><br>        # Drop rows where &#39;driver_action&#39; is null<br>        self.merged_df.dropna(subset=[&#39;driver_action&#39;], inplace=True)<br><br>        # Handle missing values<br>        self._handle_missing_times()<br>        <br>        # Convert to datetime and extract time features<br>        self._convert_timestamps_and_extract_features()<br><br>        # Extract latitude and longitude<br>        self._extract_coordinates()<br><br>        # Convert column names to lowercase and replace spaces with underscores<br>        self.merged_df.columns = self.merged_df.columns.str.lower().str.replace(&#39; &#39;, &#39;_&#39;)<br><br>        return self.merged_df</pre><h3><strong>Causal Inference</strong></h3><p>Now that our data is preprocessed, we can start building our causal inference model. The goal is to uncover the underlying causal relationships that drive order fulfillment outcomes. We will use the causalnex library, a powerful tool for causal reasoning and discovery.</p><ul><li><strong>Constructing the Causal Graph:</strong> The first step is to construct a causal graph that represents our understanding of the relationships between the variables. Based on domain knowledge and intuition, we hypothesize that factors like the time of day, driver’s location, and trip distance might influence whether an order is fulfilled or not. We will construct a causal graph reflecting these relationships.</li><li><strong>Causal Discovery:</strong> To refine our causal graph, we will use causal discovery algorithms. These algorithms analyze the data to identify potential causal relationships and refine the graph structure. This step helps us uncover hidden dependencies and validate our initial assumptions.</li><li><strong>Intervention Analysis:</strong> After refining the causal graph, we will perform intervention analysis using do-calculus. This technique allows us to simulate the effect of changing a particular variable (e.g., driver location) while keeping other variables constant. This helps us understand the causal effect of that variable on the outcome (order fulfillment).</li><li><strong>Machine Learning Integration:</strong> We will integrate machine learning models with our causal inference framework. This will allow us to predict the outcome of deliveries under different scenarios and assess the robustness of our causal conclusions.</li></ul><p>Now that our data is preprocessed, we can start building our causal inference model using the causalnex library. The goal is to uncover the underlying causal relationships that drive order fulfillment outcomes.</p><h4>Causal Graph Construction and Discovery</h4><p>As outlined earlier, we begin by constructing a causal graph representing our hypothesized relationships between variables.</p><p>We can represent these relationships using a directed acyclic graph (DAG), where nodes represent variables and arrows indicate causal direction.</p><pre>from causalnex.structure import StructureModel<br>import networkx as nx<br><br>sm = StructureModel()<br><br># Add nodes to the graph<br>sm.add_node(&quot;Trip_Origin_latitude&quot;, type=FloatDtype())<br>sm.add_node(&quot;Trip_Origin_longitude&quot;, type=FloatDtype())<br>sm.add_node(&quot;Trip_Destination_latitude&quot;, type=FloatDtype())<br>sm.add_node(&quot;Trip_Destination_longitude&quot;, type=FloatDtype())<br>sm.add_node(&quot;hour_of_day&quot;, type=CategoricalDtype())<br>sm.add_node(&quot;trip_duration&quot;, type=FloatDtype())<br><br># Add edges to the graph<br>sm.add_edge(&quot;Trip_Origin_latitude&quot;, &quot;trip_duration&quot;)<br>sm.add_edge(&quot;Trip_Origin_longitude&quot;, &quot;trip_duration&quot;)<br>sm.add_edge(&quot;Trip_Destination_latitude&quot;, &quot;trip_duration&quot;)<br>sm.add_edge(&quot;Trip_Destination_longitude&quot;, &quot;trip_duration&quot;)<br>sm.add_edge(&quot;hour_of_day&quot;, &quot;trip_duration&quot;)<br><br># Visualize the graph<br>nx.draw_networkx(sm, with_labels=True, node_size=800, node_color=&quot;skyblue&quot;, font_size=10, font_color=&quot;black&quot;)</pre><p>Next, we refine this initial graph using the NOTEARS algorithm, a powerful causal discovery method. NOTEARS learns the structure of the causal graph directly from the data, potentially revealing relationships that were not captured in our initial assumptions.</p><pre>from causalnex.discovery import from_pandas<br><br># Learn the structure from the data<br>sm = from_pandas(merged_df_accepted_copy, tabu_parent_nodes=[&#39;trip_duration&#39;])</pre><h4>Visualization and Refinement</h4><p>To gain a visual understanding of the learned graph and identify potential areas for refinement, we visualize it using plot_structure and apply a threshold to remove weak edges:</p><pre>from causalnex.plots import plot_structure, NODE_STYLE, EDGE_STYLE<br><br>sm.remove_edges_below_threshold(0.8)  <br><br>viz = plot_structure(<br>    sm,<br>    all_node_attributes=NODE_STYLE.WEAK,<br>    all_edge_attributes=EDGE_STYLE.WEAK,<br>)<br><br>viz.toggle_physics(False)<br>viz.show(&quot;late_modified.html&quot;)</pre><p>This visualization will help us assess the relationships between variables and ensure that the graph aligns with our domain knowledge.</p><h4>Cardinality Reduction</h4><p>To simplify our analysis and improve the performance of causal inference algorithms, we may reduce the cardinality (number of unique categories) of some categorical variables. In our case, we will group the hour_of_day into two categories (&quot;morning&quot; and &quot;afternoon/night&quot;) and remap the is_weekend variable to be more descriptive.</p><pre># Create a copy of the DataFrame<br>discretised_data = merged_df_accepted_copy.copy()<br><br># Create mappings for categorization<br>driver_action_map = {v: v for v in discretised_data[&#39;driver_action&#39;].unique()}<br>hour_of_day_map = {v: &#39;morning&#39; if v &lt;= 12 else &#39;afternoon/night&#39; for v in discretised_data[&#39;hour_of_day&#39;].unique()}<br>is_weekend_map = {v: &#39;weekday&#39; if v == 0 else &#39;weekend&#39; for v in discretised_data[&#39;is_weekend&#39;].unique()<br><br># Apply the mappings<br>discretised_data[&quot;driver_action&quot;] = discretised_data[&quot;driver_action&quot;].map(driver_action_map)<br>discretised_data[&quot;hour_of_day&quot;] = discretised_data[&quot;hour_of_day&quot;].map(hour_of_day_map)<br>discretised_data[&#39;is_weekend&#39;] = discretised_data[&#39;is_weekend&#39;].map(is_weekend_map)</pre><h4>Intervention Analysis</h4><p>After refining our causal graph and adjusting variable cardinality, we can proceed with intervention analysis using do-calculus. We will simulate the effect of changing a driver’s location on trip duration, as an example:</p><pre>from causalnex.evaluation import compute_effect, random_model, interventional_model<br><br># Create random and interventional models<br>random_model = random_model(sm)<br>interventional_model = interventional_model(sm)<br><br># Set the intervention (e.g., move driver to a new location)<br>interventional_model.set_intervention(&quot;Trip_Origin_latitude&quot;, 6.55)  <br>interventional_model.set_intervention(&quot;Trip_Origin_longitude&quot;, 3.4)<br><br># Compute the causal effect on trip duration<br>effect = compute_effect(random_model, interventional_model, &quot;trip_duration&quot;)<br><br>print(effect)</pre><p>By systematically evaluating the effects of different interventions, we can gain valuable insights into the causal drivers of order fulfillment. This information can guide Gokada in making data-driven decisions to optimize driver placement and reduce unfulfilled requests.</p><h4><strong>Conclusion</strong></h4><p>This blog post has provided a glimpse into the world of causal inference and its application to Gokada’s delivery optimization problem. We have covered the initial steps of data preprocessing, exploratory data analysis, and the basic concepts of causal inference.</p><p>By understanding the causal relationships behind Gokada’s unfulfilled delivery requests, we can develop targeted interventions to improve the efficiency and reliability of their delivery service, ultimately enhancing customer satisfaction and driving business growth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c913cdbd77ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Precision RAG: Prompt Tuning For Building Enterprise Grade RAG Systems]]></title>
            <link>https://medium.com/@hillaryke/precision-rag-prompt-tuning-for-building-enterprise-grade-rag-systems-25263c35153f?source=rss-5307439e4de2------2</link>
            <guid isPermaLink="false">https://medium.com/p/25263c35153f</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Hillary kipkemoi]]></dc:creator>
            <pubDate>Sat, 08 Jun 2024 19:06:38 GMT</pubDate>
            <atom:updated>2024-06-11T04:20:31.569Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we explore the development of an AI-powered prompt tuning system for Retrieval Augmented Generation (RAG) systems in an enterprise setting. Retrieval Augmented Generation (RAG) systems are revolutionizing business knowledge access by combining information retrieval with language models, but their effectiveness hinges on crafting high-quality prompts. We’ll walk through the key steps involved in building such an enterprise RAG system, leveraging the LangChain framework and OpenAI’s language models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcC4Lts6Ubuh--SlqRfKPA.png" /><figcaption>Evaluating RAG with RAGAs — from openai cookbook examples</figcaption></figure><h4>Business objective</h4><p>PromptlyTech, a hypothetical innovative e-business specializing in AI-driven solutions, is on a mission to revolutionize how businesses interact with Large Language Models (LLMs) GPT-4. The company aims to streamline and enhance the use of these powerful models by automating the generation, evaluation, and ranking of prompts, a crucial aspect of prompt engineering.</p><p>As LLMs become more prevalent in various industries, the demand for efficient and effective prompt engineering has never been greater. By automating this process, PromptlyTech empowers businesses to harness the full potential of LLMs, improve decision-making, boost operational efficiency, and enhance customer experiences.</p><p><strong>The Business Challenge:</strong></p><p>Crafting effective prompts is a time-consuming and often expensive process, requiring significant expertise in both language and AI. For businesses, this can lead to bottlenecks in development, increased costs, and missed opportunities to fully leverage the potential of RAG systems. Moreover, suboptimal prompts can result in inaccurate or irrelevant answers, leading to user frustration and ultimately harming the bottom line.</p><p><strong>Key Services of Automatic Prompt Tuning:</strong></p><p>Automatic prompt tuning platforms offer a suite of services to revolutionize how businesses interact with Large Language Models (LLMs):</p><ol><li><strong>Automatic Prompt Generation:</strong> This service streamlines the creation of effective prompts, enabling businesses to efficiently utilize LLMs for generating high-quality, relevant content without the need for extensive manual effort or specialized expertise.</li><li><strong>Automatic Evaluation Data Generation:</strong> This service automates the generation of diverse test cases, ensuring comprehensive testing and identification of potential issues early in the development process. This significantly enhances the reliability and performance of LLM applications, leading to time and cost savings in quality assurance.</li><li><strong>Prompt Testing and Ranking:</strong> This service evaluates and ranks different prompts based on their effectiveness in generating desired outcomes. By ensuring chatbots and virtual assistants provide accurate and contextually relevant responses, this service improves user engagement and satisfaction, which are critical for business success.</li></ol><p><strong>Tech Stack</strong></p><p>To tackle this challenge head-on, we utilized various tools and technologies:</p><ul><li><strong>LangChain:</strong> A powerful framework for developing LLM applications, simplifying the integration of language models, prompt templates, and retrieval mechanisms.</li><li><strong>OpenAI’s GPT Models:</strong> Cutting-edge language models like GPT-4 and GPT-3.5-Turbo for generating prompts, answering queries, and evaluating responses.</li><li><strong>ChromaDB:</strong> A vector database for efficient storage and retrieval of documents based on their semantic meaning.</li><li><strong>Ragas:</strong> A Python library designed to evaluate Retrieval Augmented Generation (RAG) pipelines by providing a comprehensive suite of metrics for assessing the quality and relevance of generated answers.</li><li><strong>Python:</strong> A versatile programming language for implementing the logic of the prompt tuning system.</li><li><strong>Sentence Transformers:</strong> A library for generating sentence embeddings, which are numerical representations of text that capture semantic similarity.</li><li><strong>LangSmith (Optional):</strong> Used for experiment tracking and visualization, and custom metrics for specialized evaluation.</li></ul><h3>The implementation</h3><p><strong>Automating Prompt Engineering:</strong></p><p>Firstly, we want to define our constant variables in a separate variable so that it can be easy for us or someone else using the application to refine the variables easily instead of having to scroll through the specific files and directories to find them. So we’ll define them under the settings file app/misc/settings.py like this:</p><pre>from typing import Final<br>from langchain.chains.query_constructor.base import AttributeInfo<br><br>class Settings:<br>    TEMPERATURE_GET_PROMPT_WINNER: Final = 0<br>    NUMBER_OF_PROMPT_CANDIDATES: Final = 3<br>    # ELO Ranking System Settings<br>    ELO_RANK_INITIAL = 1000<br>    CREATE_TEST_CASES_SYSTEM_PROMPT = &quot;...&quot;<br>    PROMPT_CANDIDATES_GENERATION_SYSTEM_PROMPT &quot;..&quot;<br>    # ... continue with the variables definitions here</pre><h4>Generate test cases</h4><p>We need to create test cases so that we can use them to compare the differents prompts during evaluation and rank them.</p><p>First we define a model class that will be used to create the different test cases. It contains the attributes; scenario and expected output.</p><pre>class TestCase:<br>    def __init__(self, scenario, expected_output=None, id=None):<br>        self.scenario = scenario<br>        self.expected_output = expected_output<br>        self.id = id</pre><pre>human_message_prompt = &quot;&quot;&quot;<br>    Please generate {amount} diverse test cases for the following task:<br>    Task (task description): {task_description} <br>    Context: {context}<br>&quot;&quot;&quot;<br><br>def generate_test_cases(task_description, retriever, amount=3):<br>    &quot;&quot;&quot;Generates test cases using a language model based on the task description.&quot;&quot;&quot;<br>    llm_model = model_factory.get_chat_openai()<br>    context_docs = retriever.invoke(task_description)<br>    <br>    context_text = format_docs_to_text(context_docs)<br>    prompt_input_variables = {<br>        &quot;task_description&quot;: task_description, <br>        &quot;context&quot;: context_text,<br>        &quot;amount&quot;: amount<br>    }<br><br>    generated_text = generate_response_with_langchain(<br>        system_message_prompt=Settings.CREATE_TEST_CASES_SYSTEM_PROMPT,<br>        human_message_prompt=human_message_prompt,<br>        input_variables=prompt_input_variables,<br>        llm_model=llm_model<br>    )<br><br>    test_cases = []<br>    for case_str in generated_text.split(&quot;Scenario:&quot;):<br>        case_str = case_str.strip() # Ensure that there are no spaces <br>        if not case_str:<br>            continue<br>        try:<br>            scenario, expected_output = case_str.split(&quot;Expected output:&quot;, 1)<br>            test_cases.append(<br>                TestCase(scenario.strip(), expected_output.strip())<br>            )<br>        except ValueError:<br>            print(f&quot;Skipping malformed test case: {case_str}&quot;)  # Handle cases where &quot;Expected output:&quot; is missing<br><br>    return test_cases</pre><p>The code above generates test cases. It first fetches relevant documents related to the task description using the <em>retriever.invoke </em>method, then uses the language model (ChatOpenAI) to create diverse scenarios and expected outputs based on the retrieved documents and the task description. The generated test cases are then returned as a list of TestCase objects, ensuring each case is well-formed with both a scenario and an expected output.</p><h4>Automate generation of the prompt candidates</h4><p>After we’ve had the test cases, next is that we need to define a class to handle the generation of the different prompt candidates. These will be obtained from the question/task description user provided, context (which is based on the task description), and the test cases.</p><pre>import nest_asyncio<br>from typing import List<br>from app.test_cases.generate_test_cases import TEMPERATURE<br>from app.utils.chat_models import ModelFactory<br>from app.test_cases.models import TestCase<br><br>from app.misc import Settings<br>from app.utils.docs_utils import format_docs_to_text<br>from app.utils.langchain_utils import generate_response_with_langchain<br>TEMPERATURE = 0.9<br>model_factory = ModelFactory()<br>human_message_prompt = &quot;&quot;&quot;<br>    Test Cases: {formatted_test_cases_str}<br>    Task: {description}<br>    Context: {context_text}<br>    Number of prompts to generate: {num_prompt_candidates}.<br>&quot;&quot;&quot;<br>class PromptGenerator:<br>  def __init__(self, retriever, temperature: float = TEMPERATURE, model_name: str = None):<br>    self.model_name = model_name<br>    self.temperature = temperature<br>    self.retriever = retriever<br>    self.num_prompt_candidates = Settings.NUMBER_OF_PROMPT_CANDIDATES<br>    self.human_message_prompt = human_message_prompt<br>    self.llm_model = model_factory.get_chat_openai()<br>  def extract_prompts(self, response):<br>    lines = response.split(&quot;\n&quot;)<br>    prompts = [line.replace(&quot;Prompt: &quot;, &quot;&quot;).strip() for line in lines if line.startswith(&quot;Prompt: &quot;)]<br>    return prompts<br>  def generate_prompt_candidates(self, testcases: List[TestCase], task_description: str) -&gt; List[str]:<br>    &quot;&quot;&quot;Generates prompt candidates using a chat language model.&quot;&quot;&quot;<br>    # nest_asyncio.apply()<br>    formatted_test_cases_str = &quot;\n&quot;.join(<br>      [<br>        f&quot;Test case #{j+1}:\nScenario: {testcase.scenario}\nExpected output: {testcase.expected_output}&quot;<br>        for j, testcase in enumerate(testcases)<br>      ]<br>    )<br>    context_docs = self.retriever.invoke(task_description)<br>    context_text = format_docs_to_text(context_docs)<br>    prompt_input_variables = {<br>        &quot;description&quot;: task_description,<br>        &quot;context_text&quot;: context_text,<br>        &quot;num_prompt_candidates&quot;: self.num_prompt_candidates,<br>        &quot;formatted_test_cases_str&quot;: formatted_test_cases_str<br>    }<br>    response = generate_response_with_langchain(<br>        system_message_prompt=Settings.PROMPT_CANDIDATES_GENERATION_SYSTEM_PROMPT,<br>        human_message_prompt=self.human_message_prompt,<br>        input_variables=prompt_input_variables,<br>        llm_model=self.llm_model<br>    )<br>    prompts = self.extract_prompts(response)<br>    return prompts</pre><p>This is what the code above does</p><ul><li>The PromptGenerator combines the task description and test cases into a structured prompt.</li><li>This prompt is sent to a language model (e.g., GPT-4) , which generates several potential prompt candidates using LangChain.</li><li>The extract_prompts function is then used to extract only the relevant prompts from the response of the model.</li></ul><h4>Generating the answers</h4><p>With our test cases and prompt candidates defined, we can now define a function to generate answers for each prompt on each test case. This crucial step will allow us to evaluate the effectiveness of each prompt in retrieving and generating relevant information from our knowledge base given the test cases.</p><pre>from langchain_core.output_parsers import StrOutputParser<br><br>from langchain.prompts.chat import ChatPromptTemplate<br>from app.utils.chat_models import ModelFactory<br>from app.rag.vectorstore import VectorStore<br>from app.test_cases import TestCase<br>from app.utils.docs_utils import format_docs_to_text<br>ANSWER_GENERATION_TEMPERATURE = 0.7<br>model_factory = ModelFactory(<br>                    temperature=ANSWER_GENERATION_TEMPERATURE, <br>                    openai_model_name=&quot;gpt-3.5-turbo&quot;<br>                  )<br>def generate_answer(prompt_candidate: str, test_case: TestCase, retriever, model = None):<br>    &quot;&quot;&quot;Generates a response using the provided prompt and test case.&quot;&quot;&quot;<br>    prompt_template = ChatPromptTemplate.from_template(<br>    &quot;&quot;&quot;<br>        Use the following context to answer the question.<br>        If you don&#39;t know the answer, just say that you don&#39;t know, don&#39;t try to make up an answer.<br>        Context: {context}<br>        Question: {prompt_candidate}<br>        Scenario: {scenario}<br>        Answer:&quot;&quot;&quot;<br>    )<br>    context_docs = retriever.invoke(test_case.scenario)<br>    context_text = format_docs_to_text(context_docs)<br>    llm = model_factory.get_chat_openai()<br>    prompt_input_variables = {<br>        &quot;context&quot;: context_text, <br>        &quot;prompt_candidate&quot;: prompt_candidate, <br>        &quot;scenario&quot;: test_case.scenario<br>    }<br>    chain = prompt_template | llm | StrOutputParser()<br>    # Generate answer from RAG chain<br>    answer = chain.invoke(prompt_input_variables)<br>    return answer</pre><p>This is what the code above does:</p><ul><li><strong>Retrieves Context:</strong> Utilizes the retriever.invoke(testCase.scenario) function to fetch a list of relevant documents from the knowledge base that match the given test case scenario.</li><li><strong>Formats Context:</strong> Converts the retrieved documents into a single string (context_text) by concatenating the page_content of each document.</li><li><strong>Constructs Prompt:</strong> Creates a prompt_input_variables dictionary containing the formatted context_text, the prompt_candidate (the prompt being evaluated), and the test_case.scenario for additional context. This dictionary is then passed to a LangChain ChatPromptTemplate to create a structured prompt that will guide the language model.</li><li><strong>Generates Answer:</strong> The formatted prompt is passed to an LLM model which generates a response that addresses the question given the scenario from the test case. Note that the temperature of the LLM is adjusted by the variable ANSWER_GENERATION_TEMPERATURE to 0.7 (adjusted for creativity).</li></ul><h3>Prompt Evaluation and Ranking</h3><p>We now transition to the critical stage of evaluating and ranking the generated prompt candidates. This process will employ Monte Carlo simulations and the ELO rating system to determine the relative performance of each prompt in facilitating optimal RAG system information retrieval.</p><h4>Elo rating system</h4><p>The Elo rating system, originally developed for chess, is a method for calculating the relative skill levels of players in competitive settings. It’s named after its creator, Arpad Elo, a Hungarian-American physics professor.</p><p>In the context of prompt engineering, we can think of each prompt as a “player” in a competition to see which one produces the best results. When two prompts are compared (a “battle”), their ELO ratings are adjusted based on the outcome:</p><ul><li><strong>Win:</strong> The winning prompt gains Elo points, while the losing prompt loses points.</li><li><strong>Draw:</strong> Both prompts’ ratings remain relatively unchanged.</li></ul><p>Over time, this creates a ranking system where prompts that consistently outperform others will have higher ELO ratings. This allows us to dynamically identify and prioritize the most effective prompts for our RAG system.</p><p>The beauty of the ELO system is its adaptability. It’s not just for chess; it can be applied to any scenario where you need to compare and rank items based on their performance in paired comparisons. This makes it a perfect fit for our goal of automating prompt evaluation and optimization.</p><h4>The ElO Ranker class</h4><p>Below is the class that handles the prompt evaluation using the Monte Carlo matchmaking and Elo rating system. We’ll break the class down and explain the methods in the class in detail.</p><pre>class EloRanker:<br>  INITIAL_ELO_RANK = Settings.INITIAL_ELO_RANK<br>  SD = Settings.SD_ELO<br>  LEARNING_RATE = Settings.LEARNING_RATE<br>  BATTLE_VALUE = Settings.BATTLE_VALUE<br><br>  def __init__(self, task_description: str, prompt_candidates, test_cases: List[TestCase], retriever, model=None, embedding_model=None):<br>    self.task_description = task_description<br>    self.prompt_candidates = prompt_candidates<br>    self.test_cases = test_cases<br>    self.model = model<br>    self.embedding_model = embedding_model<br>    self.retriever = retriever<br>    self.elo_ranks = {prompt: self.INITIAL_ELO_RANK for prompt in self.prompt_candidates}<br>    self.sd = {prompt: self.SD for prompt in self.prompt_candidates}<br><br>  def expected_score(self, ratingA, ratingB):<br>    return 1 / (1 + 10 ** ((ratingA - ratingB) / 400))<br><br>  def update_elo(self, ratingA, ratingB, score1):<br>    # code goes here ...<br><br>  def run_monte_carlo(self, sample_amount):<br>    # code implementation goes heres ...<br><br>  def run_battle(self, candidateA, candidateB):<br>    # code goes here ...<br>  def run_simulation(self, num_battles, sample_amount):<br>    # code goes here ...<br><br>  def rank_prompts(self):<br>    # code goes here ...</pre><h4>Key points and functionality of the ELO Ranker class</h4><p><strong>Purpose:</strong> The EloRanker class is designed to evaluate and rank a set of prompt candidates based on their performance in a retrieval augmented generation (RAG) system. It uses the Elo rating system, a method for calculating the relative skill levels of players in zero-sum games (like chess), to assess the quality of prompts.</p><p><strong>Class configurations: </strong>These parameters configure the Elo rating system for evaluating prompts.</p><ul><li>INITIAL_ELO_RANK: This is the initial score assigned to each new prompt, assuming all prompts start with equal potential effectiveness.</li><li>SD: The initial standard deviation for the Elo rating, reflecting the uncertainty in the initial score.</li><li>LEARNING_RATE: A factor that controls how much the ELO rating changes after each battle, with higher values leading to faster adjustments.</li><li>BATTLE_VALUE: The importance of a single battle in the overall rating adjustment process.</li></ul><p><strong>Initialization:</strong> When you create an instance of EloRanker, you provide:</p><ul><li>task_description: A description of the task the user needs prompts for, or a question asked by user.</li><li>prompt_candidates: A list of prompt candidates to be evaluated.</li><li>test_cases: A list of TestCase objects, each containing a scenario and an expected output.</li><li>retriever: An for relevant information retrieval as context.</li><li>model (optional): A language model used for answer generation (if not provided, a default one will be used which is OpenAI gpt model).</li></ul><pre>def expected_score(self, ratingA, ratingB):<br>    return 1 / (1 + 10 ** ((ratingA - ratingB) / 400))</pre><p><strong>expected_score:</strong> This method above calculates the expected score (probability of winning) for a prompt in a head-to-head comparison with another prompt, based on their current ELO ratings.</p><pre>def update_elo(self, ratingA, ratingB, score1):<br>    expectedScoreA = self.expected_score(ratingB, ratingA)<br>    expectedScoreB = self.expected_score(ratingA, ratingB)<br><br>    roundValue = self.BATTLE_VALUE / len(self.test_cases)<br>    newRatingA = ratingA + roundValue * (score1 - expectedScoreA)<br>    newRatingB = ratingB + roundValue * (1 - score1 - expectedScoreB)<br><br>    return newRatingA, newRatingB</pre><p><strong>update_elo:</strong> This method above updates the ELO ratings of two prompts after a comparison, based on the actual outcome (win, loss, or draw) and the expected score. It also adjusts the standard deviation to reflect the increasing certainty in the prompt&#39;s performance over time.</p><pre>def run_monte_carlo(self, sample_amount):<br>    distribution = {candidate: 0 for candidate in self.prompt_candidates}<br><br>    for _ in range(sample_amount):<br>      samples = {candidate: random.gauss(self.elo_ranks[candidate], self.sd[candidate]) for candidate in self.prompt_candidates}<br>      winner = max(samples, key=samples.get)<br>      distribution[winner] += 1<br><br>    return distribution</pre><p><strong>run_monte_carlo:</strong> The above method performs a Monte Carlo simulation to estimate the performance of each prompt candidate. It simulates a number of battles between randomly selected prompts, with the selection probability weighted by their current ELO ratings. The simulation results in a distribution of &quot;wins&quot; for each prompt.</p><pre>def run_battle(self, candidateA, candidateB):<br>    console.print(f&quot;[green]Running battle between {candidateA} and {candidateB}&quot;)<br><br>    total_score = 0<br>    for test_case in self.test_cases:<br>      score = get_score(self.task_description, test_case, candidateA, candidateB, self.retriever)  # Use the imported function here<br>      total_score += score<br><br>    # Calculate the average score over all test cases<br>    avg_score = total_score / len(self.test_cases)<br><br>    newRatingA, newRatingB = self.update_elo(self.elo_ranks[candidateA], self.elo_ranks[candidateB], avg_score)<br><br>    self.elo_ranks[candidateA] = newRatingA<br>    self.elo_ranks[candidateB] = newRatingB<br><br>    self.sd[candidateA] = max(self.sd[candidateA] * self.LEARNING_RATE, 125)<br>    self.sd[candidateB] = max(self.sd[candidateB] * self.LEARNING_RATE, 125)</pre><p><strong>run_battle:</strong> This method mentioned above simulates a direct comparison (&quot;battle&quot;) between two prompts. For each test case:</p><ul><li>It obtains the answers generated by both prompts.</li><li>It calculates a score for each prompt using the get_score function (which likely compares the answers to the expected output of the test case).</li><li>It calculates an average score across all test cases and updates the ELO ratings and standard deviations of both prompts accordingly.</li></ul><pre>def run_simulation(self, num_battles, sample_amount):<br>    for _ in range(num_battles):<br>      distribution = self.run_monte_carlo(sample_amount)<br>      candidateA = max(distribution, key=distribution.get)<br>      distribution[candidateA] = 0  # Exclude the first candidate from the next selection<br>      candidateB = max(distribution, key=distribution.get)<br><br>      self.run_battle(candidateA, candidateB)</pre><p><strong>run_simulation:</strong> This method combines the Monte Carlo simulation and run_battle method. It runs a specified number of battles between randomly selected prompts, using the Monte Carlo simulation to guide the selection process.</p><pre>def rank_prompts(self):<br>    highest_rank = max(self.elo_ranks.values())<br>    ranked_prompts = [<br>        (<br>            prompt, <br>            int(self.elo_ranks[prompt]), <br>            int(self.elo_ranks[prompt] / highest_rank * 100)<br>        ) for prompt in self.prompt_candidates]<br>    <br>    ranked_prompts.sort(key=lambda x: x[1], reverse=True)<br>    return ranked_prompts</pre><p><strong>rank_prompts:</strong> This method sorts the prompt candidates by their final ELO ratings (in descending order) and calculates their performance percentage relative to the highest-ranked prompt.</p><h4>Using the Elo Ranker class to rank prompts</h4><p>The next thing is that we need to define a function to run the simulations and battle and perform the evaluation of the prompts against each other given the different test scenarios.</p><pre>from app.evaluation import EloRanker<br>from app.misc.settings import Settings<br><br>NUMBER_OF_BATTLES = Settings.NUMBER_OF_BATTLES<br>SAMPLE_AMOUNT = Settings.MONTE_CARLO_SAMPLE_AMOUNT<br><br>def rank_prompts_with_elo(task_description, prompt_candidates, test_cases, retriever, num_battles=NUMBER_OF_BATTLES, sample_amount=SAMPLE_AMOUNT):<br>  elo_ranker = EloRanker(task_description, prompt_candidates, test_cases, retriever)<br>  elo_ranker.run_simulation(num_battles, sample_amount)<br>  ranked_prompts = elo_ranker.rank_prompts()<br>  return ranked_prompts</pre><p>The function above allows customization of the ranking process by accepting num_battles (the number of battles to run) and sample_amount (the number of samples for Monte Carlo simulations). This flexibility enables users to balance the trade-off between the accuracy of the rankings and the computational cost of the simulation. Increasing the number of battles and sample amount can lead to more accurate rankings but may require more computational resources and time.</p><p>Finally the function returns list of tuples of the ranked prompts which will be displayed to the user, each of which contains the prompt candidate, its Elo rank, and optionally, the percentage effectiveness of the prompt candidate compared to other prompt candidates.</p><h3>Putting it all together</h3><p>Now let’s examine how to combine all these functions automate and rank the prompts and then display them to the user within our application.</p><p>We’ll define a function to do all the work from generation of prompts to returning ranked prompts.</p><pre>from app.test_cases import generate_test_cases<br>from app.rag.loaders.load_web_docs import load_docs_from_web<br>from app.evaluation import rank_prompts_with_elo<br>from app.prompts_generation import PromptGenerator<br><br>def generate_ranked_prompts(task_description):<br>  # print(task_description)<br>  # task_description = &quot;Write me prompts to find information about few shot learning&quot;<br>  # Here we generate test_cases and prompt_candidates<br>  retriever = load_docs_from_web()<br>  test_cases = generate_test_cases(task_description, retriever, 3)<br>  prompt_generator = PromptGenerator(retriever)<br>  prompt_candidates = prompt_generator.generate_prompt_candidates(test_cases, task_description)<br>  ranked_prompts = rank_prompts_with_elo(task_description, prompt_candidates, test_cases, retriever)<br>  <br>  return ranked_prompts</pre><p>This code automates the process of generating and ranking prompts for a Retrieval Augmented Generation (RAG) system. It first loads documents from the web, creates test cases based on a task description, then generates multiple prompt candidates using those test cases. Finally, it ranks these candidates based on their performance in a simulated battle, using the ELO rating system and comparison metrics like human judgment and embedding similarity, and returning them for display to the user.</p><h3>Looking at the User Interface</h3><p>Next is to design the user interface that allows users to input their task description or a question for their information retrieval for documents and they’ll get better ranked prompts from RAG system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksELnSo39iBBf8bRQkH52w.png" /><figcaption>User interface for automatic prompt generator</figcaption></figure><p>The image showcases an intuitive user interface designed to streamline the automatic prompt generation process.</p><ul><li>Users can effortlessly input their desired query or task in the provided text box. With a simple click of the “Generate Prompts” button, the system, powered by advanced language models, swiftly generates a list of potential prompts tailored to the user’s input.</li><li>Each prompt is accompanied by an optional percentage score, indicating its estimated effectiveness, and an ELO rating, reflecting its performance in comparison to other prompts.</li><li>This user-friendly interface empowers users to quickly identify and select the most promising prompts for their specific needs by allowing the to copy to clipboard.</li></ul><h3>Challenges encountered</h3><ol><li><strong>Cost of LLM Usage:</strong> The extensive utilization of large language models (LLMs) for prompt generation and evaluation incurs substantial costs, both in terms of API usage fees and computational resources. Balancing the breadth of prompt exploration with the need to manage expenses poses a significant challenge.</li><li><strong>Test Case &amp; Dataset Confusion:</strong> Confusion came in when clearly defining the distinction between test cases (scenarios to be used to evaluate the prompts) and the test dataset (collection of questions and their ground truths) for evaluating RAG system.</li><li><strong>Prompt Generation Quality:</strong> Crafting effective prompts that guide the language model to generate accurate, relevant, and concise answers can be difficult. The prompt needs to strike a balance between specificity and flexibility.</li><li><strong>Language Model Biases</strong>: Large language models can exhibit biases present in their training data, leading to potentially harmful or unfair outputs.</li><li><strong>Ground Truth Data Acquisition:</strong> Obtaining comprehensive and reliable ground truth answers for a wide range of test cases to enable effective automated evaluation and ranking.</li></ol><p>The complete code with the implementation is available on the <a href="https://github.com/hillaryke/Prompt-Tuning-Enterprise-RAG">GitHub repository</a>.</p><h3>Conclusion</h3><p>In conclusion, automating prompt tuning for enterprise RAG systems is a transformative step towards unlocking their full potential. By utilizing language models to generate diverse prompts and test cases, then employing ELO rankings and evaluation metrics like RAGAs and embedding similarity, businesses can significantly enhance the accuracy, relevance, and efficiency of their RAG systems. This approach not only streamlines development and reduces the need for manual expertise, but also enables continuous improvement and adaptation to evolving business needs.</p><h3>References</h3><ul><li><a href="https://github.com/langchain-ai/rag-from-scratch">RAG from scratch notebook resources by Lance Martin, a LangChain Engineer.</a></li><li><a href="https://www.youtube.com/watch?v=sVcwVQRHIc8&amp;t=1699s">Learn RAG From Scratch — Python AI Tutorial from a LangChain Engineer</a></li><li><a href="https://github.com/meistrari/prompts-royale">Prompt engineering by Prompts Royale</a>.</li><li><a href="https://doubletapp.medium.com/how-to-communicate-with-a-knowledge-base-in-natural-language-using-llm-to-create-such-a-system-and-ffb73003d5c4">How to communicate with a knowledge base using LLM</a></li><li><a href="https://deci.ai/blog/evaluating-rag-pipelines-using-langchain-and-ragas/">RAG Evaluation Using LangChain and Ragas</a>.</li><li><a href="https://docs.ragas.io/en/stable/concepts/testset_generation.html">Ragas synthetic test data generation.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25263c35153f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Finetuning for African Languages (Amharic Language)]]></title>
            <link>https://medium.com/@hillaryke/llm-finetuning-for-african-languages-amharic-language-d64db07400a0?source=rss-5307439e4de2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d64db07400a0</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llama-2]]></category>
            <dc:creator><![CDATA[Hillary kipkemoi]]></dc:creator>
            <pubDate>Sat, 01 Jun 2024 19:34:21 GMT</pubDate>
            <atom:updated>2024-06-03T08:06:11.098Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we’ll dive into our exciting journey of fine-tuning a language model specifically for Amharic, a widely spoken language in Ethiopia. We’ll explore how we’re leveraging cutting-edge techniques to revolutionize Amharic news headline generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*739ZyshY8Ax0hG1RfiW4gA.png" /></figure><h3>Business objective</h3><p>The business objective of this project is to improve AfroTech Solutions’ customer support services by using AI to generate text in Amharic, Swahili, and Yoruba. The aim is to create systems that can generate quick and relevant responses in these languages based on customer questions and past interactions. The success of this project is dependent on the technology’s strong capabilities in text embedding and generation for these languages. The plan is to collect large datasets for the language of focus, and fine-tune suitable open-source LLM models based on the collected data. The models will be further fine-tuned to deliver the business objective effectively.</p><h3>Project overview</h3><p><strong>Understanding LLMs and the Hugging Face Ecosystem (Task 1 &amp; 2)</strong></p><p>The initial tasks focused on building a solid foundation in LLM concepts and the Hugging Face ecosystem. We delved into topics like:</p><ul><li>LLM architectures (encoder-only, decoder-only, encoder-decoder)</li><li>Transformer architecture and self-attention mechanisms.</li><li>Embedding techniques (tokenization, positional encoding)</li><li>Fine-tuning approaches (supervised, parameter-efficient)</li><li>Introduction to Hugging Face Hub, Transformers library, and chat model templates</li></ul><p>We then set up a GPU-enabled environment where we were provided with AWS instances enabled with Nvidia GPUs, then explored the Hugging Face Hub, and experimented with pre-trained LLMs like Llama 2–7B and Mixtral-8x7B. This hands-on exploration solidified our understanding of LLM functionalities and their potential for diverse tasks.</p><p><strong>Data Preprocessing and Preparation (Task 3)</strong></p><p>The importance of data quality for successful LLM fine-tuning was emphasized. We explored resources like “Llama-2-Amharic: LLMs for Low Resource Languages” to understand Amharic data preparation steps. Specific tasks included:</p><ul><li>Handling special characters and diacritics specific to Amharic, Swahili, and Yoruba languages</li><li>Eliminating irrelevant content and non-language text (e.g., HTML tags)</li></ul><p><strong>Fine-Tuning the LLM (Task 4)</strong></p><p>This was the core challenge, involving the actual fine-tuning process. We learned about different fine-tuning approaches based on the chosen language and available resources. Here’s a breakdown of resources for each language:</p><p><strong>Amharic:</strong></p><ul><li>Garri Logistics model (iocuydi/amharic-llama-llava)</li><li>Hugging Face alignment handbook scripts and documentation</li></ul><p>Following the provided instructions (e.g., downloading models, adjusting scripts), I fine-tuned a chosen LLM for my assigned language. This involved:</p><ol><li>Data Preprocessing: Cleaning and preparing the collected data for the specific LLM format.</li><li>Model Selection: Choosing a suitable base LLM based on factors like model size and computational resources.</li><li>Fine-tuning: Training the LLM on the prepared data to improve its performance on specific tasks related to customer support.</li><li>Evaluation: Testing the fine-tuned model’s ability to generate relevant and accurate responses in the chosen language.</li></ol><h4>Enhanced Web Scraping Process</h4><p>In our previous week, we laid the groundwork for fine-tuning language models by collecting data through web scraping. This week, we elevated our data pipeline to the next level.</p><p>Here we introduced a real-time, scalable system that not only scrapes data but also efficiently processes and stores it, ensuring a seamless flow for our Amharic language models.</p><p><strong>Steps:</strong></p><ol><li><strong>Web Scraping:</strong> Our scraper remains the initial workhorse, diligently extracting relevant text data from various online sources. However, instead of directly saving this data, it sends it to a Kafka topic.</li><li><strong>Kafka Messaging:</strong> Kafka acts as a high-throughput, distributed messaging system. It serves as the central messaging service for our data, reliably receiving the scraped article from the scraper.</li><li><strong>Faust Stream Processing:</strong> Faust, a stream processing library built on Kafka Streams, steps in to analyze and transform the incoming data. We’ve implemented Faust agents that cleans and preprocesses the texts in the article, ensuring it aligns with the requirements of our language models.</li><li><strong>MongoDB Storage:</strong> Faust seamlessly integrates with MongoDB, a NoSQL database, to store the processed data.</li></ol><h4>Data Cleaning and Preprocessing with Faust</h4><p>Now that our scraped data is flowing into Kafka, we need to get it ready for the language models. This is where Faust, our stream processing tool comes in. Faust goes through each article from the Kafka topic and processes it.</p><p>The preprocessing pipeline involves several functions from the Normalize class, which is then used in the ArticleProcessor class defined our custom defined data_cleaning python module. These include:</p><ol><li>clean_data<strong>:</strong> This orchestrates the main preprocessing steps.</li><li>remove_ascii_and_numbers<strong>:</strong> Eliminates ASCII characters and numbers.</li><li>remove_punc_and_special_chars<strong>:</strong> Removes punctuation and special characters.</li><li>normalize_char_level_missmatch<strong>:</strong> Standardizes Amharic character variations.</li><li>normalize_multi_words<strong>:</strong> Identifies and combines frequent word pairs.</li></ol><p>These functions work together to transform raw scraped Amharic text into a cleaner, standardized format, ready for further processing and language model fine-tuning.</p><p>Below is the code for Faust to implement the preprocessing functions.</p><pre>import faust<br>import os<br><br>from datetime import datetime<br>from models import ScrapedNews<br>from data_cleaning.article_processor import ArticleProcessor<br><br>KAFKA_BROKER_URL = os.getenv(&#39;KAFKA_BROKER_URL&#39;, &#39;kafka://localhost:9094&#39;)<br><br>app = faust.App(&#39;myapp&#39;, broker=KAFKA_BROKER_URL)<br>scraped_data_topic = app.topic(&#39;scraping&#39;, value_type=ScrapedNews)<br><br># create a MongoDB instance (for saving the data after processing)<br>clean_db = MongoDB(db_name=&quot;clean_data&quot;, collection_name=&quot;alain_news_clean&quot;, connection_string=&quot;mongodb://localhost:27017/&quot;)<br>archive_db = MongoDB(db_name=&quot;archive&quot;, collection_name=&quot;alain_news_archive&quot;, connection_string=&quot;mongodb://localhost:27017/&quot;)<br><br>@app.agent(scraped_data_topic)<br>async def save_raw_news(scraped_data):<br>  # Initialize the ArticleProcessor<br>  processor = ArticleProcessor(archive_collection=archive_db, cleaned_collection=clean_db, columns_to_process=[&#39;content&#39;, &#39;title&#39;, &#39;summary&#39;])<br><br>  async for data in scraped_data:<br>    # Convert the data to a dictionary<br>    data_dict = data.asdict()<br><br>    # Check if data_dict is not None before processing it<br>    if data_dict is not None:<br>      # Process the data using the ArticleProcessor<br>      processed_data = processor.process_article(data_dict)<br><br>      # Check if processed_data is not None before saving it to MongoDB<br>      if processed_data is not None:<br>        # Save the processed data to MongoDB<br>        mongodb.insert_content(processed_data)<br><br>if __name__ == &#39;__main__&#39;:<br>    app.main()</pre><p>Below is an sample displayed by Faust Stream processing library, showing the original text and the preprocessed text using the mentioned functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8sFAVgZUksHq5cg0yG0gg.png" /><figcaption>The original text is on top and the preprocessed text below.</figcaption></figure><h3>Finetuning the LLM model</h3><p>We agreed on fine-tuning our chosen LLM model to generate news headlines in Amharic language given the news category.</p><h4>Preparing for the Fine-Tuning Process</h4><p>Having our preprocessed raw data saved in Mongodb, we now need load and to format our Amharic data into a well-structured format, to be ready and in perfect shape to fine-tune a language model specifically for generating Amharic news headlines based on category input.</p><p><strong>Data Loading and Preparation:</strong></p><pre># Connect to MongoDB<br>db_name = &#39;clean_data&#39;<br>collection_name = &#39;kaggle_amharic_corpus_cleaned&#39;<br>connection_string = &#39;mongodb://localhost:27017/&#39;<br><br>clean_db = MongoDB(db_name=db_name, collection_name=collection_name, connection_string=connection_string)</pre><p>Here, we establish a connection to our MongoDB database where the preprocessed Amharic news articles reside.</p><pre># Load data into a pandas DataFrame<br>df = pd.DataFrame(list(clean_db.collection.find()))</pre><p>The cleaned articles are loaded from MongoDB into a Pandas DataFrame for easy manipulation and analysis.</p><h4>Dataset preparation and creation</h4><pre>df_subset = df[[&#39;category&#39;, &#39;title&#39;]]</pre><p>We narrow down our dataset to the essential columns: category (for the news type) and content (the article title or headline in this case). Additionally, we drop any rows with missing values.</p><pre>def preprocess(df, max_words):<br>    df[&#39;category&#39;] = df[&#39;category&#39;].apply(lambda x: &#39; &#39;.join(x.split()[:max_words]))<br>    df = df.dropna()<br>    return df</pre><p>The preprocess function is applied to further refine the data. It truncates the category labels to a maximum number of words, ensuring consistency in the input length for the model.</p><h4>Defining custom Dataset class</h4><pre>class MyDataset(Dataset):<br>    def __init__(self, df, tokenizer):<br>        self.df = df<br>        self.tokenizer = tokenizer<br><br>    def __len__(self):<br>        return len(self.df)<br><br>    def __getitem__(self, idx):<br>        row = self.df.iloc[idx]<br>        text = row[&#39;title&#39;]<br>        labels = row[&#39;category&#39;]<br>        encoding = self.tokenizer.encode_plus(<br>            text,<br>            truncation=True,<br>            padding=&#39;max_length&#39;,<br>            max_length=512,<br>            return_tensors=&#39;pt&#39;<br>        )<br>        encoding[&#39;labels&#39;] = torch.tensor([labels])<br>        return encoding</pre><p>This code snippet defines a custom PyTorch Dataset class, which is used to load and prepare the data for training. It takes the DataFrame (df) and the tokenizer as input. The __getitem__ method allows the model to access individual samples (title and category) during training.</p><p><strong>Model Selection and Preparation:</strong></p><pre>model_garri = &quot;iocuydi/llama-2-amharic-3784m&quot;<br>commit_hash = &quot;04fcac974701f1dab0b8e39af9d3ecfce07b3773&quot;<br>tokenizer = LlamaTokenizer.from_pretrained(model_garri, revision=commit_hash)</pre><p>These lines load the LlamaTokenizer from the pre-trained Garri Logistics model and the base LlamaForCausalLM model from HuggingFace hub.</p><p>The model is loaded in 8-bit mode (load_in_8bit=True), which is a quantization technique that reduces the model&#39;s memory footprint, making it possible to train and run on less powerful hardware.</p><p>device_map=&quot;auto&quot; automatically distributes the model across available GPUs or TPUs, and trust_remote_code=True is a security setting that allows the model to execute code from the model repository.</p><pre>model_llama = LlamaForCausalLM.from_pretrained(<br>    model_name_llama2_7b, <br>    load_in_8bit=True,<br>    device_map=&quot;auto&quot;,<br>    trust_remote_code=True,<br>    # cache_dir= cache_dir, # optional<br>)</pre><p><strong>Lora Configuration and Application:</strong></p><pre># Define lora configuration<br>lora_config = LoraConfig(<br>    task_type=TaskType.CAUSAL_LM,<br>    inference_mode=False,<br>    r=8,<br>    lora_alpha=32,<br>    lora_dropout=0.05,<br>    target_modules = [&quot;q_proj&quot;, &quot;v_proj&quot;, &quot;k_proj&quot;],<br>    modules_to_save = [&quot;embed_tokens&quot;,&quot;lm_head&quot;]<br>)</pre><p>Lora (Low-Rank Adaptation) is a technique for parameter-efficient fine-tuning of large language models. It reduces the number of trainable parameters, making fine-tuning faster and requiring less memory. Here, we configure LoRA for causal language modeling (predicting the next word in a sequence)</p><p>We then applied the Lora configuration to our base model as follows.</p><pre>model = get_peft_model(model, lora_config)</pre><p><strong>Training and Deployment:</strong></p><pre>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=train_dataset,<br>    data_collator=default_data_collator,<br>    callbacks=[profiler_callback] if enable_profiler else [],<br>)<br><br>trainer.train()</pre><p>This section defines the training arguments (training_args) like output_dir for storing the trained model and logging_dir for storing logs and passing in our training and test sets. A Trainer instance is then created, passing in the PEFT model, training arguments, and datasets. Finally, the trainer.train() method initiates the fine-tuning process.</p><p>By meticulously executing these steps, we create a customized language model ready to generate captivating and contextually appropriate Amharic news headlines, a valuable asset for any news outlet or content creator working in the Amharic language.</p><p><strong>Challenges encountered</strong></p><ul><li>Successfully executing the model posed a significant challenge due to a series of errors that emerged sequentially. Each error resolution led to the uncovering of a new issue, necessitating a deep and comprehensive understanding of the underlying problems.</li><li><strong>Data Scarcity:</strong> Working with low-resource languages like Amharic and Yoruba presented challenges in terms of data availability. Techniques like transfer learning and leveraging existing resources became crucial.</li><li><strong>Computational Resources:</strong> Fine-tuning large models requires significant computational power. Exploring efficient fine-tuning methods like PEFT (Parameter-Efficient Fine-Tuning) proved valuable.</li></ul><p><strong>Looking Forward</strong></p><p>This challenge provided a comprehensive experience in LLM fine-tuning for African languages. The skills acquired will be invaluable in contributing to the development of multilingual AI solutions that cater to the diverse needs of African customers.</p><p><strong>Next Steps</strong></p><ul><li>Further explore advanced fine-tuning techniques like instruction fine-tuning for improved control over generated text.</li><li>Experiment with different LLM architectures and evaluate their suitability for specific African languages.</li><li>Integrate the fine-tuned LLMs into a real-world application like a chatbot or customer support system.</li></ul><p>This blog post offers a glimpse into my journey through Week 6 of the 10 Academy Cohort B challenge. The experience has been enriching, and I’m excited to continue exploring the potential of LLMs for positive impact in Africa.</p><h3>References</h3><ul><li><a href="https://huggingface.co/docs/datasets/en/create_dataset">Creating a Hugging Face Dataset</a>.</li><li><a href="https://medium.com/analytics-vidhya/how-self-attention-works-in-transformer-6c76a12396b0">How attentions work in Transformer.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d64db07400a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable Data Warehouse for LLM Finetuning: API Design for High Throughput Data Ingestion and RAG…]]></title>
            <link>https://medium.com/@hillaryke/scalable-data-warehouse-for-llm-finetuning-api-design-for-high-throughput-data-ingestion-and-rag-f129130f71b3?source=rss-5307439e4de2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f129130f71b3</guid>
            <dc:creator><![CDATA[Hillary kipkemoi]]></dc:creator>
            <pubDate>Sat, 25 May 2024 19:53:42 GMT</pubDate>
            <atom:updated>2024-05-27T08:59:55.779Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scalable Data Warehouse for LLM Finetuning: API Design for High Throughput Data Ingestion and RAG Retrieval</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBh8p6keDh4XKlTee6MrBw.png" /><figcaption>Process flow chart made with Figma</figcaption></figure><p><strong>Business Objective</strong></p><p>Roots Tech Solutions, a leading technology company, aims to expand its Natural Language Processing (NLP) capabilities to cater to the growing demand for African language understanding. The company envisions developing a range of NLP applications such as chatbots, content generators, sentiment analyzers, and speech recognition tools tailored for Swahili, Yoruba, and Amharic. To achieve this, Roots Tech Solutions requires a robust and scalable data pipeline that can efficiently collect, process, and provide access to high-quality language data for these languages. This data pipeline will serve as the foundation for training and fine-tuning NLP models, ultimately enabling the development of cutting-edge applications that cater to the linguistic diversity of Africa. In this case we focused on the Amharic language as the starting point.</p><p><strong>Project Design</strong></p><p>The project followed a modular design, dividing the pipeline into distinct stages:</p><ol><li><strong>Data Collection:</strong> Targeted Amharic text data from online sources and social media platforms like Telegram channels.</li><li><strong>Data Cleaning:</strong> Processed raw data to remove noise and irrelevant content.</li><li><strong>API Development:</strong> Created an interface for easy access to the cleaned data.</li><li><strong>Data warehouse Integration. </strong>We used MongoDB to store the processed data.</li><li><strong>Frontend Development:</strong> Developed a user interface to interact with the API.</li><li>Automation &amp; deployment.</li></ol><p>This modularity allows for easier maintenance, scalability, and potential integration of additional components in the future.</p><p><strong>Methodologies</strong></p><ul><li><strong>Web Scraping:</strong> Employed BeautifulSoup and Selenium to extract Amharic text data from news websites and social media platforms like telegram. Due to architectural constraints, Firefox was used with Selenium on ARM-based AWS instances.</li><li><strong>Data Cleaning:</strong> Python scripts were developed to normalize text, remove HTML tags, special characters, and filter out non-Amharic content. Specific attention was given to handling Amharic characters and punctuation.</li><li><strong>API Development:</strong> FastAPI was utilized to create RESTful APIs with endpoints for searching, filtering, and retrieving the processed Amharic text data. The API design focused on providing a simple and efficient interface for developers to access the language data.</li><li><strong>Frontend Development:</strong> React was used to build an interactive user interface that allows users to query the API and visualize the retrieved Amharic text data.</li></ul><p><strong>Tech Stack</strong></p><ul><li><strong>Web Scraping:</strong> BeautifulSoup, Selenium (with Firefox), Scrapy</li><li><strong>Data Storage:</strong> MongoDB</li><li><strong>Data Processing:</strong> Python</li><li><strong>API Development:</strong> FastAPI</li><li><strong>Automation:</strong> Apache Airflow</li><li><strong>Stream Processing (Planned):</strong> Faust</li><li><strong>Data Annotation (Planned):</strong> Prodigy</li><li><strong>Containerization:</strong> Docker</li><li><strong>Monitoring (Planned):</strong> Prometheus, Grafana</li><li><strong>CI / CD: </strong>Github Actions</li><li><strong>Testing:</strong> Jest (frontend), Pytest (backend and database testing)</li></ul><h4>Webscraping using BeautfulSoup (BBC News Amharic website)</h4><p>In this project, we implemented a web scraper to extract news articles from the BBC Amharic website. This outline involved several steps, including setting up the web scraper, extracting the data, and storing the data in a MongoDB database.</p><p>The web scraper was designed to navigate to the BBC Amharic website, specifically the page that lists all the articles. It then extracted the relevant information from each article, such as the title, date, text, and image url. The methods to do this were implemented on the <strong>Article</strong> Python class.</p><p>The Article class is responsible for web scraping the BBC Amharic website. It is initialized with a base URL and a prefix, which are used to construct the full URLs of the articles. Here&#39;s a brief explanation of the class with some of the most crucial methods:</p><pre>class Article:<br>  def __init__(self, base_url, prefix):<br>      self.base_url = base_url<br>      self.prefix = prefix<br>      self.soup = self.get_soup(base_url)<br><br>  def get_soup(self, url):<br>    response = requests.get(url)<br>    return BeautifulSoup(response.text, &#39;html.parser&#39;)<br><br>  def get_article_urls(self):<br>      # Find all &#39;a&#39; elements<br>      a_elements = self.soup.find_all(&#39;a&#39;)<br><br>      # Extract the href attribute from each &#39;a&#39; element<br>      urls = [a[&#39;href&#39;] for a in a_elements if a.has_attr(&#39;href&#39;)]<br><br>      # Filter out URLs that don&#39;t start with the specified prefix<br>      filtered_urls = [url for url in urls if url.startswith(self.prefix)]<br><br>      return filtered_urls<br>  <br>  def get_title(self, soup):<br>    # Replace with the actual method to extract the title<br>    title_element = soup.select_one(&#39;title&#39;)<br>    return title_element.text if title_element else None<br><br>  def get_date(self, soup):<br>    # Replace with the actual method to extract the date<br>    date_element = soup.select_one(&#39;date&#39;)<br>    return date_element.text if date_element else None<br><br>  def get_content(self, soup):<br>    p_elements = soup.select(&#39;p&#39;)<br>    return &#39; &#39;.join(p.text for p in p_elements)</pre><p>In the get_articles method, the scraper navigates to the base URL and extracts the relative URLs of the articles. It then constructs the full URLs of the articles by appending the relative URLs to the base URL and prefix.</p><p>The get_date, get_title, and get_content methods are responsible for extracting the date, title, and content of an article, respectively. These methods use BeautifulSoup to parse the HTML of the article and extract the relevant information.</p><h4>Scraping data from telelgram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4x3Gt4-sfG0ob1CNx0onQ.png" /></figure><h4><strong>Saving the processed Amharic data and Retrieval from database</strong></h4><p>The database implementation for this project was done using MongoDB, a NoSQL database. The MongoDB database was interacted with using a Python class that we named <em>MongoDB</em>.</p><p>The <em>MongoDB</em> class was designed to handle all interactions with the MongoDB database. It was initialized with the database name and collection name, which could be provided as arguments or set as environment variables.</p><p>The class had several methods to interact with the database but the most crucical methods were these:</p><ul><li><strong><em>insert_content(content, collection_name)</em></strong>: This method was used to insert a new document into the specified collection.</li><li><strong><em>get_all_content_as_list(filter_col, collection_name)</em></strong>: This method returned the results as a list and was useful when used with the api to get Amharic data for the frontend request.</li></ul><p>The `MongoDB class was used in the web scraping script to save the scraped articles to the MongoDB database. Each article was inserted as a separate document in the ‘articles’ collection.</p><h4>Unit Testing for the database methods</h4><p>Unit tests for the <strong><em>MongoDB</em></strong> class were written in the <strong><em>test_mongodb.py</em></strong> file. The tests were designed to verify the functionality of each method in the `MongoDB` class.</p><p>A mock MongoDB database was used for the tests to avoid modifying the actual database. The mock database was created using the `mongomock` library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oTLTnWiZ73Ue3HwWYf98GA.png" /><figcaption>Mock MongoDB database for tests</figcaption></figure><p>Each method in the <strong><em>MongoDB</em></strong> class had a corresponding test method in the <strong><em>TestMongoDB</em></strong> class. The tests inserted mock data into the mock database and then verified the functionality of the methods by comparing the returned results with the expected results.</p><h4>SSH Port Forwarding</h4><p>SSH port forwarding was used to securely connect to the MongoDB server. This was done by forwarding a local port to the port on the remote server where the MongoDB server was running.</p><h4>Data Retrieval</h4><p>The data retrieved from the API was saved to the MongoDB database using the <strong><em>insert_content</em></strong> method of the <strong><em>MongoDB</em></strong> class. Each article was inserted as a separate document in the ‘articles’ collection.</p><p>The data could then be retrieved from the database using the <strong><em>get_content</em></strong>, <strong><em>get_all_content,</em></strong> and <strong><em>get_all_content_as_list</em></strong> methods of the <strong><em>MongoDB</em></strong> class. These methods returned the documents from the ‘articles’ collection that matched the provided filter.</p><p>This is how the data looked like after saving it mongodb (We used MongoDB Compass to visualize the database)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDGBRf7XdcRBVTFEqUrWNw.png" /></figure><h3>FastAPI Implementation</h3><p>FastAPI was used to create an API endpoint for retrieving the data from the MongoDB database. The endpoint was defined in the main.py file inside the api folder.</p><p>The get_content endpoint was defined as an asynchronous function. It used the get_all_content_as_list method of the MongoDB class to retrieve all documents from the &#39;articles&#39; collection in the MongoDB database. The other implementation was to get filtered content whenever the user needs it. The documents were returned as a list.</p><p>The ObjectId of each document was converted to a string to make it JSON serializable. The documents were then returned as a JSON response.</p><p>Here is the code for the get_content endpoint:</p><pre>@app.get(&quot;/api/content&quot;)<br>async def get_content():<br>    # Get content from MongoDB<br>    content = mongo.get_all_content_as_list()<br><br>    # Convert ObjectId to string<br>    for item in content:<br>        item[&quot;_id&quot;] = str(item[&quot;_id&quot;])<br><br>    return { &quot;content&quot;: content }</pre><h4>Unit Testing for FastAPI endpoints</h4><p>Unit tests for the FastAPI endpoints were written in the test_main.py file. The tests were designed to verify the functionality of each endpoint.</p><p>The test_get_content test sent a GET request to the /api/content endpoint and checked the status code of the response to verify that the request was successful. It also checked the content of the response to verify that it matched the expected content.</p><p>The test_say_hello test sent a GET request to the /hello/{name} endpoint and checked the status code of the response to verify that the request was successful. It also checked the content of the response to verify that it matched the expected content.</p><pre>def test_get_content():<br>    response = client.get(&quot;/api/content&quot;)<br>    assert response.status_code == 200<br>    assert response.json() == {<br>        &quot;content&quot;: &quot;content&quot;<br>    }<br><br>def test_say_hello():<br>    name = &quot;peter&quot;<br>    response = client.get(f&quot;hello/{name}&quot;)<br>    assert response.status_code == 200<br>    assert response.json() == {<br>        &quot;message&quot;: f&quot;Hello {name}&quot;<br>    }</pre><p>The test_get_content test currently checks if the response content is the string &quot;content&quot;, which is not the expected content. We plan on updating the test to check if the response content is a list of documents from the &#39;articles&#39; collection in the MongoDB database.</p><h3>Stream processing using Faust and Kafka</h3><p>Faust and Kafka are powerful tools that we’ve used for stream processing in the project. Kafka is a distributed streaming platform which we’ll use for message queue (it uses topics), while Faust is a Python stream processing library.</p><p><strong>Setting Up Kafka and Faust</strong></p><ul><li>In our docker-compose.yaml file, wedefined services for both Kafka and Faust. For Kafka, wespecified the Docker image, ports, and environment variables for configuration. For Faust, wespecified the build context, dependencies, environment variables, and ports.</li></ul><p><strong>Configuring Kafka</strong></p><ul><li>We configured Kafka to listen on two different ports, 9092 and 9093, for internal and external communication respectively. We also set up a connection to Zookeeper, which Kafka uses for maintaining cluster state.</li></ul><p><strong>Creating Kafka Topics</strong></p><ul><li>We used the KAFKA_CREATE_TOPICS environment variable to create a Kafka topic named &quot;my-topic&quot; with one partition and a replication factor of one.</li></ul><p><strong>Building a Faust Application</strong></p><ul><li>We built a Faust application located in the ./faust directory. The application depends on Kafka, as specified in the depends_on field.</li></ul><p><strong>Connecting Faust to Kafka</strong></p><ul><li>We connected the Faust application to Kafka using the KAFKA_BROKER_URL environment variable. This tells Faust where to find the Kafka broker.</li></ul><pre>services:<br>  zookeeper:<br>    image: wurstmeister/zookeeper:latest<br>    ports:<br>      - &quot;2181:2181&quot;<br><br>  kafka:<br>      image: wurstmeister/kafka:latest<br>      ports:<br>        - &quot;9092:9092&quot;<br>        - &quot;9093:9093&quot;<br>      environment:<br>        KAFKA_ADVERTISED_LISTENERS: INSIDE://kafka:9092,OUTSIDE://localhost:9093<br>        KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT<br>        KAFKA_LISTENERS: INSIDE://0.0.0.0:9092,OUTSIDE://0.0.0.0:9093<br>        KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE<br>        KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>        KAFKA_CREATE_TOPICS: &quot;my-topic:1:1&quot;<br>      volumes:<br>        - /var/run/docker.sock:/var/run/docker.sock<br><br>  faust:<br>    build: ./faust<br>    depends_on:<br>      - kafka<br>    environment:<br>    - KAFKA_BROKER_URL=kafka://kafka:9092<br><br>    ports:<br>      - &quot;6068:6066&quot;</pre><h4>Faust stream processing</h4><p><strong>Creating a Kafka Topic in Faust</strong></p><ul><li>We created a Kafka topic named ‘scraped_data’ in my Faust application. This topic is used to receive data that needs to be processed.</li></ul><p><strong>Processing Data with Faust</strong></p><ul><li>We defined a Faust agent named process_data that subscribes to the &#39;scraped_data&#39; topic. This agent receives data from the topic, processes it (in this case, converting the URL to uppercase), and then saves it to MongoDB.</li></ul><p>NOTE: We did not actually process the data since we ran out of time, but we plan to perform the preprocessing before saving it to the database.</p><pre>import faust<br>import os<br><br>from database import MongoDB<br><br>from datetime import datetime<br>from models import ScrapedData<br><br>KAFKA_BROKER_URL = os.getenv(&#39;KAFKA_BROKER_URL&#39;, &#39;kafka://localhost:9093&#39;)<br><br>MONGODB_CONNECTION_STRING = &#39;mongodb://mongodb:27017/&#39;<br><br>app = faust.App(&#39;myapp&#39;, broker=KAFKA_BROKER_URL)<br>scraped_data_topic = app.topic(&#39;scraped_data&#39;, value_type=ScrapedData)<br><br># create a MongoDB instance (for saving the data after processing)<br>mongodb = MongoDB(&#39;bbc_news&#39;, &#39;scraped_data&#39;, MONGODB_CONNECTION_STRING)<br><br>@app.agent(scraped_data_topic)<br>async def process_data(scraped_data):<br>  async for data in scraped_data:<br>    # HERE WE PREPROCESS THE DATA<br>    # For now we&#39;ll just convert the title to uppercase<br><br>    # convert the title to uppercase<br>    data.url = data.url.upper()<br>    list_data = [data.to_dict()]<br><br>    # Save the data to MongoDB<br>    mongodb.insert_content(data.to_dict())<br>    # print(type(data))<br><br>    print(list_data)<br><br>if __name__ == &#39;__main__&#39;:<br>    app.main()</pre><h3>Prometheus and grafana for visualization</h3><p>Prometheus and Grafana are powerful tools that we used for monitoring and visualizing metrics in the project. These tools are instrumental in helping us understand the performance of our applications.</p><p><strong>Setting Up Prometheus and Grafana</strong></p><ul><li>We set up Prometheus and Grafana using Docker Compose. In our compose.yaml file, we defined services for both tools, specifying the Docker images, ports, and volumes for data storage.</li></ul><p><strong>Prometheus Configuration</strong></p><ul><li>We configured Prometheus to scrape metrics from my services using the prometheus.yml file. This file is crucial as it tells Prometheus where to collect metrics from.</li></ul><p><strong>Using Exporters</strong></p><ul><li>We used exporters to expose metrics to Prometheus. For instance, weused the MongoDB exporter to expose MongoDB metrics. The exporter collects metrics from MongoDB and exposes them on an HTTP endpoint for Prometheus to scrape.</li></ul><p><strong>Visualizing Metrics with Grafana</strong></p><ul><li>We connected Grafana to Prometheus as a data source and created dashboards to visualize the data. This gave us a clear, visual understanding of my application’s performance.</li></ul><pre>services:<br>  grafana:<br>    image: grafana/grafana<br>    container_name: grafana<br>    restart: unless-stopped<br>    ports:<br>      - &quot;4000:3000&quot;<br>    volumes:<br>      - grafana-storage:/var/lib/grafana<br><br>  prometheus:<br>    image: prom/prometheus<br>    container_name: prometheus<br>    command:<br>      - &#39;--config.file=/etc/prometheus/prometheus.yml&#39;<br>    ports:<br>      - &quot;9090:9090&quot;<br>    restart: unless-stopped<br>    volumes:<br>      - ./prometheus:/etc/prometheus<br>      - prom_data:/prometheus<br><br>volumes:<br>  grafana-storage:<br>  prom_data:</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObSrjKpYof0AOyFMo1cKyA.png" /><figcaption>Grafana visualizing metrics for the AWS Instance</figcaption></figure><p><strong>Challenges and Solutions</strong></p><ul><li><strong>Architectural Constraints:</strong> The challenge was that the AWS instances were running on 32bit architecture hence it was hard to install chrome engine for using with Selenium. To address we used Firefox with Selenium.</li><li><strong>Data Quality:</strong> Ensuring high-quality Amharic data required careful cleaning and filtering to remove non-Amharic content and irrelevant text.</li><li><strong>Limited Labeled Data:</strong> The availability of annotated Amharic data is limited. To address this, we plan to incorporate Prodigy for data annotation in future work, enabling the creation of labeled datasets for supervised NLP tasks.</li><li><strong>Team Challenges:</strong> Several team members faced unexpected challenges, including laptop malfunctions and electricity outages, which impacted their ability to contribute consistently. Despite these setbacks, the team rallied together, redistributing tasks and offering support to ensure project continuity.</li><li><strong>Pipeline Complexity:</strong> The pipeline, with its various components and dependencies, presented initial challenges in terms of coordination and integration. Thorough planning, modular design, and the use of Airflow for orchestration helped to manage this complexity.</li></ul><p><strong>Results and Achievements</strong></p><p>We successfully collected a substantial amount of Amharic text data from diverse online sources. The data cleaning process effectively removed noise and irrelevant content, resulting in a clean and structured dataset ready for NLP applications. A functional FastAPI-based API was developed, providing efficient access to the processed Amharic data. Additionally, a React-based frontend interface was implemented, allowing users to interact with the API and visualize the retrieved data. Importantly, Apache Airflow successfully orchestrates the entire pipeline, streamlining the data collection, cleaning, and API update processes.</p><p><strong>Next Steps</strong></p><p>The next phase of this project will focus on:</p><ul><li><strong>Annotation: </strong>We planned to annotate the processed data using a tool like Prodigy.</li><li><strong>Containerization:</strong> Containerizing all pipeline components, including web scrapers, Faust stream processors, and the Prodigy annotation tool, using Docker for seamless scalability and reproducibility.</li><li><strong>Monitoring:</strong> Integrating Prometheus and Grafana to monitor pipeline health, resource utilization, and data quality metrics. This will ensure the pipeline’s stability and performance over time.</li><li><strong>Deployment. </strong>Containerizing the all the services in docker containers and hosting them on AWS instance and creating communications using Kubernetes to ensure future scalability of the services and there accessibility anywhere.</li></ul><p><strong>Conclusion</strong></p><p>This scalable data pipeline is a significant contribution to the advancement of Amharic NLP. By providing a reliable source of high-quality data, a user-friendly API, an interactive frontend interface, and a robust orchestration framework, it empowers Roots Tech Solutions and the broader NLP community to develop innovative Amharic language applications that cater to the needs of Ethiopian communities.</p><p>The project’s current codebase and documentation can be found in our GitHub repository: <a href="https://github.com/10AcademyG4/data-warehouse-for-llm-finetuning">https://github.com/10AcademyG4/data-warehouse-for-llm-finetuning</a>.</p><p><strong>References</strong>:</p><ul><li>Beautiful Soup vs Scrapy vs Selenium — Which one to use? Python Web scraping</li></ul><p><a href="https://www.getodata.com/blog/beautiful-soup-vs-scrapy-vs-selenium-which-one-to-use-python-web-scraping">https://www.getodata.com/blog/beautiful-soup-vs-scrapy-vs-selenium-which-one-to-use-python-web-scraping</a></p><ul><li>Web Scraping — Tutorials for the Oklahoma State University</li></ul><p><a href="https://github.com/jtrain789/OSU_MSIS_5193_Tutorials">GitHub - jtrain789/OSU_MSIS_5193_Tutorials: Tutorials for the Oklahoma State University Class 5193 Programming For Data Science and Analytics 1 (Primarily Test mining and Sentiment Analysis in R&amp;Python)</a></p><ul><li>Scrapy Vs Selenium Vs Beautiful Soup for Web Scraping</li></ul><p><a href="https://medium.com/analytics-vidhya/scrapy-vs-selenium-vs-beautiful-soup-for-web-scraping-24008b6c87b8">https://medium.com/analytics-vidhya/scrapy-vs-selenium-vs-beautiful-soup-for-web-scraping-24008b6c87b8</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f129130f71b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Redash Chatbot LLM with GPT by OpenAI]]></title>
            <link>https://medium.com/@hillaryke/building-a-redash-chatbot-llm-with-openai-with-gpt-by-openai-8bb1e5b2605b?source=rss-5307439e4de2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bb1e5b2605b</guid>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[redash]]></category>
            <dc:creator><![CDATA[Hillary kipkemoi]]></dc:creator>
            <pubDate>Tue, 14 May 2024 15:40:55 GMT</pubDate>
            <atom:updated>2024-05-14T19:59:12.735Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Business objective</strong></h3><p>The objective was to develop a powerful Redash chatbot add-on that leverages Large Language Models (LLMs) to revolutionize data analysis and visualization for our company. This add-on will enable seamless interaction with Redash dashboards and databases, providing advanced analytics, visualizations, and automated insights.</p><h4><strong>Project Design</strong></h4><p><strong>High-Level Architecture</strong></p><ol><li><strong>Redash Chat Interface:</strong> A user-friendly chat interface within Redash where users input natural language queries.</li><li><strong>Natural Language Processing (NLP) Engine:</strong> Powered by LangChain and LLamaIndex, this engine interprets user queries, extracts intent, and formulates appropriate responses.</li><li><strong>SQL Query Generator:</strong> Translates natural language queries into optimized SQL queries for execution on the connected databases.</li><li><strong>Data Retrieval and Processing:</strong> Executes generated SQL queries against YouTube data sources, retrieves relevant data, and performs necessary processing.</li><li><strong>Visualization Engine:</strong> Generates insightful visualizations based on the retrieved data, leveraging Redash’s visualization capabilities.</li></ol><h4><strong>Tech Stack used:</strong></h4><ul><li><strong>Frontend:</strong> React (JavaScript)</li><li><strong>Backend:</strong> Python (Quart framework)</li><li><strong>LLMs:</strong> OpenAI API, LangChain, LLamaIndex</li><li><strong>Database:</strong> PostgreSQL (or your preferred choice)</li><li><strong>Vector Database:</strong> Pinecone (or similar)</li><li><strong>Deployment:</strong> Docker, docker-compose</li><li><strong>CI/CD:</strong> GitHub Actions</li></ul><h4>Methodologies</h4><ul><li><strong>Iterative Development:</strong> We followed an iterative approach, starting with basic functionality and gradually incorporating advanced features.</li><li><strong>Prompt Engineering:</strong> A significant effort was dedicated to crafting effective prompts to optimize the LLM’s interpretation and response generation.</li><li><strong>Continuous Integration and Deployment (CI/CD):</strong> GitHub Actions automated testing and deployment processes, streamlining development.</li></ul><h4>Data Understanding</h4><p>Before diving into the technical intricacies, we embarked on a crucial phase: data understanding. We needed to thoroughly grasp the structure, content, and potential insights hidden within the YouTube dataset.</p><ul><li><strong>Data Sources:</strong> We were provided with YouTube data which included the YouTube views for various times including the Cities, Device types, Operating systems and more.</li><li><strong>Schema Design:</strong> We meticulously crafted a database schema to efficiently store and organize this diverse data. Our schema included tables for video information, like viewership metrics.</li><li><strong>Data Exploration (EDA):</strong> We conducted exploratory data analysis (EDA) to uncover patterns, trends, and anomalies. We examined viewership trends over time from the different category folders and explored correlations between the different metrics. This EDA phase was instrumental in shaping our the data and guiding our subsequent development efforts for efficient storage and retrieval.</li></ul><h4>Key insights from the data exploration</h4><p>We explored the data from Jupyter Notebook and these are the insights revealed in the process:</p><ul><li><strong>Data Structure:</strong> We observed that our dataset was primarily in a long format, with each row representing a single observation (e.g., views for a specific device type on a given date). This structure would require reshaping for certain analyses.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*Me2U1DNw7RdqnbPSRfjE7g.png" /><figcaption>Results of unique values of the different categories of the youtube data</figcaption></figure><ul><li><strong>Categorical Variables:</strong> We found that variables like ‘Device Type’, ‘Cities’ and ‘Operating System’ among others were categorical, requiring reshaping to make each categorical variable appear on its own column</li></ul><h4><strong>Data Preprocessing: Preparing for Actionable Insights</strong></h4><p>Based on our exploration, we implemented the following preprocessing steps:</p><ol><li><strong>Reshaping Data:</strong> We transformed the long-format datasets into wide format, where each category (e.g., device type, content type, cities, Operating system) became a separate column. This facilitated easier analysis and visualization and saving.</li><li><strong>Handling Duplicates:</strong> We aggregated data where necessary to eliminate duplicate entries, ensuring that each row had a unique date for every category of values.</li><li><strong>Saving Preprocessed Data:</strong> We saved the preprocessed datasets in CSV files inside a clean folder under each category for further preprocessing.</li></ol><p><strong>Data Integration: Combining Insights for a Holistic View</strong></p><p>With our preprocessed datasets in hand, we embarked on the critical task of data integration. Our goal was to merge the various data sources into a unified dataset that would enable a comprehensive analysis of our YouTube performance.</p><ol><li><strong>Merging DataFrames:</strong> We employed Pandas’ powerful merge function to combine the preprocessed datasets, aligning them based on the common &#39;Date&#39; column. We utilized an &#39;outer&#39; join to ensure that we retained all dates and filled in missing values with NaN (Not a Number).</li><li><strong>Renaming Columns:</strong> To have descriptive column names and avoid naming conflicts after merging, we renamed the columns of each DataFrame to include the category name as a prefix (e.g., ‘Device Type_Mobile’, ‘Content Type_Video’).</li><li><strong>Saving Merged Data:</strong> We saved the final merged dataset as a CSV file for further analysis and to facilitate loading into our database.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MS8opcJi2fiCmP0jcahBXA.png" /><figcaption>Results of the merged data frame with the category variables in each column</figcaption></figure><p><strong>Database Integration: Making Data Accessible</strong></p><p>To make our merged dataset readily accessible for analysis and querying by the Redash chatbot, we loaded it into a PostgreSQL database using SQLAlchemy. This allowed us to leverage the power of SQL for efficient data retrieval and manipulation.</p><h4>Implementation Details</h4><ol><li><strong>Redash Setup and PostgreSQL Integration:</strong> Followed the instructions provided in the Redash documentation to set up the local development environment and successfully integrated Redash with the PostgreSQL database.</li><li><strong>Database Schema Design and Migration:</strong> Created a migration folder within the project directory to manage database schema changes using Alembic. This ensured version control and streamlined updates to the database schema as the project evolved.</li><li><strong>Data Loading:</strong> Utilized Datagrip to load and organize the merged YouTube data into the PostgreSQL database. Addressed challenges related to inconsistent data formatting and value conflicts by customizing the data merging process.</li><li><strong>Chatbot Frontend and Backend Development:</strong> Developed the frontend chatbot interface using React and established the backend API using Quart. Implemented asynchronous execution using Celery to handle concurrent requests to the OpenAI API and Redash query execution.</li><li><strong>Prompt Engineering and LLM Integration:</strong> Fine-tuned prompts for the OpenAI API to enhance natural language understanding and SQL query generation. Leveraged LangChain and LLamaIndex to enhance the chatbot’s ability to process complex queries and retrieve relevant data efficiently.</li><li><strong>Visualization Generation:</strong> Implemented automatic generation of visualizations based on user queries, generated SQL queries, and existing visualization contexts within Redash dashboards.</li></ol><h4>Connecting to PostgreSQL database and loading the data</h4><p>There are the steps followed to connect to the PostgreSQL database:<br>Sure, here’s a brief overview:</p><ol><li>Running PostgreSQL Docker Container: We ensured our PostgreSQL Docker container is running. This was defined and run from the compose.yaml file that the Redash starter code came with. (Later one Redash installtion).</li><li>Connecting to PostgreSQL Database: In this case I used used DataGrip to connect to your PostgreSQL database. This involves creating a new data source, configuring the connection, and testing the connection.</li><li>Loading Data into PostgreSQL Database: Once the database IDE connects, I then loaded data into our database. This involves importing the CSV file generated earlier after merging the YouTube data.</li><li>The Schema will then be generated automatically once the CSV file is imported in the database IDE, here one can also edit the schema including the data types, column names and the table name.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0IvmrtCbmfCu_5Tq5RvCkQ.png" /><figcaption>Datagrip importing the CSV file with youtube views chart data and schema creation.</figcaption></figure><h4><strong>Redash Setup: Building the Foundation</strong></h4><p>To kickstart the project, we needed to have Redash installed, a powerful BI tool with its flexibility and ability to connect to various data sources.</p><p>We followed the steps outlined in the official Redash documentation (<a href="https://github.com/getredash/redash/wiki/Local-development-setup">https://github.com/getredash/redash/wiki/Local-development-setup</a>) to set up a local development environment. Once Redash was up and running, we were ready to connect it to our data source.</p><h4><strong>Connecting Redash to PostgreSQL: Bridging Data and Insights</strong></h4><p>After successfully setting up Redash on our local development environment, the next crucial step was to establish a seamless connection between Redash and our PostgreSQL database, the repository of our valuable YouTube data. This connection would enable Redash to query and visualize our data, transforming raw numbers into actionable insights.</p><p><strong>Step-by-Step Connection Guide:</strong></p><ol><li><strong>Accessing Data Sources:</strong> Within the Redash interface, we navigated to the “Data Sources” section. This is where we could manage connections to various databases and data sources.</li><li><strong>Selecting PostgreSQL:</strong> We clicked on the “New Data Source” button and selected “PostgreSQL” from the list of available options. Redash provides built-in support for PostgreSQL, simplifying the connection process.</li><li><strong>Entering Connection Details:</strong> A configuration form appeared, prompting us to enter the necessary details to establish the connection:<br>- <strong>Name:</strong> We gave our data source a descriptive name, such as “YouTube<br>Analytics.”<br>- <strong>Host:</strong> We entered the hostname or IP address of our PostgreSQL server. In our case, it was running within a Docker container named “redash_chatbot_llm-postgres-1,” so we used “postgres” as the host<br>- <strong>Port:</strong> We specified the port number on which the PostgreSQL server was listening (5432 in our setup).<br>- <strong>User:</strong> We entered the username for accessing the PostgreSQL database (default: “postgres”).<br>- <strong>Password:</strong> We provided the corresponding password for the specified user (default: “postgres”).<br>- <strong>Database Name:</strong> We entered the name of the PostgreSQL database we wanted to connect to (default: “postgres”).</li><li><strong>Testing the Connection:</strong> To ensure everything was working correctly, we clicked the “Test Connection” button. Redash validated the connection parameters, and upon success, displayed a reassuring “Success” message.</li><li><strong>Saving the Data Source:</strong> With the connection verified, we clicked “Save” to create the data source. Redash was now ready to interact with our YouTube data stored in the PostgreSQL database.</li></ol><h4>Creating visualization manually with Redash</h4><p>After connecting Redash to PostgreSQL, we can create a query and get the query results then use the results to create a visualization in the visualization editor of Redash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NrtCUEr8C-2a_14ZpdoYA.png" /><figcaption>Visualization Editor in Redash</figcaption></figure><h4><strong>Adding the Chatbot: Frontend and Backend</strong></h4><p>The heart of the project was integrating the chatbot into Redash. The frontend, built with React, provides a user-friendly chat interface. The backend, powered by Python’s Quart framework, connects this interface to the LLM. I used Postman to test the chat API.</p><p><strong>Adding the Chatbot to Redash Frontend</strong></p><p>To elevate the user experience, we integrated visualization capabilities, empowering the chatbot to generate compelling graphs and charts in response to user queries. The first step in this process was to integrate a chatbot directly into the Redash interface. We leveraged the open-source Redash ChatGPT plugin available on GitHub (<a href="https://github.com/RYees/redash-chatgpt-plugin">https://github.com/RYees/redash-chatgpt-plugin</a>). This project provided a valuable starting point, a springboard for our own chatbot development efforts.</p><p>The GitHub repository offered a clear roadmap for integrating the chatbot plugin into our Redash environment. We followed the step-by-step instructions outlined in the project’s README file:</p><ol><li><strong>Redash Installation:</strong> As a prerequisite, we ensured that we had a Redash instance running locally. We followed the official Redash documentation for local development setup (<a href="https://github.com/getredash/redash/wiki/Local-development-setup">https://github.com/getredash/redash/wiki/Local-development-setup</a>).</li><li><strong>Copying Component Files:</strong> We copied the necessary UI component files (chat folder) and the backend Python code (chat.py) from the repository into the corresponding directories within our Redash source code</li><li><strong>Integrating into Redash Codebase:</strong> We made specific modifications to Redash’s index.jsx file to include the chatbot component. This involved importing the ChatBox component and adding it to the JSX structure.</li><li><strong>Creating a Chat Service:</strong> We created a new file (chat.js) within the client/app/services directory to handle communication between the frontend and backend components.</li><li><strong>Modifying Backend API:</strong> We made adjustments to the redash/handlers/api.py file to register the chatbot API endpoint.</li><li><strong>Setting OpenAI API Key:</strong> Finally, we obtained our OpenAI API key and added it to our .env file, ensuring secure access to the OpenAI language models.</li><li><strong>Rebuilding Redash:</strong> After carefully completing all the integration steps, we rebuilt our Redash instance to incorporate the changes.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9DGV9fLCdonzDpvIOpUtw.png" /><figcaption>Chatbot GPT plugin integrated in the Redash frontend with query replies</figcaption></figure><h4><strong>Running Quart and Redash with Nginx: A Containerized Synergy</strong></h4><p><strong>Why Quart?</strong></p><p>Quart, an asynchronous alternative to Flask, was my backend framework of choice. It shines in handling asynchronous requests, a crucial feature when dealing with LLM interactions and data queries</p><p>To create a robust and flexible platform for our chatbot add-on, we decided to containerize both Quart and Redash, utilizing Nginx as a reverse proxy to manage traffic between them. This containerized approach offered several advantages, including isolation of application environments, portability, scalability, and reproducibility.</p><p><strong>Building the Quart Container</strong></p><p>We began by constructing a Dockerfile for our Quart application. This Dockerfile outlined the steps necessary to create a Docker image containing our Python environment, dependencies, and the Quart application code.</p><pre>FROM python:3.9<br><br>WORKDIR /app<br><br>COPY quart/api/requirements.txt ./<br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY quart/api/src ./<br><br>CMD [&quot;hypercorn&quot;, &quot;api:app&quot;, &quot;-b&quot;, &quot;0.0.0.0:5057&quot;]</pre><p>The core steps included:</p><ol><li><strong>Base Image:</strong> We started with the official Python 3.9 image.</li><li><strong>Working Directory:</strong> We set the working directory within the container to /app.</li><li><strong>Dependencies:</strong> We copied the requirements.txt file from our Quart API directory and used pip to install the required Python packages.</li><li><strong>Source Code:</strong> We copied our Quart API source code into the container.</li><li><strong>Command:</strong> We specified the command to run when the container starts, in this case, the Hypercorn ASGI server to host our Quart application.</li></ol><p><strong>Integrating Quart into Docker Compose</strong></p><p>Next, we integrated our newly created Quart container into the existing Docker Compose configuration for Redash. We defined a service named quart_server within the docker-compose.yml file, specifying the Dockerfile, command, port mappings, and environment variables (including our OpenAI API key).</p><pre>quart_server:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.quart<br>    command: [ &quot;hypercorn&quot;, &quot;api:app&quot;, &quot;-b&quot;, &quot;0.0.0.0:5057&quot; ]<br>    ports:<br>      - &quot;5057:5057&quot;<br>    environment:<br>      - OPENAI_API_KEY=${OPENAI_API_KEY}<br>    depends_on:<br>      - server</pre><p><strong>Nginx as the Traffic Conductor</strong></p><p>With our Quart container integrated, we introduced Nginx as the reverse proxy. This involved adding an nginx service to our Docker Compose configuration and creating an nginx.conf file to define routing rules.</p><pre>nginx:<br>    image: nginx:latest<br>    volumes:<br>      - ./nginx.conf:/etc/nginx/nginx.conf<br>    ports:<br>      - 80:80<br>    depends_on:<br>      - server<br>      - quart_server</pre><p>The nginx.conf file contained the following key elements:</p><ul><li><strong>Upstream Servers:</strong> We defined upstream servers for both the Redash (server) and Quart (quart_server) containers.</li><li><strong>Location Blocks:</strong> We created location blocks to direct requests based on the URL pattern. Requests matching /api/chat were forwarded to the Quart container, while all other requests were routed to the Redash container.</li></ul><pre>events {}<br>http {<br>    upstream server {<br>        server server:5000;<br>    }<br><br>    upstream quart_server {<br>        server quart_server:5057;<br>    }<br><br>    server {<br>        listen 80;<br><br>        location ~ ^/api/chat(/|$) {<br>            proxy_pass http://quart_server;<br>            proxy_set_header Host $host;<br>            proxy_set_header X-Real-IP $remote_addr;<br>            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        }<br><br>        location / {<br>            proxy_pass http://server/;<br>            proxy_set_header Host $host;<br>            proxy_set_header X-Real-IP $remote_addr;<br>            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        }<br>    }<br>}</pre><p><strong>Starting the Containerized Ensemble</strong></p><p>With our enhanced docker-compose.yml file in place, we could now orchestrate the entire setup with a single command: make up. This command initiated all the containers, including Redash, Quart, and Nginx.</p><p>Upon verifying that the containers were running using docker ps, we were able to access Redash at http://localhost:8081 and our custom Quart API endpoints at <a href="http://localhost/api/chat/your-endpoint.">http://localhost/api/chat/your-endpoint.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*8L17781ixmbuGEE8.png" /><figcaption>The output of running containers and their ports</figcaption></figure><p>This containerized approach provided us with a scalable and maintainable architecture for our Redash chatbot project. It allowed us to seamlessly integrate our custom Quart API endpoints with Redash, paving the way for a more powerful and customizable data exploration experience.</p><h4>Testing our Quart server with Postman</h4><p>After the Quart server is successfully running, we can define a basic endpoint that just returns the question it was received from the request:</p><pre>@app.route(&#39;/api/chat/echo&#39;)<br>async def echo():<br>    value = await request.get_json()<br>    question = value.get(&#39;question&#39;)<br>    response_data = {&quot;answer&quot;: question }<br>    return jsonify(response_data), 200</pre><h4>LangChain integration</h4><p>Langchain is a Python library that allows us to interact with OpenAI models in a more structured and convenient way. It provides a pipeline-like interface where we can chain together different components (like prompts and models) and then invoke the entire chain with a single method call.</p><p>To integrate LangChain from the provided documentation into out Quart server, we would need to install the necessary packages, import the required modules, and then use the LangChain methods in out API endpoints. Here’s how we did it:</p><pre>pip install langchain-core<br>pip install langchain-openai<br><br>@app.route(&#39;/api/chat&#39;, methods=[&#39;POST&#39;])<br>async def handle_user_question():<br>    try:<br>        schema = get_schema()<br>        logging.info(schema)<br><br>        value = await request.get_json()<br>        question = value.get(&#39;question&#39;)<br><br>        # Use LangChain to get the answer<br>        system_message = &quot;&quot;&quot;You are a nice assistant trained to generate SQL queries for Redash based on user&#39;s questions. You have knowledge to the schema&quot;&quot;&quot;<br>            # Create a SystemMessagePromptTemplate from the system message<br>        prompt = (<br>            SystemMessagePromptTemplate.from_template(system_message) + &quot;{question}&quot;<br>        )<br>        llm = OpenAI()<br>        llm_chain = prompt | llm<br>        answer = llm_chain.invoke(question)<br><br>        response_data = {&quot;answer&quot;: answer}<br>        return jsonify(response_data), 200<br>    except Exception as error:<br>        print(error)<br>        logging.error(error)<br>        return jsonify({&quot;error&quot;: &quot;An error occurred&quot;}), 500</pre><p>We could then then use the PromptTemplate and OpenAI classes in the API endpoints. For example, by our /api/chat endpoint to use LangChain.</p><p>In the example, the invoke method of the <em>llm_chain</em> object is used to get the answer to the user’s question. The invoke method takes a question and returns an answer.</p><h4>Celery for concurrency task execution</h4><p>The long_running_task is a placeholder for a task that you want to run asynchronously using Celery. This task could be anything that might take a long time to complete, such as processing a large amount of data, making a request to an external API, or executing a complex database query.</p><p>For example, if you want to execute a SQL query using Redash API and process the results, your long_running_task might look something like this:</p><pre>@celery.task<br>def long_running_task(query):<br>    # Execute the query and get the results<br>    results = RedashApi.query_and_wait_result(1, query)<br><br>    # Process the results (this is just a placeholder, replace with your actual processing logic)<br>    processed_results = process_results(results)<br><br>    return processed_results</pre><p>In this example, long_running_task takes a SQL query as an argument, executes this query using the Redash API, processes the results, and then returns the processed results.</p><p>The process_results function could be used to format the results returned from the Redash API into a more usable format, or to perform some kind of analysis on the results. In this case, the function formats the results into a list of dictionaries, where each dictionary represents a row of the result:</p><pre>def process_results(results):<br>    # The results returned from the Redash API are in the format:<br>    # {&#39;columns&#39;: [{&#39;name&#39;: &#39;column1&#39;, &#39;type&#39;: &#39;type1&#39;}, {&#39;name&#39;: &#39;column2&#39;, &#39;type&#39;: &#39;type2&#39;}], &#39;rows&#39;: [{&#39;column1&#39;: &#39;value1&#39;, &#39;column2&#39;: &#39;value2&#39;}]}<br>    # We&#39;ll transform this into a list of dictionaries for easier processing<br><br>    processed_results = []<br><br>    for row in results[&#39;rows&#39;]:<br>        processed_row = {}<br>        for column in results[&#39;columns&#39;]:<br>            column_name = column[&#39;name&#39;]<br>            processed_row[column_name] = row[column_name]<br>        processed_results.append(processed_row)<br><br>    return processed_results</pre><p>You can then call this task from your Quart route like this:</p><pre>@app.route(&#39;/api/chat/start_task&#39;, methods=[&#39;POST&#39;])<br>async def start_task():<br>    value = await request.get_json()<br>    query = value.get(&#39;query&#39;)<br>    task = long_running_task.delay(query)<br>    return jsonify({&#39;task_id&#39;: task.id}), 200</pre><p>In this route, the SQL query is received from the client as part of the request data. The long_running_task is then sent to the Celery worker for execution using the delay method, and the task ID is returned to the client.</p><h4>Challenges and Solutions</h4><ul><li><strong>Data Merging Challenges:</strong> Encountered inconsistencies in data values across different files during the merg+-ing process. Resolved this by assigning separate tables for each table data file, ensuring data integrity.</li><li><strong>Data Saving with SQLAlchemy and psycopg2:</strong> I faced difficulties saving the merged data due to the module isssues. I addressed by this by using the Datagrip (Jetbrains IDE for databases). I connected the database to datagrip and loaded the merged data contained in a CSV file.</li><li><strong>Complex SQL Generation:</strong> Handled complex natural language queries by leveraging LangChain and LLamaIndex to improve query understanding and generate more accurate SQL translations.</li></ul><h4>Limitations and Future Enhancements</h4><ul><li><strong>Query Complexity:</strong> The chatbot may struggle with highly complex or ambiguous queries. Further refinement of prompt engineering and integration of domain-specific knowledge can address this.</li><li><strong>Error Handling:</strong> The current implementation may not comprehensively handle all potential errors in user queries or data retrieval. Robust error handling mechanisms should be implemented.</li><li><strong>Scalability:</strong> As the dataset grows, the query execution time may increase. Implementing caching mechanisms and query optimization strategies can enhance scalability.</li></ul><h3>Conclusion</h3><p>Building a Redash chatbot add-on for YouTube data analysis was a rewarding and educational experience. By combining cutting-edge LLM technology with a well-thought-out methodology, a deep understanding of our data, meticulous preprocessing, and careful data integration, we empowered our team to unlock valuable insights from our YouTube data with ease. This project not only demonstrates the transformative potential of LLMs in the realm of data analytics but also highlights the importance of a collaborative and iterative approach to software development, encompassing the entire data lifecycle from understanding to integration.</p><h3>References</h3><ul><li><a href="https://github.com/getredash/redash/wiki/Local-development-setup">Redash local development setup</a></li><li><a href="https://github.com/RYees/redash-chatgpt-plugin">Redash Chatbot Addon</a></li><li><a href="https://python.langchain.com/v0.1/docs/integrations/llms/openai/">Running openAI with langchain</a></li><li><a href="https://api.python.langchain.com/en/latest/prompts/langchain_core.prompts.prompt.PromptTemplate.html">Using llm promptTemplate to write customizable and better prompts for openAI</a></li><li><a href="https://github.com/mnick-yt/Chat-Bot-using-gpt-3.5-turbo/tree/main/ChatGPT%20API/static/images">Using gpt 3.5 turbo</a></li><li><a href="https://pgjones.gitlab.io/quart/tutorials/api_tutorial.html">Using quart to create Restful API — official documentation</a></li><li><a href="https://github.com/RYees/Asynchronous_OpenAI_-Streaming_Execution">Asynchronous OpenAI</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bb1e5b2605b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Quart and Redash with Nginx: A Containerized Approach]]></title>
            <link>https://medium.com/@hillaryke/running-quart-and-redash-with-nginx-a-containerized-approach-95565dadb17c?source=rss-5307439e4de2------2</link>
            <guid isPermaLink="false">https://medium.com/p/95565dadb17c</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[redash]]></category>
            <category><![CDATA[quart]]></category>
            <dc:creator><![CDATA[Hillary kipkemoi]]></dc:creator>
            <pubDate>Mon, 13 May 2024 14:38:57 GMT</pubDate>
            <atom:updated>2024-05-13T15:15:55.158Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re knee-deep in data analysis and visualization, you’ve probably come across Quart (a Python web framework) and Redash (an open-source BI tool). Combining these two powerful tools can give you a flexible, customizable data platform. In this post, I’ll walk you through how I containerized Quart alongside Redash container, then used Nginx as a reverse proxy to manage traffic between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ocYRFrqkiq1aeBqbLpvqtQ.png" /></figure><p><strong>Why Containers?</strong></p><p>Containers offer a ton of advantages:</p><ul><li><strong>Isolation:</strong> Each application runs in its own isolated environment, preventing conflicts.</li><li><strong>Portability:</strong> You can easily move containers between different environments.</li><li><strong>Scalability:</strong> It&#39;s simpler to scale your applications up or down as needed.</li><li><strong>Reproducibility:</strong> You can consistently recreate the same environment for development, testing, and production.</li></ul><p><strong>The Setup</strong></p><p>Here’s a simplified overview of my setup:</p><ol><li><strong>Quart Container:</strong> This container runs your Quart application, serving your custom API endpoints or data processing logic.</li><li><strong>Redash Container:</strong> This container hosts the Redash application, providing your data dashboards and visualization tools.</li><li><strong>Nginx Container:</strong> This container acts as the traffic director (reverse proxy). It listens for incoming requests and forwards them to the appropriate container (Quart or Redash) based on the URL pattern.</li></ol><p><strong>The Redash Local Development Setup</strong></p><p>Following the official guide on the Redash GitHub wiki (<a href="https://github.com/getredash/redash/wiki/Local-development-setup">https://github.com/getredash/redash/wiki/Local-development-setup</a>), I configured Redash for local development. This setup involves a few key components:</p><ul><li><strong>Docker Compose:</strong> This tool elegantly handles the multi-container environment.</li><li><strong>Key Services:</strong> The setup includes server, scheduler, worker, postgres, redis, email for local email testing, and cypress for end-to-end testing.</li></ul><p><strong>Building the Quart Container</strong></p><p>To seamlessly integrate custom API endpoints or data processing tasks, I created a Dockerfile.quart file in the root directory of my project. This file defines the steps to build a Docker image for the Quart application:</p><pre>FROM python:3.9<br><br>WORKDIR /app<br><br>COPY quart/api/requirements.txt ./<br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY quart/api/src ./<br><br>CMD [&quot;hypercorn&quot;, &quot;api:app&quot;, &quot;-b&quot;, &quot;0.0.0.0:5050&quot;]</pre><p>This Dockerfile does the following:</p><ol><li><strong>Base Image:</strong> Starts with the official Python 3.9 image.</li><li><strong>Working Directory:</strong> Sets the working directory within the container to /app.</li><li><strong>Dependencies:</strong> Copies the requirements.txt file from your <strong>Quart API</strong> directory (quart/api) and installs the necessary Python packages.</li><li><strong>Source Code:</strong> Copies the Quart API source code into the container.</li><li><strong>Command:</strong> Specifies the command to run when the container starts, which in this case is the Hypercorn ASGI server to host the Quart application.</li></ol><p><strong>Adding the Quart Container</strong></p><p>To introduce custom API endpoints or data processing tasks, I integrated a Quart container into the existing Docker Compose configuration:</p><pre>quart_server:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.quart<br>    command: [ &quot;hypercorn&quot;, &quot;api:app&quot;, &quot;-b&quot;, &quot;0.0.0.0:5057&quot; ]<br>    ports:<br>      - &quot;5057:5057&quot;<br>    environment:<br>      - OPENAI_API_KEY=${OPENAI_API_KEY}<br>    depends_on:<br>      - server</pre><p><strong>Nginx: The Traffic Controller</strong></p><p>Nginx takes center stage as the reverse proxy, directing incoming traffic to the appropriate service:</p><pre>nginx:<br>    image: nginx:latest<br>    volumes:<br>      - ./nginx.conf:/etc/nginx/nginx.conf<br>    ports:<br>      - 80:80<br>    depends_on:<br>      - server<br>      - quart_server</pre><p>The accompanying nginx.conf file contains the routing rules:</p><pre>events {}<br>http {<br>    upstream server {<br>        server server:5000;<br>    }<br><br>    upstream quart_server {<br>        server quart_server:5057;<br>    }<br><br>    server {<br>        listen 80;<br><br>        location ~ ^/api/chat(/|$) {<br>            proxy_pass http://quart_server;<br>            proxy_set_header Host $host;<br>            proxy_set_header X-Real-IP $remote_addr;<br>            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        }<br><br>        location / {<br>            proxy_pass http://server/;<br>            proxy_set_header Host $host;<br>            proxy_set_header X-Real-IP $remote_addr;<br>            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        }<br>    }<br>}</pre><p><strong>Starting the Ensemble</strong></p><p>With your enhanced docker-compose.yml file in place. To initiate your containerized data platform, run the commands given in the Redash setup documentation provided before:</p><pre>yarn</pre><pre>make build</pre><pre>make compose_build</pre><pre>make up</pre><p>If you now run docker ps command on your terminal, you’ll see the three containers alongside other services defined in the compose.yaml file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zApLPnjn639buQXEwgyuZw.png" /><figcaption>The output of running containers and their ports</figcaption></figure><p>From the output, we can notice that nginx and quart_server containers are running on ports 80 and 5057 respectively inside their containers and are also mapped to be accessed on my local machine with the ports 8081 and 5057 respectively.</p><p>Now, you can:</p><ul><li>In your browser, you can access your Redash instance at <a href="http://localhost:8081/">http://localhost:8081/.</a> Notice the port is for nginx, meaning that when we make a request with the endpoint / , the endpoint will be directed to the Redash server by nginx server.</li><li>Utilize your Quart API endpoints at http://localhost/api/chat/your-endpoint.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95565dadb17c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>