<?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 Abubeker on Medium]]></title>
        <description><![CDATA[Stories by Abubeker on Medium]]></description>
        <link>https://medium.com/@abubekershamil?source=rss-dec8d7adb524------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GPK-cGl00kWG7VaVSU8k9g.png</url>
            <title>Stories by Abubeker on Medium</title>
            <link>https://medium.com/@abubekershamil?source=rss-dec8d7adb524------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:53:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abubekershamil/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[Building an Efficient Retrieval Augmented Generation (RAG) System for Legal Document — Q&A Chatbot]]></title>
            <link>https://medium.com/@abubekershamil/building-an-efficient-retrieval-augmented-generation-rag-system-for-legal-document-q-a-chatbot-db5394ca54b5?source=rss-dec8d7adb524------2</link>
            <guid isPermaLink="false">https://medium.com/p/db5394ca54b5</guid>
            <category><![CDATA[legal]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[legaltech]]></category>
            <category><![CDATA[evaluation]]></category>
            <dc:creator><![CDATA[Abubeker]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 19:53:33 GMT</pubDate>
            <atom:updated>2024-07-08T08:07:24.306Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an Efficient Retrieval Augmented Generation (RAG) System for Legal Document — Q&amp;A Chatbot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*94La04YiEZd7nG5OQ__tOQ.png" /></figure><h3>Introduction</h3><p>In the world of Natural Language Processing (NLP), Retrieval Augmented Generation (RAG) has emerged as a powerful technique that combines the strengths of information retrieval and text generation to create highly accurate and contextually relevant responses. In this post, we will walk through the process of building a RAG system tailored for answering questions about legal documents. We’ll cover the end-to-end workflow, from setting up the backend with <a href="https://fastapi.tiangolo.com/">FastAPI</a> and Frontend with <a href="https://react.dev/">React</a> to evaluating different configurations using <a href="https://docs.ragas.io/en/stable/getstarted/index.html">RAGAS</a>.</p><h3>Retrieval Augmented Generation (RAG)</h3><p>RAG combines the strengths of information retrieval and text generation to create systems capable of answering complex queries with contextually relevant and accurate responses. Traditional retrieval systems can quickly fetch relevant documents like google indexing millions of webpages in a second, but they often fall short in generating coherent and precise answers. Conversely, generative models can create human-like text but may lack the necessary context or domain-specific knowledge. RAG bridges this gap by integrating retrieval mechanisms with generative models, enabling the generation of well-informed and context-aware responses.</p><p>RAG systems are particularly beneficial in domains that require precise and context-sensitive information, such as legal document processing. By leveraging RAG, legal professionals or not, can efficiently query large corpora of legal texts, retrieve relevant documents, and generate accurate and concise answers to specific legal questions.</p><h3>Project Objective</h3><p>Our primary goal is to build a robust RAG system tailored for handling legal documents. We will address how to set up a FastAPI backend, integrate it with OpenAI models, implement various chunking, query transformation and retrieval strategies, evaluate the system using RAGAS, and experiment with different configurations to optimize performance.</p><p>By the end of this post, we will have a comprehensive understanding of</p><ul><li>Setting up a FastAPI application for RAG.</li><li>Integrating PostgreSQL for database management.</li><li>Utilizing OpenAI models for embedding and text generation.</li><li>Implementing and experimenting with different chunking and retrieval strategies.</li><li>Evaluating the RAG system using RAGAS.</li><li>Optimizing the system for better performance.</li></ul><h3>Considerations in Building Q&amp;A RAG</h3><p>Building a <a href="https://python.langchain.com/v0.1/docs/use_cases/question_answering/">Retrieval-Augmented Generation (RAG) Q&amp;A application</a> is easy but making it production-ready and scalable is very difficult. We need to consider different aspects such as</p><ul><li><strong><em>Latency</em></strong></li><li><strong><em>Cost of retrieval and generation using LLM</em></strong></li><li><strong><em>Answer Relevancy (how precise the answer should be)</em></strong></li></ul><p>Getting the RAG pipeline’s performance to a satisfying state is especially difficult because of the different components in a RAG pipeline</p><ul><li><strong>Retriever component </strong>retrieves additional context from an external database for the LLM to answer the query.</li><li><strong>Generator component </strong>generates an answer based on a prompt augmented with the retrieved information.</li></ul><p>Hence the efficiency of the above pipeline is essential for the overall performance of the RAG.</p><h3>Setting Up the Project</h3><p><strong>Project Structure</strong></p><p>Before diving into the implementation, it’s essential to organize our project in a structured manner. This ensures that our code is maintainable and scalable. Here’s a simple overview of our project structure</p><pre>my_rag_project/<br>│<br>├── app/<br>│   ├── __init__.py<br>│   ├── main.py  # Entry point for the FastAPI application.<br>│   ├── config.py<br>│   ├── models.py<br>│   ├── schemas.py<br>│   ├── database.py<br>│   ├── factory.py  # Factory methods for creating components.<br>│   ├── routers/<br>│   │   ├── __init__.py<br>│   │   ├── qa.py<br>│   │   └── history.py<br>│   └── services/    # Business logic and service layer<br>│       ├── __init__.py<br>│       ├── qa_service.py<br>│       └── history_service.py<br>├── data/<br>│   ├── raw/<br>│   │   └── law_docx/<br>│   └── evaluation_data.json<br>├── requirements.txt<br>└── config.yaml # houses our configuration for tweaking hyperparameters</pre><h4>Environment Setup</h4><p>To start, we need to set up our development environment with the necessary tools and libraries. Follow these steps to get everything installed and configured.</p><h4>Install Python and Virtual Environment</h4><p>Ensure you have Python 3.10 or higher installed. You can download it from the <a href="https://www.python.org/downloads/">official Python website</a>. Once installed, create a virtual environment for the project</p><pre>python -m venv myenv<br>source myenv/bin/activate   # On Windows use `myenv\Scripts\activate`</pre><h4>Install Required Libraries</h4><p>Create a requirements.txt file with the following content:</p><pre>fastapi<br>uvicorn<br>sqlalchemy<br>asyncpg<br>databases<br>pydantic<br>pyyaml<br>openai<br>langchain<br>ragas<br><br># Refer to my github repo for more dependencies</pre><p>Install the dependencies using pip</p><pre>pip install -r requirements.txt</pre><h4>Create Configuration File</h4><p>Create a config.yaml file to manage our component settings which is essential to tweak our hyperparameters to find out our efficient params.</p><p>Below is my configuration</p><pre>model: &quot;gpt-4o&quot; # gpt-4o, gpt-3.5-turbo, gpt-4-turbo<br>embedding: &quot;openai&quot;<br>retriever: &quot;dense&quot; # dense, sparse, hybrid<br>text_splitter: &quot;semantic&quot; # sentence, character, semantic, recursive<br>prompt: &quot;history_aware&quot; # history_aware, contextualize_q, qa_assistant<br>chunk_size: 300 # chunk_size<br>chunk_overlap: 50 # chunk_overlap<br>query_translation: &quot;hyde&quot; # multi_query, rag_fusion, decomposition, hyde</pre><p>As you can see above, we have different params as we will see later on this post how we will leverage them. This configuration file will allow us to easily swap out models, embeddings, and retrievers as needed.</p><h3>Building the RAG Backend System</h3><h4>Configuring the FastAPI Backend</h4><p>FastAPI is a modern, fast web framework for building APIs with Python based on standard Python type hints and pydantic. It is easy to set up and provides great performance.</p><h4>Install FastAPI and Uvicorn</h4><p>If you haven’t already installed FastAPI and Uvicorn, you can do so by running</p><pre>pip install fastapi uvicorn</pre><h4>Create the Initial FastAPI Application</h4><p>Create a new file named main.py inside the app directory. This file will serve as the entry point for our FastAPI application</p><pre>import os<br>from langchain_community.document_loaders import Docx2txtLoader<br><br>from fastapi import FastAPI<br>from .database import engine, SessionLocal<br>from .models import Base<br>from .routers import qa, history<br>from .retriever import get_retriever_instance<br>import logging <br><br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)<br><br>logger.info(&quot;Logger CWD:: &quot; + os.getcwd())<br><br># Create the database tables<br>Base.metadata.create_all(bind=engine)<br><br>app = FastAPI()<br><br># Include routers<br>app.include_router(qa.router)<br>app.include_router(history.router)<br><br>def get_document_from_docx(documents: list, file_path):<br>    # Load and parse HTML file found in the specified folder and subfolders<br>    docx_files = [os.path.join(file_path, f) for f in os.listdir(file_path) if f.endswith(&#39;.docx&#39;)]<br><br>    # Load and parse HTML files<br>    for file in docx_files:<br>        loader = Docx2txtLoader(file)<br>        documents.extend(loader.load())<br><br>    return documents<br><br># Initialize the retriever with documents<br>documents = get_document_from_docx([], &quot;data/raw/docx&quot;)<br>len = len(documents)<br>logger.info(f&quot;The Logger INFO :: {len}&quot;)<br>retriever = get_retriever_instance(documents).store_documents(documents)</pre><p>This sets up a basic FastAPI application with a root endpoint that sets up the initial legal docks into a vector database for initial processing. We also include routers for the QA and history endpoints, which we will define later.</p><h4>Database Integration with PostgreSQL</h4><p>We will use SQLAlchemy for database ORM (Object Relational Mapping) for asynchronous database interactions.</p><h4>Configure Database Connection</h4><p>Create a file named database.py inside the app directory. This file will handle the database connection setup and session management</p><pre>from sqlalchemy import create_engine<br>from sqlalchemy.ext.declarative import declarative_base<br>from sqlalchemy.orm import sessionmaker<br>import os<br><br>SQLALCHEMY_DATABASE_URL = os.getenv(&quot;DATABASE_URL&quot;)<br><br>engine = create_engine(SQLALCHEMY_DATABASE_URL)<br>SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)<br>Base = declarative_base()<br><br># Dependency to get DB session<br>def get_db():<br>    db = SessionLocal()<br>    try:<br>        yield db<br>    finally:<br>        db.close()</pre><p>We have used render AWS redundant Postgres database for this, but any database will work fine.</p><h4>Define Database Models</h4><p>Next, we define our database models in a file named models.py</p><pre># app/models.py<br><br>from sqlalchemy import Column, Integer, String, Text, DateTime<br>from .database import Base<br>from datetime import datetime<br><br>class ChatHistory(Base):<br>    __tablename__ = &#39;chat_history&#39;<br><br>    id = Column(Integer, primary_key=True, index=True)<br>    session_id = Column(String, index=True)<br>    message = Column(Text)<br>    timestamp = Column(DateTime, default=datetime.utcnow)</pre><h4>Create Pydantic Schemas</h4><p>Create a file named schemas.py to define Pydantic models for request and response validation</p><pre># app/schemas.py<br><br>from pydantic import BaseModel<br>from datetime import datetime<br>from typing import List<br><br>class QueryRequest(BaseModel):<br>    query: str<br><br>class QueryResponse(BaseModel):<br>    response: str<br><br>class MessageHistory(BaseModel):<br>    session_id: str<br>    message: str<br><br>class MessageHistoryResponse(BaseModel):<br>    id: int<br>    session_id: str<br>    message: str<br>    timestamp: datetime<br><br>    class Config:<br>        orm_mode = True</pre><h4>Create QA Router</h4><p>One of the essential routes is to QA route as this will be the first communication channel between the user and our RAG application.</p><p>Create a file named qa.py inside the routers directory. This file will handle the question-answering endpoints</p><pre># app/routers/qa.py<br><br>from fastapi import APIRouter, Depends, HTTPException<br>from sqlalchemy.orm import Session<br>from ..schemas import QueryRequest, QueryResponse<br>from ..database import get_db<br>from ..services.qa_service import get_answer<br><br>router = APIRouter()<br><br>@router.post(&quot;/qa&quot;, response_model=QueryResponse)<br>async def qa_endpoint(query: QueryRequest, db: Session = Depends(get_db)):<br>    response = await get_answer(query, db)<br>    return QueryResponse(response=response)</pre><blockquote>Factory Methods for Component Swapping</blockquote><p>We have seen the overview of our implementation FastAPI, routers and databases now we shall see an essential component of our RAG application which is a factory method for creating and managing different components (models, embeddings, retrievers) to allow easy swapping and configuration. We’ll also ensure our system is flexible and can be easily adapted for various scenarios.</p><h3>Building the RAG System</h3><p>To create a flexible system that allows easy swapping of models, embeddings, and retrievers, we need to implement factory methods. This will enable us to experiment with different configurations without modifying the core logic of our application.</p><h4>Abstracting Component Interfaces</h4><p>We’ll start by defining abstract interfaces or base classes for our components. This ensures that all implementations adhere to a common structure.</p><h4>Create the Factory File</h4><p>Create a file named factory.py inside the app directory. This file will contain our factory methods</p><pre>from langchain_openai import ChatOpenAI, OpenAIEmbeddings<br>from langchain_community.vectorstores import Chroma<br>from .chunking import TextSplitter<br>from .config import load_config<br><br># makes the .env file in the same directory<br>import os<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>def get_model():<br>    config = load_config()<br>    if config[&quot;model&quot;] == &quot;gpt-3.5-turbo&quot;:<br>        return ChatOpenAI(model=&quot;gpt-3.5-turbo&quot;, temperature=0)<br>    elif config[&quot;model&quot;] == &quot;gpt-4o&quot;:<br>        return ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0)<br>    # Add more models as needed<br><br>def get_embedding():<br>    config = load_config()<br>    if config[&quot;embedding&quot;] == &quot;openai&quot;:<br>        return OpenAIEmbeddings()<br>    elif config[&quot;embedding&quot;] == &quot;huggingface&quot;:<br>        return &quot;HuggingFaceEmbeddings&quot;<br>    # Add more embeddings as needed<br><br>def get_retriever():<br>    config = load_config()<br>    if config[&quot;retriever&quot;] == &quot;dense&quot;:<br>        return &quot;DenseRetriever(documents)&quot;<br>    elif config[&quot;retriever&quot;] == &quot;sparse&quot;:<br>        return &quot;SparseRetriever(documents)&quot;<br>    # Add more retrievers as needed<br><br>def get_prompt():<br>    from .generator import create_context_prompt, get_qa_assistant_prompt, create_history_aware_prompt<br>    config = load_config()<br>    if config[&quot;prompt&quot;] == &quot;history_aware&quot;:<br>        return create_history_aware_prompt()<br>    elif config[&quot;prompt&quot;] == &quot;contextualize_q&quot;:<br>        return create_context_prompt()<br>    elif config[&quot;prompt&quot;] == &quot;qa_assistant&quot;:<br>        return get_qa_assistant_prompt()<br>    # Add more prompts as needed<br><br>def get_text_splitter() -&gt; TextSplitter:<br>    config = load_config()<br><br>    chunk_size = config[&quot;chunk_size&quot;]<br>    chunk_overlap = config[&quot;chunk_overlap&quot;]<br>    <br>    if config[&quot;text_splitter&quot;] == &quot;character&quot;:<br>        return TextSplitter(&quot;Character&quot;, chunk_size, chunk_overlap)<br>    elif config[&quot;text_splitter&quot;] == &quot;sentence&quot;:<br>        return TextSplitter(&quot;Sentence&quot;, chunk_size, chunk_overlap)<br>    elif config[&quot;text_splitter&quot;] == &quot;recursive&quot;:<br>        return TextSplitter(&quot;Recursive&quot;, chunk_size, chunk_overlap)<br>    elif config[&quot;text_splitter&quot;] == &quot;semantic&quot;:<br>        return TextSplitter(&quot;Semantic&quot;, chunk_size, chunk_overlap)<br>    # Add more text splitters as needed<br><br>def get_query_translation():<br>    config = load_config()<br>    from .generator import get_answer_using_multi_query, get_answer_using_rag_fusion, get_answer_using_decomposition, get_answer_using_hyde<br>    if config[&quot;query_translation&quot;] == &quot;multi_query&quot;:<br>        return get_answer_using_multi_query<br>    elif config[&quot;query_translation&quot;] == &quot;rag_fusion&quot;:<br>        return get_answer_using_rag_fusion<br>    elif config[&quot;query_translation&quot;] == &quot;decomposition&quot;:<br>        return get_answer_using_decomposition<br>    elif config[&quot;query_translation&quot;] == &quot;hyde&quot;:<br>        return get_answer_using_hyde<br>    # Add more query translation as needed</pre><p>With the factory methods and previous configuration management in place, we have a flexible system that allows us to easily swap out different components and configurations. This sets the stage for running evaluations and experimenting with various setups.</p><p>Before that let me introduce you to the data.</p><h3>Understanding and Visualizing Token Counts in Document Processing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*jbdMNUW3QGwQcIYd6fuKrg.png" /></figure><p>When working with large documents in natural language processing (NLP) tasks, one critical aspect to consider is the token count of each document. Tokens are the individual pieces of the text that models like GPT-3.5 process, and understanding their distribution across documents is essential for efficient and effective model performance.</p><h4>Why Visualize Token Counts?</h4><p>Visualizing token counts helps us in several ways</p><ol><li><strong>Context Window Management</strong> GPT-3.5 has a maximum context window of <strong>16k </strong>tokens. If a document exceeds this limit, it must be split or truncated, which can lead to loss of critical information or increased complexity in handling multiple parts. By visualizing token counts, we can easily identify documents that exceed this limit.</li><li><strong>Performance Optimization</strong> When documents of vastly different lengths are processed together, shorter documents may not fully utilize the model’s capacity, while longer documents may need to be split, complicating the processing pipeline. Visualizing helps us balance the document lengths for optimal performance.</li><li><strong>Resource Allocation</strong> Longer documents require more costly resources for processing. Knowing the token distribution allows us to allocate resources efficiently, ensuring that longer documents are given adequate processing power without over-allocating resources to shorter documents.</li></ol><h4>Code — Visualizing Token Counts</h4><p>We used the tiktoken library to calculate the token counts and matplotlib to create a bar chart that displays these counts. Below is the Python code to achieve this visualization</p><pre>import matplotlib.pyplot as plt<br>import tiktoken<br>import os<br><br>def get_document_from_docx(documents: list, file_path):<br>    # Load and parse docx files found in the specified folder and subfolders<br>    docx_files = [os.path.join(file_path, f) for f in os.listdir(file_path) if f.endswith(&#39;.docx&#39;)]<br><br>    # Load and parse docx files<br>    for file in docx_files:<br>        loader = Docx2txtLoader(file)<br>        documents.extend(loader.load())<br><br>    return documents<br><br># Initialize the retriever with documents<br>docs = get_document_from_docx([], &quot;data/raw/docx&quot;)<br><br>def num_tokens_from_string(string: str, encoding_name: str) -&gt; int:<br>    &quot;&quot;&quot;Returns the number of tokens in a text string.&quot;&quot;&quot;<br>    encoding = tiktoken.get_encoding(encoding_name)<br>    num_tokens = len(encoding.encode(string))<br>    return num_tokens<br><br># Document texts and names<br>docs_texts = [d.page_content for d in docs]<br>doc_names = [os.path.basename(d.metadata[&#39;source&#39;]) for d in docs]  # Assuming metadata contains &#39;source&#39;<br># Calculate the number of tokens for each document<br>counts = [num_tokens_from_string(d, &quot;cl100k_base&quot;) for d in docs_texts]<br><br># Plotting the bar plot of token counts<br>plt.figure(figsize=(10, 6))<br>bars = plt.bar(doc_names, counts, color=&quot;blue&quot;, edgecolor=&quot;black&quot;, alpha=0.7)<br># Annotate bars with the token count<br>for bar, count in zip(bars, counts):<br>    plt.text(bar.get_x() + bar.get_width() / 2, bar.get_height(), str(count), ha=&#39;center&#39;, va=&#39;bottom&#39;)<br><br>plt.xticks(rotation=15, ha=&#39;right&#39;)<br><br>plt.title(&quot;Token Counts per Document&quot;)<br>plt.xlabel(&quot;Document Name&quot;)<br>plt.ylabel(&quot;Token Count&quot;)<br>plt.grid(axis=&quot;y&quot;, alpha=0.75)<br><br># Display the bar plot<br>plt.tight_layout()<br>plt.show()</pre><h4>Insights from Visualization</h4><p>The resulting bar chart clearly shows the token count for each document. In this specific case, we observe that Raptor has an extremely high token count of <strong>44k</strong>, while Robinson has a much lower count of <strong>2.7k</strong> tokens. This disparity highlights a few critical points:</p><ol><li>The Raptor document cannot be processed in a single context window of GPT-3.5. We need to split this document into smaller chunks, ensuring each chunk fits within the 16,000 token limit. This splitting must be done carefully to preserve the context and meaning.</li><li>Including both token document in the same batch could lead to inefficient processing. The smaller document might get processed quickly, while the larger document requires more time and resources, potentially affecting latency and cost.</li></ol><p>With all that in place, let’s move on to the actual fun part we were building up to — RAG Evaluation using and opensource tool called <a href="https://docs.ragas.io/en/stable/getstarted/index.html">RAGAS</a></p><h3>Evaluating the RAG System</h3><h4>Evaluating the RAG System</h4><p>To ensure that our RAG system performs optimally, we need to evaluate it using a structured framework. RAGAS (Retrieval-Augmented Generation Assessment System) provides the tools and metrics necessary for thorough evaluation.</p><h4>Introducing RAGAS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*sj_kfRWbpNUMVkY7SOGdag.png" /></figure><p>RAGAS is a system designed to assess the performance of Retrieval Augmented Generation (RAG) models. It offers various metrics such as</p><ul><li><strong>Faithfulness</strong> Measures the factual accuracy of the generated answer with the context provided. This is done in two steps</li></ul><ol><li>Given a question and generated answer, RAGAS uses an LLM to extract the statements made by the generated answer.</li><li>Given the list of statements and the context returned, RAGAS uses an LLM to check if the statements are supported by the context. The score is obtained by dividing the number of correct statements by the total number of statements in the generated answer.</li></ol><ul><li><strong>Answer Relevancy</strong> Measures how relevant and to the point the answer is to the question. RAGAS uses an LLM to find probable questions that the generated answer could respond to and computes the similarity to the actual question asked.</li><li><strong>Context Relevancy</strong> Measures the signal-to-noise ratio in the retrieved contexts. RAGAS identifies sentences from the retrieved context needed to answer the question and calculates the ratio between the necessary sentences and the total sentences in the context.</li><li><strong>Context Recall</strong> Measures the retriever’s ability to retrieve all necessary information needed to answer the question. RAGAS checks if each statement from the ground truth answer can be found in the retrieved context and calculates the proportion of statements supported by the retrieved context.</li></ul><p>To evaluate how well our system retrieves and generates responses.</p><p>Most of the measurements do not require any labeled data, making it easier for users to run it without worrying about building a human-annotated test dataset first. In order to run ragas all, you need is a few questions and if your using context_recall luckily for us we have a question-and-answer sets provided by the team.</p><h4>Install RAGAS</h4><p>First, ensure RAGAS is installed in your environment</p><pre>pip install ragas=0.1.8 # we had thread issues with latest ragas</pre><h4>Creating an Evaluation Dataset</h4><p>We will use a predefined set of legal documents and queries to evaluate the performance of our RAG system. Here is an example evaluation dataset</p><pre>{<br>  &quot;questions&quot;: <br>      [<br>       &quot;What is the termination notice period for the employment contract?&quot;,<br>       &quot;What are the confidentiality obligations in the advisory agreement?&quot;<br>       ]<br>  &quot;ground_truths&quot;: <br>      [<br>        &quot;This is a sample contract about employment. The termination notice period is 30 days.&quot;,<br>        &quot;This advisory agreement includes confidentiality obligations that require the advisor to keep all company information confidential for a period of two years after the termination of the agreement.&quot;<br>      ]<br>}</pre><p>RAGAs accept a Dataset having features as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*DuS5MWeSQUCqmtcpERkFig.png" /></figure><h4>Define Evaluation Script</h4><p>Create an evaluation script that uses RAGAS to evaluate different configurations of our RAG system</p><p>First, we load our QA for question and the ground truth</p><pre>import yaml<br><br>def load_eval_qa():<br>    with open(&quot;data/evaluation/raptor.json&quot;, &quot;r&quot;) as f:<br>        return yaml.safe_load(f)<br>qa = load_eval_qa()</pre><p>Then, we can iterate over the questions to get the generated answers</p><pre>import requests<br><br>url = &quot;http://127.0.0.1:8000/qa/hyde_chunk300_50_test_ragas&quot;<br>answers = []<br>contexts = []<br>for q in question:<br>    data = {<br>        &quot;query&quot;: q<br>    }<br>    response = requests.post(url, json=data)<br><br>    print(response.json()[&#39;response&#39;])<br><br>    answers.append(response.json()[&#39;response&#39;])<br>    contexts.append(response.json()[&#39;context&#39;])</pre><p>Once that is done our API returns with the context it uses and its generated answer for the question, so we will build a dataset that we can use to evaluate our RAG</p><pre>from datasets import Dataset<br># To dict<br>data = {<br>    &quot;question&quot;: question,<br>    &quot;answer&quot;: answers,<br>    &quot;contexts&quot;: contexts,<br>    &quot;ground_truth&quot;: ground_truth<br>}<br><br># Convert dict to dataset<br>dataset = Dataset.from_dict(data)</pre><p>Now, run the evaluation script with different configurations to assess the performance of various chunking and retrieval strategies. Analyze the results to determine which configuration provides the best performance based on the defined metrics.</p><pre>from ragas import evaluate<br>from langchain_openai import ChatOpenAI<br>from ragas.metrics import (<br>    faithfulness,<br>    answer_relevancy,<br>    context_recall,<br>    context_precision,<br>)<br><br>result = evaluate(<br>    dataset = dataset, <br>    llm = ChatOpenAI(model=&quot;gpt-4-preview&quot;, temperature=0), # use gpt-4o to increase context window, but has high cost<br>    metrics=[<br>        context_precision,<br>        context_recall,<br>        faithfulness,<br>        answer_relevancy,<br>    ],<br>)</pre><h4>Now that we run it what is Next?</h4><p>After running the evaluation script, analyze the results to identify the best-performing configuration. Compare the scores for faithfulness, answer relevancy, context relevancy, and context recall across different configurations to determine which setup yields the most accurate and relevant responses.</p><p>In our case we Implemented different, query translations retrievers (indexing mechanism), chunking strategies and text spliters from semantic to simple recursive splitters and here are the reports</p><h4>Evaluation Configurations</h4><p>We tested several configurations with different chunking methods, chunk sizes, query translations and retrieval strategies. The configurations included</p><ul><li>Rag Fusion with Chunk Size 300, Chunk Overlap 50</li><li>Recursive Chunking with Chunk Size 300, Chunk Overlap 50</li><li>Semantic Chunking</li><li>Character Chunking with Chunk Size 2000, Chunk Overlap 300</li><li>Chunk Size 200, Chunk Overlap 30</li><li>Text Character Splitter Chunk Size 2000, Chunk Overlap 300</li><li>Sentence Splitter Chunk Size 300, Chunk Overlap 50</li><li>Multi Query Retrieval</li><li>Rag Fusion with Chunk Size 200, Chunk Overlap 30</li></ul><p>We started with a simple recursive text splitter with chunk size 2000 but got a terrible result in overall efficiency which was around 61%</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*C53YWVeqHXKskae22W5uog.png" /></figure><p>we can see that context recall is also very low i.e. <strong>38%</strong> which says a lot about either the retriever or the query since both of which affect what context can be given to the LLM</p><p>So, we implemented a query transformation.</p><h3>Query transformations</h3><p>Since the search query to retrieve additional context in a RAG pipeline is also embedded into the vector space, its phrasing can also impact the search results as we can see from the above context recall score. Thus, our search query did not get us a satisfactory search results, we shall experiment with various <a href="https://blog.langchain.dev/query-transformations/">query transformation</a> techniques, some which we implemented so far are</p><ul><li><strong>RAG Fusion</strong> Use an LLM to rephrase the query and try again.</li><li><strong>Hypothetical Document Embeddings (HyDE)</strong> Use an LLM to generate a hypothetical response to the search query and use both for retrieval.</li><li><strong>Multi Queries</strong> Break down longer queries into multiple shorter queries.</li></ul><h4>Evaluation Test with Multi Query</h4><p>With our multi query tested with chunk size reduced to 300 and overlap 20 we got the result as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*DLqNPo5WQj7uuytvqiytwA.png" /></figure><p>The average total score has increased significantly to <strong>79.28%</strong> which will be the top 3rd method so far, as we will see shortly, also something to note is context recall nearly doubled to <strong>60.71%</strong> from <strong>38% </strong>which is a significant improvement. while also seeing improving in generation part of RAG with answer relevancy getting to <strong>98.07%</strong> from <strong>74.5% </strong>which is also a significant improvement just by changing chunk size and query translation methods.</p><h4>Evaluation Test with <strong>Hypothetical Document Embeddings (HyDE)</strong></h4><p>With the HyDe method of query translation we found that our RAG performed poorly on all benchmarks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*obe94yCicSiFPt7b6MWQBA.png" /></figure><p>With the same result as with our initial one.</p><h4>Evaluation Test with RAG Fusion — RRF</h4><p>The RAG Fusion technique uses a programming language, vector search database, LLM with query generation, and results re-ranking steps. Reciprocal Rank Fusion (RRF), is a data re-ranking technique deployed to combine the results from different queries seamlessly. It aims to organize the search results in a unified ranking, improving the accuracy of relevant information.</p><p>Our metrics with RAG fusion and chunk size 300 and chunk overlap of 50 reveled an outstanding metrics above all the metrics we tested on previously, scoring <strong>81.09%</strong> on all benchmarks and one of the highest in answer relevancy and context precision</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*D0CeV_Rlv8yrNYp5Si3e6g.png" /></figure><p>However, context recall has plunged the explanation could be, the generations scores have increased while also increased retrieval had a role to play</p><h3>Indexing</h3><p>Indexing mechanisms play a crucial role in Retrieval-Augmented Generation (RAG) and RAPTOR systems by enabling efficient and accurate retrieval of relevant documents or passages from a large corpus</p><h4>RAPTOR - Recursive Abstractive Processing for Tree-Organized Retrieval</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*95v0K13O2rvsAYJ96ldhew.png" /></figure><p>The <a href="https://arxiv.org/pdf/2401.18059.pdf">RAPTOR</a> paper presents an interesting approaching for indexing and retrieval of documents</p><ul><li>The leafs are a set of starting documents</li><li>Leafs are embedded and clustered</li><li>Clusters are then summarized into higher level (more abstract) consolidations of information across similar documents</li></ul><p>This process is done recursively, resulting in a “tree” going from raw docs (leafs) to more abstract summaries.</p><p>In our RAPTOR implementation we used a <a href="https://github.com/parthsarthi03/raptor">GitHub repo</a> for raptor implementation.</p><p>RAPTOR’s implementation has significantly increased the RAGs ability both in overall and context recall evaluations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*XbJ56hmo5QjwvkLkWanvQQ.png" /></figure><p>This is a really impresive data as we can see raptor has out performed all the other RAG implementations. So, are we done.</p><p>No, we are far from done, the above evaluation report is for the robinson document Q&amp;A as seen earlier the token count is small and could fit in a small context window. Although the raptor performed well here in the longer document performed almost the same with our previous top methods like rag fusion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*WaIwx14KUwxu2Gi-zRwM_g.png" /></figure><h3>Optimizing with Hybrid Search &amp; Reranking</h3><p>Hybrid search, on the other hand, combines the strengths of dense (Vector) and sparse (Keyword) search methods, unlocking new levels of efficiency and accuracy. Hybrid search is flexible and can be adapted to tackle a wider range of information needs.</p><h4>What is Hybrid Search?</h4><p>word embeddings are used to represent data in the vector database, and vector similarity search is commonly used for searching through them. For LLMs and RAG systems, embeddings — because they capture semantic relationships between words — are generally preferred over keyword-based representations like Bag-of-words (BoW) approaches.</p><blockquote>“keyword search is not as good as vector similarity search at fetching relevant results based on semantic relationships or meaning, which are only available via word embeddings. For example, a keyword search will relate the words <em>“the river bank”</em> and <em>“the Bank of America”</em> even though there is no actual semantic connection between the terms — a difference to which vector similarity search is sensitive. Keyword search would, therefore, benefit from vector search, but the prevailing approach is not to combine them but rather to implement them separately using distinct methodologies.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*OR_Uy0_XghtSMtLZAeVbRg.png" /><figcaption>Full credit to <a href="https://superlinked.com/vectorhub/articles/optimizing-rag-with-hybrid-search-reranking">Optimizing RAG with Hybrid Search &amp; Reranking | VectorHub by Superlinked</a></figcaption></figure><p>In our implementation of Hybrid search we aimed to implement using both third party apps like <a href="https://weaviate.io/">Welcome</a> and Chroma (Chroma database does not support hybrid yet), while Weaviate implements reranking internally when using hybrid.</p><p><strong>Implementation</strong></p><p>We added both implementation to our retriever class to be instantiated with our config file implemented earlier.</p><pre>class Retriever:<br>    def __init__(self, documents: list):<br>        self.documents = documents<br><br>        self.persist_directory = &#39;db&#39;<br><br>        self.retriever_type = config[&quot;retriever&quot;]<br><br>        if config[&quot;retriever&quot;] == &quot;dense&quot;:<br>            self.retriever = Chroma(persist_directory=self.persist_directory, embedding_function=OpenAIEmbeddings())<br><br>        elif config[&quot;retriever&quot;] == &quot;hybrid&quot;:<br>            print(&quot;We are Using Weaviate Hybrid Search Retriever&quot;)<br>            import weaviate<br><br>            auth_config = weaviate.auth.AuthApiKey(api_key=os.getenv(&quot;WEAVIATE_API_KEY&quot;))<br><br>            client = weaviate.Client(<br>                url=&quot;https://sandbox-rag-hrim3oyf.weaviate.network&quot;,<br>                additional_headers={<br>                        &quot;X-Openai-Api-Key&quot;: os.getenv(&quot;OPENAI_API_KEY&quot;),<br>                },<br>                auth_client_secret=auth_config<br>            )<br><br>            self.retriever = WeaviateHybridSearchRetriever(<br>                client=client,<br>                index_name=&quot;LizzyAi&quot;,<br>                text_key=&quot;text&quot;,<br>                attributes=[],<br>                create_schema_if_missing=True,<br>            )<br>            print(&quot;Loaded the Hybrid Search Retriever&quot;, self.retriever)<br>        else:<br>            raise ValueError(&quot;Invalid retriever type&quot;)<br>            <br>    def store_documents(self, documents: list[Document]):<br>        logger.info(f&quot;Storing documents From function {len(documents)}&quot;)<br><br>        splits = get_text_splitter().split_documents(documents)<br><br>        logger.info(f&quot;Splits {len(splits)}&quot;)<br><br>        docs = self.retriever.add_documents(splits)<br>        <br>        logger.info(f&quot;Documents added {docs[0]}&quot;)</pre><p>Then all we have to do is add our retriever to our config file named <strong>“hybrid”</strong></p><h4>Running Evals on Hybrid Database</h4><p>The hybrid search appears to perform better in providing a specific and detailed response to the query, but performed slightly better when coupled with rag fusion query transformation, the results were</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*TSsW8UQG4n-JivW7WIOBEw.png" /></figure><p>As it can be seen some metrics such as context precision were performing well but through our previous tests this could be regarded as average. The above is a benchmark on raptor dataset.</p><h3>Building a Chat Interface with React — Frontend Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q49MyWbJnhfs885_28Wzlw.png" /></figure><h4>Frontend Implementation</h4><p>The frontend is implemented using React, which allows us to create a dynamic and responsive chat interface. Our goal is to fetch the conversation data from the backend and display it in an organized and aesthetically pleasing manner.</p><h4>Component Structure</h4><p>We have two main components in our chat interface:</p><ol><li><strong>Conversation List </strong>Displays the list of recent conversations.</li><li><strong>Messages </strong>Displays the chat history for a selected conversation.</li></ol><h4>Fetching Data</h4><p>We use the useEffect hook to fetch conversation and history data when the component mounts. The data is stored in the state using the useState hook.</p><h4>Displaying Conversations</h4><p>The Conversation component is responsible for displaying the list of recent conversations. Each conversation shows a truncated version of the last AI message and the time it was sent.</p><h4>Displaying Messages</h4><p>The Messages component displays the chat history for the selected conversation. It ensures that both AI and human messages are displayed correctly without distorting the layout. sample code is as follows</p><pre>import React from &#39;react&#39;;<br><br>const Messages = ({ history }) =&gt; {<br>    console.log(&quot;The history prop is in messages :: &quot;, history);<br><br>    const filtered_history = history.filter((item) =&gt; item.session_id === &quot;test_ragas&quot;);<br><br>    const top_messages = filtered_history.slice(0, 15);<br><br>    console.log(&quot;The top messages props is :: &quot;, top_messages);<br><br>    const getAIMessage = (message, timestamp) =&gt; {<br>        return (<br>            &lt;div className=&quot;flex items-end w-3/4&quot; &gt;<br>                &lt;img className=&quot;w-8 h-8 m-3 rounded-full&quot; src=&quot;https://cdn.pixabay.com/photo/2017/01/31/21/23/avatar-2027366_960_720.png&quot; alt=&quot;avatar&quot; /&gt;<br>                &lt;div className=&quot;p-3 mx-3 dark:bg-gray-800 my-1 rounded-2xl rounded-bl-none max-w-full break-words&quot;&gt;<br>                    &lt;div className=&quot;text-xs text-gray-600 dark:text-gray-200&quot;&gt;<br>                        Lizzy<br>                    &lt;/div&gt;<br>                    &lt;div className=&quot;text-gray-700 dark:text-gray-200&quot;&gt;<br>                        {message}<br>                    &lt;/div&gt;<br>                    &lt;div className=&quot;text-xs text-gray-100 dark:text-gray-300 flex justify-end&quot;&gt;<br>                        {timestamp}<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        );<br>    };<br><br>    const getHumanMessage = (message) =&gt; {<br>        return (<br>            &lt;div className=&quot;flex justify-end w-3/4 self-end&quot;&gt;<br>                &lt;div className=&quot;flex items-end bg-blue-600 m-1 rounded-xl rounded-br-none p-2 max-w-full break-words&quot;&gt;<br>                    &lt;div className=&quot;text-gray-200 w-auto&quot;&gt;<br>                        {message}<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        );<br>    };<br><br>    return (<br>        // Dynamic UI<br>    )</pre><h3>Conclusion and Limitations</h3><h4>Conclusion</h4><p>In this post, we embarked on the journey of building, evaluating, and optimizing a Retrieval-Augmented Generation (RAG) system tailored for legal documents. We covered the following key steps</p><ol><li><strong>Introduction to RAG Systems</strong> We started with an overview of RAG systems and their importance in handling complex legal texts.</li><li><strong>Setting Up the Project </strong>We set up our project environment, structured the project directories, and installed the necessary tools and libraries.</li><li><strong>Building the RAG System </strong>We configured the FastAPI backend, integrated PostgreSQL for managing chat history, and implemented a conversational QA system using OpenAI models.</li><li><strong>Evaluating the RAG System </strong>We used RAGAS to define evaluation metrics, create an evaluation dataset, and run evaluations with different configurations to analyze and compare results.</li><li><strong>Experimentation and Optimization</strong> We experimented with different chunking and retrieval strategies, swapped out components, and continuously fine-tuned the system based on evaluation results and user feedback.</li></ol><p>Through our analysis, we identified the best-performing configurations and implemented strategies to improve context recall and answer relevancy. This iterative process ensured that our RAG system remains robust and effective in handling legal queries, providing accurate and relevant responses.</p><h4>Limitations</h4><p>While our RAG system showed promising results, there are some limitations to consider</p><ol><li><strong>Scalability</strong> As the size of the document corpus grows, the retrieval process may become slower and less efficient. Implementing advanced retrieval techniques and optimizing the indexing process can help address scalability concerns.</li><li><strong>Handling Ambiguity </strong>Legal documents often contain ambiguous language and complex clauses. While our RAG system can handle straightforward queries effectively, it may struggle with highly nuanced or ambiguous questions. Incorporating more sophisticated NLP techniques and integrating external knowledge bases could improve performance in such cases.</li><li><strong>Continuous Improvement </strong>The system’s effectiveness depends on continuous improvement and regular updates based on user feedback. Establishing a robust feedback loop and actively incorporating user suggestions are crucial for maintaining the system’s accuracy and relevance.</li><li><strong>Legal Expertise</strong> For the question and answer to be refined and to understand the evaluation better Domain knowledge would help</li></ol><p>Despite these limitations, our RAG system provides a strong foundation for handling legal documents and offers significant potential for further enhancements and customization.</p><h4>Contacts</h4><p>For any questions, feedback, or further assistance, feel free to reach out</p><ul><li>GitHub: <a href="https://github.com/dev-abuke">https://github.com/dev-abuke</a></li><li>LinkedIn: <a href="https://www.linkedin.com/in/abubeker-shamil/">https://www.linkedin.com/in/abubeker-shamil/</a></li></ul><p>Thank you for following along with this post. We hope you found it informative and helpful in building your own RAG system.</p><p>Happy RAG!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db5394ca54b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Scalable Backtesting Infrastructure for Crypto and Stock Trading with Kafka, FastAPI…]]></title>
            <link>https://medium.com/@abubekershamil/building-a-scalable-backtesting-infrastructure-for-crypto-and-stock-trading-with-kafka-fastapi-267d27e14b85?source=rss-dec8d7adb524------2</link>
            <guid isPermaLink="false">https://medium.com/p/267d27e14b85</guid>
            <dc:creator><![CDATA[Abubeker]]></dc:creator>
            <pubDate>Wed, 26 Jun 2024 20:09:40 GMT</pubDate>
            <atom:updated>2024-06-27T08:51:32.761Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Scalable Backtesting Infrastructure for Crypto and Stock Trading with Kafka, FastAPI, and PostgreSQL</h3><h3>Introduction</h3><p>In the fast-paced world of cryptocurrency trading, having a robust and scalable backtesting infrastructure is crucial for testing trading strategies under historical data conditions. This project demonstrates how to build such an infrastructure using <a href="https://kafka.apache.org/">Apache Kafka</a>, <a href="https://github.com/tiangolo/fastapi">FastAPI</a>, and <a href="https://www.postgresql.org/">PostgreSQL </a>hosted on Amazon RDS. We will also touch upon integrating machine learning operations (MLOps) tools to ensure our pipeline is reliable and efficient.</p><h3>Project Overview</h3><h3>Business Need</h3><p>A startup named Mela aims to simplify cryptocurrency trading for everyone, providing investors with a reliable source of investment while reducing trading risks. Our task is to design and build a reliable, large-scale trading data pipeline that can run various backtests and store the results in a robust data warehouse system.</p><h3>Key Components</h3><ul><li><strong>FastAPI</strong> A modern, fast (high-performance) web framework for building APIs with Python 3.6+.</li><li><strong>Apache Kafka </strong>A distributed event streaming platform capable of handling trillions of events a day.</li><li><strong>PostgreSQL</strong> An open-source relational database management system emphasizing extensibility and SQL compliance, hosted on Amazon RDS.</li><li><strong>SQLAlchemy</strong> The Python SQL toolkit and Object-Relational Mapping (ORM) library.</li><li><strong>Kafka-python</strong> A Python client for Apache Kafka.</li></ul><h3><strong>Expected Outcomes</strong></h3><ul><li>Technical Analysis</li><li>Backtesting</li><li>Trading</li><li>Using Apache Kafka, MLflow, and other MLOps tools</li><li>Building data pipelines and orchestration workflows</li></ul><h3>Implementation</h3><h3>Setting Up the Environment</h3><h4>Installing Dependencies</h4><p>First, we installed the necessary dependencies:</p><pre>pip install fastapi uvicorn sqlalchemy psycopg2 kafka-python pandas</pre><h4>Configuring PostgreSQL with Amazon RDS</h4><p>We set up a PostgreSQL instance on Amazon RDS, ensuring we have a reliable and scalable database to store our data.</p><h3>Building the FastAPI Application</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r09-mfA1W_6KpjwttbvB9Q.png" /></figure><p>We created a FastAPI application to manage the backtesting process and interact with the database.</p><h3>Defining Models and Schemas</h3><p><strong>SQLAlchemy Models</strong></p><ul><li>Define your database tables using SQLAlchemy models. These models will map to your PostgreSQL tables.</li><li>Include models for Scene, BacktestResult, Indicator, and Stock.</li></ul><p><strong>Pydantic Schemas</strong></p><ul><li>Define Pydantic schemas for data validation and serialization. These schemas will be used to validate incoming data and serialize outgoing responses.</li><li>Defining Models and Schemas</li></ul><p>We defined SQLAlchemy models for our database tables and Pydantic schemas for data validation and serialization.</p><pre>from sqlalchemy import Boolean, Column, Integer, Float, Date, ForeignKey, TIMESTAMP, String, Text, text, UniqueConstraint<br>from sqlalchemy.orm import relationship<br>from .database import Base<br><br>class Indicator(Base):<br>    __tablename__ = &#39;indicators&#39;<br>    id = Column(Integer, primary_key=True, index=True)<br>    name = Column(String, nullable=False, unique=True)<br>    symbol = Column(String, nullable=False, unique=True)<br>    description = Column(Text)<br><br>class User(Base):<br>    __tablename__ = &#39;users&#39;<br>    id = Column(Integer, primary_key=True, index=True)<br>    email = Column(String, unique=True, index=True, nullable=False)<br>    hashed_password = Column(String, nullable=False)<br>    full_name = Column(String, nullable=True)<br>    is_active = Column(Boolean, default=True)<br>    is_superuser = Column(Boolean, default=False)<br>    <br>class Stock(Base):<br>    __tablename__ = &#39;stocks&#39;<br>    id = Column(Integer, primary_key=True, index=True)<br>    name = Column(String, nullable=False, unique=True)<br>    symbol = Column(String, nullable=False, unique=True)<br>    description = Column(Text)<br><br>class Scene(Base):<br>    __tablename__ = &#39;scenes&#39;<br>    id = Column(Integer, primary_key=True, index=True)<br>    period = Column(Integer, nullable=False)<br>    start_date = Column(Date, nullable=False)<br>    end_date = Column(Date, nullable=False)<br>    stock_id = Column(Integer, ForeignKey(&#39;stocks.id&#39;))<br>    indicator_id = Column(Integer, ForeignKey(&#39;indicators.id&#39;))<br>    backtests = relationship(&#39;BacktestResult&#39;, back_populates=&#39;scene&#39;)<br>    stock = relationship(&#39;Stock&#39;)<br>    indicator = relationship(&#39;Indicator&#39;)<br><br>    __table_args__ = (UniqueConstraint(&#39;start_date&#39;, &#39;end_date&#39;, &#39;indicator_id&#39;, &#39;stock_id&#39;, name=&#39;_scene_uc&#39;),)<br><br>class BacktestResult(Base):<br>    __tablename__ = &#39;backtest_results&#39;<br>    id = Column(Integer, primary_key=True, index=True)<br>    scene_id = Column(Integer, ForeignKey(&#39;scenes.id&#39;))<br>    initial_cash = Column(Float, nullable=False)<br>    final_value = Column(Float, nullable=False)<br>    percentage_return = Column(Float)<br>    total_trades = Column(Integer)<br>    winning_trades = Column(Integer)<br>    losing_trades = Column(Integer)<br>    sharpe_ratio = Column(Float)<br>    created_at = Column(TIMESTAMP, server_default=text(&#39;CURRENT_TIMESTAMP&#39;))<br>    scene = relationship(&#39;Scene&#39;, back_populates=&#39;backtests&#39;)</pre><p>The schemas are aslo defined as follows</p><pre>from pydantic import BaseModel<br>from typing import List, Optional<br>from datetime import datetime<br><br>class SceneBase(BaseModel):<br>    period: int<br>    start_date: datetime<br>    end_date: datetime<br>    indicator_id: int<br>    stock_id: int<br><br>class SceneCreate(SceneBase):<br>    pass<br><br>class Scene(SceneBase):<br>    id: int<br><br>    class Config:<br>        orm_mode = True<br><br>class BacktestResultBase(BaseModel):<br>    scene_id: int<br>    initial_cash: float<br>    final_value: float<br>    percentage_return: float<br>    total_trades: int<br>    winning_trades: int<br>    losing_trades: int<br>    sharpe_ratio: float<br><br>class BacktestResultCreate(BacktestResultBase):<br>    pass<br><br>class BacktestResult(BacktestResultBase):<br>    id: int<br>    created_at: datetime<br><br>    class Config:<br>        orm_mode = True</pre><h3>Implementing FastAPI Endpoints</h3><p><strong>CRUD Operations</strong></p><ul><li>Implement CRUD operations for Scene, BacktestResult, Indicator, Users and Stock.</li><li>Ensure each endpoint performs necessary validation and error handling.</li></ul><p><strong>Backtesting Endpoint</strong></p><ul><li>Implement an endpoint to trigger backtesting based on provided scene parameters.</li><li>Fetch historical data, run the backtest, and save the results to the database.</li></ul><h3>Setting Up CORS Middleware</h3><p><strong>Allowing Cross-Origin Requests</strong>:</p><ul><li>Configure CORS middleware to allow requests from your front-end application.</li><li>Specify the origins, methods, and headers allowed.</li></ul><h3>Integrating Kafka</h3><h3>Kafka Configuration</h3><p><strong>Producer and Consumer Setup</strong></p><ul><li>Configure Kafka producers and consumers to handle the production and consumption of scene parameters and backtest results.</li><li>Ensure the Kafka broker URL and topic names are correctly set.</li></ul><p><strong>Session Timeout and Heartbeat Interval</strong></p><ul><li>Configure session timeout and heartbeat interval settings to prevent consumer timeouts during long backtests.</li></ul><h3>Kafka Producer and Consumer</h3><p><strong>Sending Scene Parameters</strong></p><ul><li>Implement a Kafka producer to send scene parameters to the SCENE_TOPIC.</li><li>Ensure parameters are serialized correctly before sending.</li></ul><p><strong>Consuming Scene Parameters</strong></p><ul><li>Implement a Kafka consumer to listen for scene parameters on the SCENE_TOPIC.</li><li>Deserialize parameters, run the backtest, and send the results to the RESULT_TOPIC.</li></ul><p><strong>Attaching Backtest Results</strong></p><ul><li>After running a backtest, save the results to the database and send them to Kafka.</li><li>Attach the backtest results to the corresponding scene for later retrieval.</li></ul><pre>from kafka import KafkaProducer, KafkaConsumer<br>import json<br><br>KAFKA_BROKER_URL = &#39;localhost:9092&#39; # can be changed to a remote kafka url<br>SCENE_TOPIC = &#39;scene_parameters&#39;<br>RESULT_TOPIC = &#39;backtest_results&#39;<br><br>def get_kafka_producer():<br>    return KafkaProducer(<br>        bootstrap_servers=KAFKA_BROKER_URL,<br>        value_serializer=lambda v: json.dumps(v).encode(&#39;utf-8&#39;)<br>    )<br><br>def get_kafka_consumer(topic):<br>    return KafkaConsumer(<br>        topic,<br>        bootstrap_servers=KAFKA_BROKER_URL,<br>        auto_offset_reset=&#39;earliest&#39;,<br>        enable_auto_commit=True,<br>        group_id=&#39;my-group&#39;,<br>        session_timeout_ms=30000,<br>        heartbeat_interval_ms=10000,<br>        value_deserializer=lambda x: json.loads(x.decode(&#39;utf-8&#39;))<br>    )</pre><h3>Running Backtests</h3><h3>Backtest Logic</h3><p><strong>Implementing Backtest Functions</strong></p><ul><li>Create functions to fetch historical data and run backtests based on scene parameters.</li><li>We must ensure the results include necessary metrics such as</li></ul><blockquote>initial cash</blockquote><blockquote>final value</blockquote><blockquote>percentage return</blockquote><blockquote>total trades</blockquote><blockquote>winning trades</blockquote><blockquote>losing trades</blockquote><blockquote>sharpe ratio</blockquote><h3>Saving Backtest Results</h3><p><strong>Database Operations</strong></p><ul><li>Save backtest results to the PostgreSQL database.</li><li>Ensure results are correctly linked to the corresponding scene.</li></ul><h3>Fetching and Displaying Results</h3><p><strong>Fetching Results</strong></p><ul><li>Implement endpoints to fetch backtest results based on scene ID.</li><li>Ensure results are serialized correctly for the front-end application.</li></ul><p><strong>backtesting.py</strong></p><pre>import yfinance as yf<br>import backtrader as bt<br>import os, sys<br><br>project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), &#39;../../&#39;))<br>if project_root not in sys.path:<br>    sys.path.append(project_root)<br><br>from scripts.backtesting.util.user_input import get_user_input<br>from scripts.backtesting.analyzers.metrics_analyzer import MetricsAnalyzer<br><br>def run_backtest(config):<br>    initial_cash = config[&#39;initial_cash&#39;]<br>    start_date = config[&#39;start_date&#39;]<br>    end_date = config[&#39;end_date&#39;]<br>    ticker = config[&#39;ticker&#39;]<br>    indicator = config[&#39;indicator&#39;]<br><br>    # Fetch historical data<br>    try:<br>        data = yf.download(ticker, start=start_date, end=end_date)<br>        data_feed = bt.feeds.PandasData(dataname=data)<br>    except Exception as e:<br>        print(f&quot;Error fetching data: {e}&quot;)<br>        return<br><br>    # Initialize Cerebro engine<br>    cerebro = bt.Cerebro()<br>    cerebro.adddata(data_feed)<br>    cerebro.broker.setcash(initial_cash)<br><br>    # Add strategy based on selected indicator<br>    if indicator == &#39;SMA&#39;:<br>        from scripts.backtesting.strategies.sma_strategy import SMAStrategy<br>        cerebro.addstrategy(SMAStrategy)<br>    elif indicator == &#39;LSTM&#39;:<br>        from scripts.backtesting.strategies.lstm_strategy import LSTMStrategy<br>        cerebro.addstrategy(LSTMStrategy)<br>    elif indicator == &#39;MACD&#39;:<br>        from scripts.backtesting.strategies.macd_strategy import MACDStrategy<br>        cerebro.addstrategy(MACDStrategy)<br>    elif indicator == &#39;RSI&#39;:<br>        from scripts.backtesting.strategies.rsi_strategy import RSIStrategy<br>        cerebro.addstrategy(RSIStrategy)<br>    elif indicator == &#39;Bollinger Bands&#39;:<br>        from scripts.backtesting.strategies.bollinger_bands_strategy import BollingerBandsStrategy<br>        cerebro.addstrategy(BollingerBandsStrategy)<br>    else:<br>        print(&quot;Invalid indicator selected.&quot;)<br>        return<br><br>    # Add analyzers<br>    cerebro.addanalyzer(bt.analyzers.SharpeRatio, riskfreerate=0.0, _name=&#39;sharperatio&#39;)<br>    cerebro.addanalyzer(MetricsAnalyzer, _name=&#39;MetricsAnalyzer&#39;)<br><br>    # Run backtest<br>    results = cerebro.run()<br>    strat = results[0]<br>    metrics_analyzer = strat.analyzers.getbyname(&#39;MetricsAnalyzer&#39;)<br>    metrics = metrics_analyzer.get_analysis()<br><br>    return {<br>        &#39;initial_cash&#39;: initial_cash,<br>        &#39;final_value&#39;: cerebro.broker.getvalue(),<br>        &#39;sharpe_ratio&#39;: strat.analyzers.sharperatio.get_analysis()[&#39;sharperatio&#39;],<br>        &#39;percentage_return&#39;: metrics[&#39;return&#39;],<br>        &#39;total_trades&#39;: metrics[&#39;trades&#39;],<br>        &#39;winning_trades&#39;: metrics[&#39;winning_trades&#39;],<br>        &#39;losing_trades&#39;: metrics[&#39;losing_trades&#39;]<br>    }<br>    run_backtest(config)</pre><h3>Creating and Fetching Scenes</h3><p>We implemented endpoints to create scenes, run backtests, and fetch results.</p><h3>Step 5: Creating and Fetching Scenes</h3><p><strong>Creating New Scenes</strong></p><ul><li>Implement an endpoint to create new scenes based on provided parameters.</li><li>Validate parameters and save the new scene to the database.</li></ul><h3>Fetching Scenes</h3><p><strong>Fetching Scenes</strong></p><ul><li>Implement an endpoint to fetch scenes from the database.</li><li>Ensure scenes include related data such as indicators and stocks.</li></ul><pre><br>@app.post(&#39;/scenes/&#39;, response_model=schemas.Scene)<br>def create_scene(scene: schemas.SceneCreate, db: Session = Depends(get_db)):<br>    try:<br>        db_scene = models.Scene(**scene.dict())<br>        db.add(db_scene)<br>        db.commit()<br>        db.refresh(db_scene)<br>        print(&quot;Scene created successfully:&quot;, db_scene)<br><br>        # Send scene parameters to Kafka<br>        scene_parameters = {<br>            &#39;scene_id&#39;: db_scene.id,<br>            &#39;period&#39;: db_scene.period,<br>            &#39;initial_cash&#39;: 500,<br>            &#39;indicator_name&#39;: db_scene.indicator.name,<br>            &#39;indicator&#39;: db_scene.indicator.symbol,<br>            &#39;stock_name&#39;: db_scene.stock.name,<br>            &#39;ticker&#39;: db_scene.stock.symbol,<br>            &#39;start_date&#39;: db_scene.start_date.strftime(&#39;%Y-%m-%d&#39;),<br>            &#39;end_date&#39;: db_scene.end_date.strftime(&#39;%Y-%m-%d&#39;)<br>        }<br>        print(&quot;Sending scene parameters to Kafka:&quot;, scene_parameters)<br>        producer.send(SCENE_TOPIC, scene_parameters)<br>        print(&quot;Scene parameters sent to Kafka&quot;)<br>        producer.flush()<br>        print(&quot;Scene flushed successfully:&quot;)<br><br>        return db_scene<br>    except IntegrityError:<br>        db.rollback()<br>        existing_scene = db.query(models.Scene).filter(<br>            models.Scene.start_date == scene.start_date,<br>            models.Scene.end_date == scene.end_date,<br>            models.Scene.indicator_id == scene.indicator_id<br>        ).first()<br>        return existing_scene<br><br>@app.delete(&#39;/scenes/{scene_id}&#39;, response_model=schemas.Scene)<br>def delete_scene(scene_id: int, db: Session = Depends(get_db)):<br>    db_scene = db.query(models.Scene).options(joinedload(models.Scene.indicator), joinedload(models.Scene.stock)).filter(models.Scene.id == scene_id).first()<br>    if db_scene is None:<br>        raise HTTPException(status_code=404, detail=&quot;Scene not found&quot;)<br>    db.delete(db_scene)<br>    db.commit()<br>    return db_scene<br><br>@app.get(&#39;/scenes/{scene_id}&#39;, response_model=schemas.Scene)<br>def read_scene(scene_id: int, db: Session = Depends(get_db)):<br>    db_scene = db.query(models.Scene).options(joinedload(models.Scene.indicator), joinedload(models.Scene.stock)).filter(models.Scene.id == scene_id).first()<br>    if db_scene is None:<br>        raise HTTPException(status_code=404, detail=&quot;Scene not found&quot;)<br>    return db_scene</pre><h3>LSTM Model Implementation using TensorFlow</h3><p>This documentation describes the step-by-step process for implementing an LSTM (Long Short-Term Memory) model using TensorFlow for forecasting and anomaly detection on time series data.</p><h3>Prerequisites</h3><p>Ensure you have the following libraries installed</p><pre>pip install pandas nixtla statsforecast tensorflow scikit-learn joblib</pre><h3>Implementation</h3><h3>1. Import Required Libraries</h3><p>First, import the necessary libraries</p><pre>import pandas as pd<br>import numpy as np<br>from sklearn.preprocessing import MinMaxScaler<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import LSTM, Dense, Dropout<br>import joblib</pre><h3>Data Preparation for LSTM</h3><p>Prepare the data for LSTM model training</p><p>Load the historical data. This data will be used for both forecasting future values and detecting anomalies.</p><ul><li><strong>Create Sequences </strong>Implement a function to create sequences of data points from the time series data.</li><li><strong>Scale Data </strong>Normalize the data using MinMaxScaler to ensure the LSTM model trains effectively.</li></ul><pre>def create_sequences(data, seq_length):<br>    sequences = []<br>    for i in range(len(data) - seq_length):<br>        sequences.append(data[i:i + seq_length])<br>    return np.array(sequences)<br><br>def prepare_lstm_data(df, target_column, seq_length):<br>    data = df[target_column].values.reshape(-1, 1)<br>    scaler = MinMaxScaler(feature_range=(0, 1))<br>    scaled_data = scaler.fit_transform(data)<br>    <br>    X = []<br>    y = []<br>    for i in range(seq_length, len(scaled_data)):<br>        X.append(scaled_data[i-seq_length:i, 0])<br>        y.append(scaled_data[i, 0])<br>    <br>    X, y = np.array(X), np.array(y)<br>    X = np.reshape(X, (X.shape[0], X.shape[1], 1))<br>    return X, y, scaler</pre><h3>Build and Train the LSTM Model</h3><p>Build the LSTM model</p><p>Construct the LSTM model using TensorFlow’s Keras API. The model will have multiple layers, including LSTM layers and dropout layers to prevent overfitting.</p><ul><li><strong>Build the Model</strong> Define the architecture of the LSTM model, specifying the number of LSTM units, dropout rates, and the optimizer.</li><li><strong>Train the Model</strong> Train the model on the prepared data, specifying the number of epochs and batch size. we will use a validation split to monitor the model’s performance on unseen data during training.</li></ul><pre>def build_lstm_model(input_shape):<br>    model = Sequential()<br>    model.add(LSTM(50, return_sequences=True, input_shape=input_shape))<br>    model.add(Dropout(0.2))<br>    model.add(LSTM(50, return_sequences=False))<br>    model.add(Dropout(0.2))<br>    model.add(Dense(1))<br>    <br>    model.compile(optimizer=&#39;adam&#39;, loss=&#39;mean_squared_error&#39;)<br>    return model</pre><p>Train the LSTM model</p><pre>def train_lstm_model(model, X_train, y_train, epochs=50, batch_size=32):<br>    model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2)<br>    return model</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*vDh-6OoDapII6RLbll9Zeg.png" /></figure><h3>Save the Model and Scaler</h3><p>Save the trained model and the scaler</p><pre>lstm_model.save(&#39;my_model.keras&#39;)<br>joblib.dump(scaler, &#39;scaler.gz&#39;)</pre><h3>Model Predictions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*nakQfh4NP9c6Biz3YFW1fA.png" /></figure><h3>Front-End Integration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjYH_ERfqGnd7BGC0DXzHw.png" /></figure><h3>Front-End Setup</h3><p><strong>Creating the Front-End Application</strong></p><ul><li>Use a front-end framework like React or Vue.js to create the user interface.</li><li>Set up components for creating scenes, running backtests, and displaying results.</li></ul><p><strong>Connecting to the Backend</strong></p><ul><li>Use Axios or Fetch API to connect to the FastAPI backend.</li><li>Handle API requests and responses to interact with the back-end application.</li></ul><h3>User Interface</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TfWKJc52g5qWTnC-JVSqiA.png" /><figcaption><a href="https://www.figma.com/design/S2zn2nBwYO6WfRN0qui9TF/Backtest?node-id=0-1&amp;t=ZPVTjTjVR1ctS9RI-0">Backtest — Figma</a></figcaption></figure><p><strong>Creating Scenes</strong></p><ul><li>Implement a form to create new scenes.</li><li>Validate user input and send the data to the back-end API.</li></ul><p><strong>Displaying Results</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQONZcQrcj8zbXk4Wg34hA.png" /></figure><ul><li>Create components to display backtest results.</li><li>Ensure results are presented in a user-friendly manner with charts and tables.</li></ul><h3>Future Plan</h3><h3>1. Enhancing Backtesting Algorithms</h3><ul><li><strong>Advanced Technical Indicators </strong>Incorporate more complex and varied technical indicators to provide deeper insights and more robust trading strategies.</li><li><strong>Machine Learning Models </strong>Integrate diverse machine learning models to predict market movements and improve strategy performance.</li><li><strong>Real-Time Data Integration</strong> Implement real-time data feeds to enable live backtesting and strategy refinement.</li></ul><h3>2. Scaling Infrastructure</h3><ul><li><strong>Distributed Computing</strong> Leverage distributed computing resources such as AWS Lambda or Apache Spark to handle large-scale backtesting and data analysis.</li><li><strong>Microservices Architecture </strong>Break down the application into microservices for better scalability, maintainability, and fault isolation.</li><li><strong>Load Balancing</strong> Implement load balancing techniques to distribute the workload evenly across servers, improving performance and reliability.</li></ul><h3>3. User Experience Enhancements</h3><ul><li><strong>Interactive Dashboards </strong>Develop interactive dashboards with advanced visualization tools like D3.js or Plotly to provide users with detailed and customizable views of backtest results.</li><li><strong>User-Friendly Interface </strong>Continuously improve the user interface to make it more intuitive and accessible, ensuring a seamless user experience.</li></ul><h3>Limitations</h3><h3>1. Data Quality and Availability</h3><ul><li><strong>Historical Data Limitations </strong>The accuracy of backtests is heavily dependent on the quality and completeness of historical data. Any gaps or inaccuracies in the data can lead to misleading results.</li><li><strong>Market Changes </strong>Backtesting relies on historical data, which may not accurately reflect future market conditions. Sudden market changes or unprecedented events can render backtest results less reliable.</li></ul><h3>2. Computational Resources</h3><ul><li><strong>Resource Intensive </strong>Backtesting, especially for complex strategies, can be computationally intensive and time-consuming. Scaling up computational resources is essential but can also be costly.</li><li><strong>Real-Time Processing </strong>Implementing real-time data processing and backtesting can introduce latency and require significant optimization efforts.</li></ul><h3>3. User Knowledge and Skills</h3><ul><li><strong>Technical Expertise Required </strong>Users need a certain level of technical expertise to set up and use the platform effectively. This can be a barrier for novice traders.</li><li><strong>Strategy Complexity </strong>More advanced features and strategies may require deep knowledge of financial markets and trading algorithms, limiting accessibility for less experienced users.</li></ul><h3>Conclusion</h3><p>This project demonstrates the development of a robust, scalable backtesting infrastructure for cryptocurrency trading. By integrating FastAPI, Apache Kafka, PostgreSQL, and MLOps tools like MLflow, we have created a platform capable of handling large volumes of trading data, running complex backtests, and providing insightful analysis.</p><h3>Key Achievements</h3><ul><li><strong>Scalable Infrastructure</strong>: Leveraged Kafka for efficient data streaming and FastAPI for a high-performance API, ensuring the platform can scale to meet increasing demands.</li><li><strong>Reliable Data Storage</strong>: Utilized PostgreSQL on Amazon RDS for reliable and scalable data storage, ensuring data integrity and accessibility.</li><li><strong>Comprehensive Backtesting</strong>: Implemented detailed backtesting functionality, allowing users to test and refine their trading strategies using historical data.</li><li><strong>User Interface</strong>: Designed a user-friendly front-end application to facilitate seamless interaction with the back-end services.</li></ul><h3>Next Steps</h3><p>The future plan outlines several enhancements, including the integration of advanced algorithms, scaling the infrastructure, and improving user experience. Addressing the limitations will be crucial to ensuring the platform remains reliable, secure, and user-friendly.</p><h3>Contact</h3><p>For more information, questions, or support, please feel free to reach out to me through the following channels:</p><ul><li><strong>GitHub</strong>: <a href="https://github.com/dev-abuke">dev-abuke</a></li><li><strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/abubeker-shamil/">Abubeker Shamil</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=267d27e14b85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Optimization — Optimizing Delivery Location with Causal Inference — What IF?]]></title>
            <link>https://medium.com/@abubekershamil/logistic-optimization-optimizing-delivery-location-with-causal-inference-what-if-897a622cbdfc?source=rss-dec8d7adb524------2</link>
            <guid isPermaLink="false">https://medium.com/p/897a622cbdfc</guid>
            <dc:creator><![CDATA[Abubeker]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 20:57:19 GMT</pubDate>
            <atom:updated>2024-06-18T13:58:48.460Z</atom:updated>
            <content:encoded><![CDATA[<h3>Logistic Optimization — Optimizing Delivery Location with Causal Inference — Answering “What IF?” Questions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gvtjfA6heFSFRhXiDmkxfw.png" /><figcaption>Gokada app UI from official website</figcaption></figure><p><a href="https://www.gokada.ng/">Gokada</a> — the largest last mile delivery service in Nigeria. Gokada partnered with motorbike owners and drivers to deliver parcels across Lagos, Nigeria.</p><p><strong>Problem statement — </strong>One key issue Gokada has faced as it expands its service is the sub-optimal placement of <a href="https://www.gokada.ng/superapp">pilots</a> (Gokada calls their motor drivers pilots) and clients who want to use Gokada to send their parcel. This has led to a high number of unfulfilled delivery requests.</p><h3>Why Causal Inference — Understanding “What If” Scenarios</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*x48kuZd_uhFtGDv9I7XqUg.png" /></figure><p>Causal inference is a statistical framework that goes beyond correlation to establish cause-and-effect relationships between variables. Developed extensively by Judea Pearl and others, this approach allows us to answer questions about how changing one variable will impact another, providing actionable insights for decision-making.</p><p><strong>What is a “What If” Scenario?</strong> A “What If” scenario, also known as a counterfactual, explores the outcomes that would have occurred if a different action or condition had been in place. In the context of causal inference, it allows us to simulate and predict the effects of hypothetical changes, such as altering driver routes or adjusting operational strategies.</p><h3>Understanding Concepts in Causal Inference</h3><p><strong>1. Causal Graphs (Directed Acyclic Graphs — DAGs)</strong> Causal graphs visually represent the relationships between variables using nodes (representing variables) and directed edges (representing causal influences). These graphs help identify which variables directly affect the outcome of interest and how different variables are interrelated.</p><p><strong>2. The “do” Operator</strong> The “do” operator is a fundamental concept in causal inference introduced by Judea Pearl. It represents an intervention in a system, allowing us to estimate the effect of forcibly setting a variable to a particular value. For example, “do(X = x)” represents setting the variable X to value x and observing the resulting changes in other variables.</p><h3>Steps to Perform Causal Inference</h3><ol><li><strong>Define the Problem</strong> Identify the key question or hypothesis you want to test. For example,</li></ol><blockquote>“What if drivers moved 1 km every 30 minutes in a selected direction?”</blockquote><ol><li><strong>Construct the Causal Graph </strong>Build a causal graph to represent the relationships between the variables involved. This involves using expert knowledge, data-driven insights, and algorithms to identify causal connections.</li><li><strong>Estimate the Causal Effect </strong>Use statistical techniques and the “do” operator to estimate the impact of the intervention. This often involves computing counterfactuals and potential outcomes based on the constructed causal graph.</li></ol><h3>Causal Inference for Gokada’s Problem</h3><blockquote>“What will happen to the number of completed orders if drivers are recommended to move 1 km every 30 minutes in a selected direction?”</blockquote><h4><strong>Define the Variables</strong></h4><ul><li><strong>X:</strong> Driver movement (1 km every 30 minutes)</li><li><strong>Y:</strong> Number of completed orders</li><li><strong>Z:</strong> Other influencing factors (e.g., traffic conditions, weather, time of day)</li></ul><h4><strong>Construct the Causal Graph</strong></h4><ul><li>Nodes: Driver Movement (X), Completed Orders (Y), Traffic (Z1), Weather (Z2), Time of Day (Z3)</li><li>Edges: Directed edges from X to Y, Z1 to Y, Z2 to Y, and Z3 to Y</li></ul><h4><strong>Intervene and Estimate</strong></h4><ul><li>Use the “do” operator to simulate the intervention: “do (Driver Movement = 1 km every 30 minutes)”</li><li>Estimate the change in the number of completed orders (Y) based on this intervention.</li></ul><h4><strong>Compute the Counterfactuals</strong></h4><ul><li>Calculate the expected number of completed orders if the intervention is applied.</li><li>Compare this with the actual number of completed orders to understand the impact.</li></ul><p>To assist Gokada in understanding the primary causes of unfulfilled requests and to recommend driver locations that increase the fraction of completed orders, we will approach this challenge in several steps to get to the causal inference recommendation</p><p><strong>Data Analysis</strong></p><ul><li>Perform an <strong>Exploratory Data Analysis (EDA)</strong> on the historical data to identify patterns and factors leading to unfulfilled requests1.</li><li>Clean the data by removing entries with missing values and merging relevant tables to prepare for analysis1.</li></ul><p><strong>Feature Engineering</strong></p><ul><li>Generate new features such as month, day, weekday, and hour from the trip start time.</li><li>Calculate the driver’s proximity to the order and the trip distance, duration, and speed if available.</li></ul><p><strong>Causal Inference</strong></p><ul><li>Use <a href="https://github.com/niyotham/causal_inference">causal inference</a> methodologies to build a structural model that can help understand the relationships between different variables and unfulfilled requests1.</li><li>Generate hypotheses and test them using the data, such as the impact of moving drivers 1km every 30 mins or knowing the location of the next 20% of orders within 5km accuracy1.</li></ul><p><strong>Optimization Strategies</strong></p><ul><li>Implement route optimization to minimize total driving time, considering factors like delivery time windows, vehicle load capacity, driver schedule, and traffic conditions<a href="https://onfleet.com/blog/route-optimization/">2</a>.</li><li>Use dynamic route planning technology to prioritize orders, adhere to commitments, and leverage drivers’ input for more efficient deliveries<a href="https://insights.workwave.com/industry/logistics-distribution/7-simple-ways-to-increase-your-delivery-efficiency/">3</a>.</li></ul><p><strong>Visualization and Recommendations</strong></p><ul><li>Create heatmaps to visualize high-demand areas and recommend driver locations accordingly <a href="https://medium.com/@Meg_Chepy/logistic-optimization-using-causal-inferencing-51c17c867a79"><em>4</em></a><em>.</em></li><li>Develop an algorithm that can dynamically suggest hotspots to drivers based on real-time order requests and traffic conditions.</li></ul><p><strong>Implementation and Testing</strong></p><ul><li>Deploy the solution in a controlled environment to monitor its effectiveness.</li><li>Collect feedback from drivers and customers to further refine the recommendations.</li></ul><h3>Data Exploration and Preparation (EDA)</h3><p><strong>Data Description</strong> Two main datasets were used for this project</p><ol><li><strong>Completed Orders</strong> This dataset contains information about completed delivery trips, including trip IDs, origins, destinations, start and end times.</li><li><strong>Delivery Requests </strong>This dataset includes details about delivery requests (both completed and unfulfilled), such as order IDs, driver IDs, actions, and geographic coordinates.</li></ol><p><strong>Data Cleaning</strong></p><ul><li>Missing values in the Trip Start Time and Trip End Time columns were handled by removing rows with missing values.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*asKQcl4eAolYaJ13WiR_kw.png" /></figure><ul><li>Data types for the trip start and end times were converted to datetime format to facilitate time-based calculations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZjZ0j2EZvxdkb_11ueo-w.png" /></figure><h3>Visualizations and Insights from EDA</h3><p>Visualizations were created to uncover patterns, trends, and anomalies in the data. These visualizations helped to gain a better understanding of the factors affecting delivery performance.</p><p><strong>Distribution of Trip Durations</strong></p><ul><li>A histogram was used to visualize the distribution of trip durations, helping to identify the presence of outliers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*HQ__QKox8TuuuGafDzyyaA.png" /></figure><p><strong>Trip Frequency by Day and Hour</strong></p><ul><li>Bar charts were created to show the number of trips initiated on different days of the week and at different hours of the day.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*g9A_JNFUJ7gNbWTo_ij_8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*cPyVHGisHki-MektUR5s2w.png" /></figure><p><strong>Geographic Distribution of Trips:</strong></p><ul><li>Maps were plotted to visualize the origins and destinations of trips, highlighting high-demand areas.</li></ul><p><strong>Insights Gained</strong></p><p><strong>Trip Duration</strong></p><ul><li>The majority of trips had durations within a reasonable range, with some outliers that were removed for analysis.</li><li>Most trips were completed within 30 to 60 minutes.</li></ul><p><strong>Trip Frequency</strong></p><ul><li>Higher trip frequencies were observed during peak hours (mornings and evenings).</li><li>Certain days of the week had higher trip frequencies, indicating patterns in customer demand.</li></ul><h3>Feature Engineering</h3><p>Feature engineering is a crucial step in data analysis and modeling. It involves creating new features from raw data to improve the performance of machine learning models and to gain deeper insights. In this project, we performed several feature engineering steps to enhance our understanding of the delivery data and to prepare it for causal inference analysis.</p><h4>Calculating Trip Duration</h4><p><strong>Objective </strong>To determine the time taken to complete each trip.</p><p><strong>Convert Trip Start and End Times to Datetime</strong></p><ul><li>The raw data contained trip start and end times as strings. We converted these to datetime objects to facilitate time-based calculations.</li></ul><pre>completed_orders_cleaned[&#39;Trip Start Time&#39;] = pd.to_datetime(completed_orders_cleaned[&#39;Trip Start Time&#39;]) <br>completed_orders_cleaned[&#39;Trip End Time&#39;] = pd.to_datetime(completed_orders_cleaned[&#39;Trip End Time&#39;])</pre><p><strong>Calculate Trip Duration</strong></p><ul><li>Trip duration was calculated as the difference between the trip end time and the trip start time, measured in minutes.</li></ul><pre>completed_orders_cleaned[&#39;Trip Duration&#39;] = (completed_orders_cleaned[&#39;Trip End Time&#39;] - completed_orders_cleaned[&#39;Trip Start Time&#39;]).dt.total_seconds() / 60</pre><p><strong>Handle Outliers</strong></p><ul><li>To ensure the calculated durations were reasonable, we removed outliers using the Interquartile Range (IQR) method.</li></ul><pre>Q1 = completed_orders_cleaned[&#39;Trip Duration&#39;].quantile(0.25)<br>Q3 = completed_orders_cleaned[&#39;Trip Duration&#39;].quantile(0.75)<br>IQR = Q3 - Q1<br>lower_bound = Q1 - 1.5 * IQR<br>upper_bound = Q3 + 1.5 * IQR<br>completed_orders_no_outliers = completed_orders_cleaned[<br>    (completed_orders_cleaned[&#39;Trip Duration&#39;] &gt;= lower_bound) &amp;<br>    (completed_orders_cleaned[&#39;Trip Duration&#39;] &lt;= upper_bound)<br>]</pre><h4>Creating Time-Based Features</h4><p><strong>Objective </strong>To capture temporal patterns that might affect delivery performance.</p><p><strong>Day of the Week</strong></p><ul><li>Extracted the day of the week from the trip start time to see if there are variations in delivery performance across different days.</li></ul><pre>completed_orders_no_outliers[&#39;Day of Week&#39;] = completed_orders_no_outliers[&#39;Trip Start Time&#39;].dt.dayofweek</pre><p><strong>Hour of the Day</strong></p><ul><li>Extracted the hour of the day from the trip start time to analyze the impact of different times of the day on delivery performance.</li><li>Code:</li></ul><pre>completed_orders_no_outliers[&#39;Hour of Day&#39;] = completed_orders_no_outliers[&#39;Trip Start Time&#39;].dt.hour</pre><h4>Calculating Trip Distance</h4><p><strong>Objective </strong>To determine the geographical distance between the trip origin and destination.</p><p><strong>Extract Latitude and Longitude</strong></p><ul><li>The trip origin and destination columns contained latitude and longitude coordinates as strings. We split these into separate columns for latitude and longitude.</li></ul><pre>completed_orders_no_outliers[[&#39;Origin Lat&#39;, &#39;Origin Lon&#39;]] = completed_orders_no_outliers[&#39;Trip Origin&#39;].str.split(&#39;,&#39;, expand=True).astype(float)<br>completed_orders_no_outliers[[&#39;Destination Lat&#39;, &#39;Destination Lon&#39;]] = completed_orders_no_outliers[&#39;Trip Destination&#39;].str.split(&#39;,&#39;, expand=True).astype(float)</pre><p><strong>Calculate Distance Using the Haversine Formula</strong></p><ul><li>The Haversine formula calculates the great-circle distance between two points on a sphere given their longitudes and latitudes.</li></ul><pre>import numpy as np<br><br>def haversine_distance(lat1, lon1, lat2, lon2):<br>    # Convert latitude and longitude from degrees to radians<br>    lat1, lon1, lat2, lon2 = map(np.radians, [lat1, lon1, lat2, lon2])<br>    <br>    # Haversine formula<br>    dlat = lat2 - lat1<br>    dlon = lon2 - lon1<br>    a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2<br>    c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1-a))<br>    r = 6371  # Radius of Earth in kilometers<br>    return c * r<br><br>completed_orders_no_outliers[&#39;Trip Distance (km)&#39;] = haversine_distance(<br>    completed_orders_no_outliers[&#39;Origin Lat&#39;], completed_orders_no_outliers[&#39;Origin Lon&#39;],<br>    completed_orders_no_outliers[&#39;Destination Lat&#39;], completed_orders_no_outliers[&#39;Destination Lon&#39;]<br>)</pre><h4>Integrating Weather Data</h4><p><strong>Objective:</strong> To determine if weather conditions, specifically rain, affected delivery performance.</p><p><strong>Fetch Historical Weather Data</strong></p><ul><li>Using the meteostat library, we fetched historical weather data for Lagos, focusing on precipitation information focusing on hourly data.</li></ul><pre>!pip install meteostat<br>from meteostat import Point, Hourly<br><br># Define location for Lagos, Nigeria<br>lagos = Point(6.5244, 3.3792)<br><br># Define time range for the data<br>start_date = completed_orders_no_outliers[&#39;Trip Start Time&#39;].min().date()<br>end_date = completed_orders_no_outliers[&#39;Trip Start Time&#39;].max().date()<br><br># Get daily weather data for Lagos<br>weather_data = Hourly(lagos, start_date, end_date)<br>weather_data = weather_data.fetch()<br><br># Save the weather data to a CSV file for uploading<br>weather_data.to_csv(&#39;weather_data_lagos.csv&#39;)</pre><p><strong>Load and Merge Weather Data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*0D0-_VGVeZV4ObGYd3rYbw.png" /></figure><ul><li>After fetching the weather data, the weather data was merged with the trip data based on the trip date and hour.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DhcwenazlXAtIg32ENqsQ.png" /></figure><p><strong>Adding Holiday Information</strong></p><ul><li>We created a list of public holidays in Lagos, Nigeria, and used it to determine if a trip occurred on a holiday.</li></ul><pre>import holidays<br>nigerian_holidays = holidays.country_holidays(country=&#39;NG&#39;, years=[2021, 2022])<br>merged_data[&#39;Is Holiday&#39;] = merged_data[&#39;Trip Date&#39;].apply(lambda x: int(x in nigerian_holidays))</pre><h4>Constructing the Causal Graph</h4><p>We used the CausalNex library to construct and visualize the causal graph. This graph represents the causal relationships between different variables.</p><pre>from causalnex.structure import StructureModel<br>from causalnex.structure.notears import from_pandas<br>from causalnex.plots import plot_structure<br><br># Select columns for the causal graph<br>columns = [<br>    &#39;Driver Action&#39;, &#39;Trip Duration(minutes)&#39;, &#39;Trip_Distance_km&#39;, <br>    &#39;Day of Week&#39;, &#39;Hour of Day&#39;, &#39;Average Temperature(Celcius)&#39;, <br>    &#39;Wind Speed(km/h)&#39;, &#39;Air Pressure(hPa)&#39;, &#39;Distance_From_Driver_to_Origin_km&#39;, <br>    &#39;Average Speed&#39;, &#39;Is Holiday&#39;, &#39;Is Weekend&#39;<br>]<br><br># Create a subset of the data<br>data_subset = data[columns]<br><br># Construct the causal graph using the NOTEARS algorithm<br>sm = from_pandas(data_subset)<br><br># Visualize the causal graph<br>viz = plot_structure(sm, graph_attributes={&quot;scale&quot;: &quot;1.5&quot;})<br>viz.show(&quot;causal_structure.html&quot;)</pre><h4>Performing Causal Inference</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1_pjFS6xPofFDuj8hqyTw.png" /></figure><p>With the causal graph in place, we perform causal inference using the DoWhy library. This involves defining a causal model, estimating the effect of interventions, and validating our findings.</p><pre>from dowhy import CausalModel<br><br># Define the causal model<br>model = CausalModel(<br>    data=data_subset,<br>    treatment=&#39;Distance_From_Driver_to_Origin_km&#39;,<br>    outcome=&#39;Driver Action&#39;,<br>    graph=&quot;digraph { &#39;Distance_From_Driver_to_Origin_km&#39; -&gt; &#39;Driver Action&#39;; &#39;Trip Duration(minutes)&#39; -&gt; &#39;Driver Action&#39;; &#39;Trip_Distance_km&#39; -&gt; &#39;Driver Action&#39;; &#39;Hour of Day&#39; -&gt; &#39;Driver Action&#39;; }&quot;<br>)<br><br># View the causal graph<br>model.view_model()<br><br># Identify the causal effect<br>identified_estimand = model.identify_effect()<br>print(identified_estimand)<br><br># Estimate the causal effect<br>causal_estimate = model.estimate_effect(identified_estimand, method_name=&quot;backdoor.linear_regression&quot;)<br>print(causal_estimate)<br><br># Refute the causal effect<br>refute_results = model.refute_estimate(identified_estimand, causal_estimate, method_name=&quot;placebo_treatment_refuter&quot;)<br>print(refute_results)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*OyplOPzZ12c1wYWzPCXKoA.png" /></figure><p>The Directed Acyclic Graph (DAG) representing causal relationships between various factors.</p><p><strong>Nodes </strong>Each node represents a variable or factor in the causal network</p><ul><li>Duration (minutes)</li><li>Trip Distance (km)</li><li>Weekend</li><li>Driver Action</li><li>Average Speed</li><li>Distance From Driver to Origin (km)</li><li>Is Rain</li><li>Is Holiday</li><li>Is Heavy Rain</li></ul><p><strong>Edges/Arrows </strong>The arrows indicate causal relationships between the variables, where the direction of the arrow implies that one variable is influencing or causing the other:</p><ul><li>An arrow from <strong><em>“Trip Distance (km)”</em></strong> to <strong><em>“Duration (minutes)”</em></strong> suggests that the distance of a trip affects the duration of the trip.</li><li>Similarly, arrows from “Weekend” and “Is Rain” to “Trip Distance (km)” suggest that whether it is a weekend or if it is raining influences the trip distance which somehow does not make sense.</li></ul><h4><strong>Decoding the graph</strong></h4><ul><li><strong>Driver Action</strong> is influenced by “Duration (minutes)” and “Distance From Driver to Origin (km)”.</li><li><strong>Average Speed</strong> is influenced by “Driver Action”.</li><li><strong>Trip Distance (km)</strong> is influenced by “Weekend” and “Is Rain”.</li><li><strong>Duration (minutes)</strong> is influenced by “Trip Distance (km)”.</li><li><strong>Distance From Driver to Origin (km)</strong> is influenced by “Average Speed”.</li></ul><p>The graph shows how various external factors like weather conditions (Is Rain, Is Heavy Rain), special days (Is Holiday, Weekend), and trip-related attributes (Trip Distance, Distance From Driver to Origin) interact and influence each other but it would be upto us to deduce, infer and conclude the actual effects on ground.</p><h4>Common Sense Explanation</h4><ol><li><strong>Trip Duration </strong>The duration of a trip is naturally influenced by multiple factors such as the distance of the trip, the speed of the vehicle, and possibly traffic conditions. Therefore, longer trips or trips taken at lower speeds will typically have a longer duration.</li><li><strong>Trip Distance </strong>The distance of a trip could be influenced by whether it is a weekend or a weekday. On weekends, people might tend to take longer trips for leisure activities compared to weekdays when trips might be shorter and related to work or routine activities.</li><li><strong>Weather Conditions </strong>Factors like rain (Is Rain) and heavy rain (Is Heavy Rain) influence driving conditions. Rain can slow down traffic, increase trip duration, and affect driving behavior. This might lead to drivers taking more cautious actions and potentially reducing their average speed.</li><li><strong>Special Days </strong>Whether it is a holiday or a weekend (Is Holiday, Is Weekend) can significantly affect traffic patterns and trip characteristics. For example, weekends and holidays might see more recreational trips, leading to higher trip distances and potentially longer durations due to increased traffic.</li><li><strong>Distance From Driver to Origin </strong>This factor indicates how far the driver is from the starting point of the trip. It affects the trip duration and potentially the driver’s actions, as drivers might adjust their behavior based on how far they need to travel to reach their destination.</li></ol><p>In summary, some of the causal relationships depicted in the DAG align with common sense observations: trip duration is affected by trip distance and average speed, which in turn are influenced by weather conditions and day type (weekend/holiday).</p><p>Now let&#39;s add our Domain experience and and common sense and see the graphs</p><pre><br>sm.add_edge(&quot;Is Heavy Rain&quot;, &quot;Driver Action&quot;)<br>sm.add_edge(&quot;Is Holiday&quot;, &quot;Driver Action&quot;)<br>sm.add_edge(&quot;Is Weekend&quot;, &quot;Driver Action&quot;)<br>sm.add_edge(&quot;Is Rain&quot;, &quot;Driver Action&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-lvoMMB0KOFUvyD4heOgg.png" /></figure><p>Since we know the above factors influence the drivers action, we can add them and get the above result.</p><h3>Bayesian Network</h3><p>Bayesian Networks is a probabilistic graphical model that represents dependencies between variables and their joint distribution. Bayesian Network is directed acyclic graph, DAG, where <strong>nodes are random variables</strong> and <strong>edges are causal connections between variables</strong> and represent conditional probability distribution. Once we have a structural model, we create our Bayesian Network and fit conditional probabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wIMEoxlfvu3KpBqyCyFT-Q.png" /></figure><p>Currently, CausalNex supports only discrete probability distributions, so it is needed to discretize our features. We also have to reduce the cardinality of the data by converting them to categorical then to numeric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAwPBx9v34Il3n5U_RXROw.png" /></figure><h4>Classification Report</h4><p>Results with discretization</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*Dh-wsXYPB8Ahxiv71t1_7Q.png" /></figure><h4>Insights from Causal Inference on Driver Actions</h4><p>In our analysis, we utilized a Bayesian Network to model and predict driver actions based on various factors. By performing interventions on these factors, we can observe how changes in each variable influence the likelihood of a particular driver action. Here are the insights derived from our interventions</p><p><strong>Distance From Trip Origin</strong></p><ul><li><strong>Initial Insight </strong>At a distance of 0 units from the trip origin, the likelihood of a certain driver action (denoted as Driver Action 0) is approximately 92.6%.</li><li><strong>Trend</strong> As the distance increases, the probability of action 1 increases, indicating a shift in driver behavior as they move further from the trip origin.</li><li><strong>Significant Change</strong> Around a distance of 2–5 units, there is a notable shift where the probability of action 1 increases significantly, reaching approximately 49.1% at a distance of 5 units.</li><li><strong>Causal Insight</strong> The distance from the trip origin has a significant causal impact on driver actions. As drivers move further from their starting point, their likelihood of switching actions increases markedly.</li></ul><p><strong>Distance to Trip Destination</strong></p><ul><li><strong>Initial Insight</strong> At a distance of 0 units to the destination, action 0 is highly likely with a probability of about 92.9%.</li><li><strong>Trend </strong>The likelihood of action 1 gradually increases as the distance to the destination increases.</li><li><strong>Significant Change </strong>Beyond 5 units to the destination, there is a sharp increase in the probability of action 1, peaking at around 42.2% at a distance of 7 units.</li><li><strong>Causal Insight</strong> Distance from trip origin to the trip destination also causally influences driver actions. The further a trip origin is from the destination, the higher the likelihood of changing their action, particularly beyond 5 units.</li></ul><p><strong>Latitude and Longitude</strong></p><ul><li><strong>Latitude Insight</strong> Certain latitudes show a significant impact on driver actions. For example, latitude 1 and 5 show critical points where driver behavior changes notably.</li><li><strong>Longitude Insight</strong> Similarly, certain longitudes influence driver actions significantly, with specific points showing extreme changes in the likelihood of different actions.</li><li><strong>Causal Insight </strong>Geographic location (latitude and longitude) impacts driver actions, suggesting that the driver’s position plays a crucial role in their behavior.</li></ul><p><strong>Is Weekend</strong></p><ul><li><strong>Weekday Insight </strong>On weekdays, the likelihood of action 0 is approximately 54.1%.</li><li><strong>Weekend Insight</strong>: On weekends, there is a higher probability of action 1, suggesting a significant behavioral change during weekends.</li><li><strong>Causal Insight</strong>: The day of the week causally affects driver actions, with weekends seeing a significant increase in the likelihood of action 1 compared to weekdays. This suggests temporal factors play a critical role in influencing driver behavior.</li></ul><h3>Future Work and Limitations</h3><h4>Limitations</h4><p>While our analysis provided valuable insights into driver behavior and order fulfillment dynamics, there are several limitations to consider:</p><ol><li><strong>Data Quality and Completeness </strong>The accuracy of causal inference heavily depends on the quality and completeness of the data. Any missing or incorrect data can lead to misleading results. Ensuring high-quality data is critical for reliable causal analysis.</li><li><strong>Causal Graph Assumptions</strong> The construction of the causal graph involves assumptions based on domain knowledge. If these assumptions are incorrect or incomplete, the resulting causal relationships might not accurately represent the true underlying processes. This could lead to incorrect conclusions about the effects of different variables.</li><li><strong>Discrete Data Requirements</strong> CausalNex and other causal inference tools often require data to be discretized, which can lead to a loss of information. While discretization makes the analysis tractable, it can also introduce artifacts that might not be present in the original continuous data.</li><li><strong>External Factors </strong>The analysis might not account for all external factors that can influence driver behavior and order fulfillment, such as traffic conditions, road closures, or other unexpected events. These factors can have significant impacts but might be challenging to include in the model.</li><li><strong>Model Generalization</strong> The causal relationships identified in the analysis are specific to the dataset and context of this study. Generalizing these findings to other contexts or datasets requires careful consideration and potentially additional validation.</li><li><strong>Limited Domain Knowledge</strong> The available team on domain knowledge of delivery and other related knowledge was limited hence might affect conclusions.</li><li><strong>Limited Computational Power </strong>We were limited with the amount of available computational power that led to us using only 10% of the data which usually took about 22 minutes on our dedicated Core i5, 8GB Ram server.</li></ol><h4>Future Work</h4><p>To address these limitations and further enhance the analysis, several avenues for future work are recommended:</p><ol><li><strong>Data Enrichment </strong>Integrate additional data sources to enrich the dataset. For example, incorporating real-time traffic data, weather forecasts, and public event schedules can provide a more comprehensive understanding of the factors affecting driver behavior and order fulfillment.</li><li><strong>Advanced Causal Inference Methods </strong>Explore more advanced causal inference methods and tools to refine the causal graph and improve the robustness of the analysis. Techniques such as instrumental variable analysis or propensity score matching can help address some of the limitations of the current approach.</li><li><strong>Continuous Data Analysis </strong>Develop methods to handle continuous data more effectively within the causal inference framework. This can help preserve more information and provide a more accurate representation of the underlying causal relationships.</li><li><strong>Simulation and Scenario Analysis </strong>Use simulation techniques to model different scenarios and their potential impacts on order fulfillment. This can help Gokada understand the potential effects of different strategies and make more informed decisions.</li><li><strong>Real-time Analytics</strong> Implement real-time analytics to continuously monitor and update the causal relationships as new data becomes available. This can help Gokada adapt to changing conditions and optimize driver placement dynamically.</li><li><strong>User Behavior Analysis</strong> Expand the analysis to include customer behavior and preferences. Understanding how customer actions and choices influence order fulfillment can provide additional insights and help tailor strategies to meet customer needs more effectively.</li><li><strong>Collaboration and Feedback </strong>Engage with domain experts and stakeholders to validate the findings and refine the causal models. Their insights and feedback can help ensure that the analysis is grounded in real-world knowledge and is practically applicable.</li></ol><h4>Conclusion</h4><p>Causal inference provides a powerful approach to understanding and optimizing complex systems like last-mile delivery services. By leveraging causal graphs and inference techniques, Gokada can make data-driven decisions to improve driver placement, enhance customer satisfaction, and boost business growth. This analysis highlights the importance of considering causal relationships in data analysis and decision-making, moving beyond mere correlations to uncover true cause-and-effect dynamics.</p><h4>Connect with Me</h4><p>Let’s continue the conversation!</p><p>Connect with me on <a href="https://www.linkedin.com/in/abubeker-shamil/">LinkedIn</a> to stay updated on my latest projects and insights.</p><p>Don’t forget to check out my work on <a href="https://github.com/dev-abuke">GitHub</a> and explore some cool code.</p><p>Hit that clap button if you found this interesting! 👏👏👏</p><h4>References</h4><ul><li><a href="http://ftp.cs.ucla.edu/pub/stat_ser/r350.pdf">Causal Inference in Statistics: An Overview</a></li><li><a href="https://github.com/microsoft/dowhy">DoWhy: An End-to-End Library for Causal Inference</a></li><li><a href="https://causalnex.readthedocs.io/en/latest/">CausalNex Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=897a622cbdfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Precision RAG: Building Enterprise Grade RAG Systems]]></title>
            <link>https://medium.com/@abubekershamil/precision-rag-building-enterprise-grade-rag-systems-947cf4e52e0b?source=rss-dec8d7adb524------2</link>
            <guid isPermaLink="false">https://medium.com/p/947cf4e52e0b</guid>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Abubeker]]></dc:creator>
            <pubDate>Sat, 08 Jun 2024 18:42:17 GMT</pubDate>
            <atom:updated>2024-06-10T08:11:10.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnfEun6nx1FQMPKAhEdIOA.png" /></figure><h4>Introduction</h4><p>The rapid advancement of artificial intelligence (AI) has significantly transformed various industries, enabling businesses to leverage powerful Language Models (LLMs) like GPT-4 for diverse applications. However, the effectiveness of these models hinges on the quality of prompts they receive, making prompt engineering a critical skill. To address this challenge, our project focuses on developing an enterprise-grade Retrieval-Augmented Generation (RAG) system that automates prompt generation, evaluation, and testing. By integrating advanced prompt engineering techniques and cutting-edge tools like Pinecone and LangChain, we aim to revolutionize AI interaction, enhancing the efficiency and accuracy of LLMs in business contexts.</p><h4><strong>Business Context</strong></h4><p>Let me introduce you to a day today workings of any business, our example would be a tech firm called PromptlyTech.</p><p>PromptlyTech, is an innovative e-business, specializes in providing AI-driven solutions to optimize the use of LLMs across various industries. Our services, including Automatic Prompt Generation, Evaluation Data Generation, and Prompt Testing and Ranking, cater to the evolving needs of digitally driven businesses. By streamlining prompt engineering, we help businesses improve decision-making, operational efficiency, and customer experience, making advanced AI capabilities more accessible and effective.</p><h3>Understanding Prompt Engineering and RAG Systems</h3><h4>Understanding Prompt Engineering and RAG Systems</h4><p><strong>Prompt Engineering</strong> is a pivotal skill in AI, focusing on crafting precise and instructive prompts to guide language models in generating desired outputs. Effective prompt engineering involves</p><ul><li><strong>Instructive Prompt</strong>: Clearly stating the task to ensure the model understands the expected outcome.</li><li><strong>Task Specification</strong> Defining the task in detail, including any constraints or specific requirements.</li><li><strong>Context Inclusion </strong>Providing relevant context to help the model generate accurate responses.</li><li><strong>Prompt Variations</strong> Creating different versions of prompts to explore various ways of framing the task.</li><li><strong>Avoiding Ambiguity</strong> Ensuring the prompt is clear and unambiguous to avoid misinterpretation.</li><li><strong>Iterative Refinement</strong> Continuously refining prompts based on the generated outputs to improve accuracy and relevance.</li></ul><p><strong>Retrieval-Augmented Generation (RAG) Systems</strong></p><p>Retrieval-augmented generation is a method for enriching LLM prompts with relevant data. Typically, the user prompts will be converted into an embedding and matching documents are fetched from a vector store. Then, the LLM is called with the matching documents as part of the prompt.</p><p>RAG systems enhance the performance of language models by combining retrieval-based and generation-based approaches. The key components of a RAG system include</p><ul><li><strong>Retriever</strong> Searches and retrieves relevant documents or data from a predefined corpus based on the input query (in our case it would be a vector store)</li><li><strong>Re-ranker</strong> Ranks the retrieved documents to ensure the most relevant ones are prioritized.</li><li><strong>Generator</strong> Uses the top-ranked documents to generate responses or content, leveraging the additional context for accuracy.</li></ul><p><strong>Importance of RAG in Enhancing LLM Performance</strong></p><ul><li><strong>Improved Accuracy </strong>By integrating external knowledge sources, RAG systems provide more accurate and contextually relevant responses.</li><li><strong>Enhanced Relevance</strong> The retriever component ensures that the generated content is closely aligned with the query, improving relevance.</li><li><strong>Efficient Knowledge Utilization</strong> RAG systems can dynamically incorporate up-to-date information, making them valuable for applications requiring current knowledge.</li></ul><p><strong>Applications of RAG Systems</strong></p><ul><li><strong>Customer Support</strong> Providing accurate and context-aware responses to customer inquiries.</li><li><strong>Content Generation</strong> Creating high-quality articles, reports, and summaries by leveraging external data.</li><li><strong>Knowledge Management</strong> Enhancing internal knowledge bases with accurate and relevant information retrieval.</li></ul><p>In our project, we aim to harness the power of RAG systems to revolutionize how businesses interact with LLMs, ensuring high-quality and relevant outcomes through advanced prompt engineering techniques.</p><h3>Project Goals and Objectives</h3><p>Our project focuses on building an enterprise-grade Retrieval-Augmented Generation (RAG) system with advanced prompt engineering techniques. Here are the primary goals and objectives of the project</p><p><strong>1. Automate Prompt Generation</strong> Develop a system that can automatically generate high-quality prompts based on user inputs, reducing the need for manual crafting and expertise.</p><p><strong>2. Implement Evaluation Data Generation</strong> Create mechanisms to generate diverse test cases automatically for evaluating prompts, ensuring comprehensive coverage and performance analysis.</p><p>When designing an evaluation strategy for RAG applications, we should evaluate both steps</p><blockquote>Document retrieval from the vector store</blockquote><blockquote>LLM output generation</blockquote><p>It’s important to evaluate these steps separately, because breaking your RAG into multiple steps makes it easier to pinpoint issues.</p><p>There are several criteria used to evaluate RAG applications</p><h4>Output-based</h4><ul><li><strong>Factuality (also called Correctness)</strong> Measures whether the LLM outputs are based on the provided ground truth.</li><li><strong>Answer relevance</strong> Measures how directly the answer addresses the question.</li></ul><h4>Context-based</h4><ul><li><strong>Context adherence (also called Grounding or Faithfulness)</strong> Measures whether LLM outputs are based on the provided context.</li><li><strong>Context recall</strong> Measures whether the context contains the correct information, compared to a provided ground truth, in order to produce an answer.</li><li><strong>Context relevance</strong> Measures how much of the context is necessary to answer a given query.</li></ul><p><strong>3. Develop a Robust Prompt Testing and Ranking System</strong> Use methodologies like Monte Carlo matchmaking and ELO rating systems to assess and rank the generated prompts based on their effectiveness and relevance.</p><p><strong>4. Integrate Advanced Tools like Pinecone and LangChain</strong> Utilize Pinecone for efficient vectorized data storage and retrieval and LangChain for seamless interaction with the RAG framework, enhancing the overall system performance.</p><p><strong>5. Design a User-Friendly Interface</strong> Create an intuitive interface for users to input objectives, generate prompts, and view evaluation results, making the system accessible and easy to use.</p><p><strong>6. Ensure Comprehensive System Integration and Testing</strong> Integrate all components of the system and conduct thorough testing to ensure functionality, usability, and performance, refining the system based on feedback and results.</p><h3>Methodology</h3><p>The development of our RAG system involves a structured methodology that includes several key steps</p><p><strong>1. Research and Design</strong> Conduct thorough research on prompt engineering and RAG systems to design an effective approach for our project. This includes understanding the latest techniques, tools, and best practices in the field.</p><p><strong>2. Implementation of Prompt Engineering Techniques</strong> Apply advanced prompt engineering techniques to craft effective prompts that guide the LLM to generate desired outputs. This involves iterative refinement, context inclusion, and avoiding ambiguity.</p><p><strong>3. Integration of Pinecone and LangChain</strong> Integrate Pinecone for efficient storage and retrieval of vectorized data, and LangChain for seamless interaction with the RAG framework. This integration enhances the performance and scalability of the system.</p><p><strong>4. Development of Evaluation Metrics</strong> Define and implement evaluation metrics to assess the generated prompts. Metrics include relevance, clarity, context alignment, accuracy, and diversity.</p><p><strong>5. Automatic Evaluation Data Generation</strong> Develop mechanisms to automatically generate evaluation data, creating diverse test cases to ensure comprehensive coverage and thorough analysis of prompt performance.</p><p><strong>6. Implementation of Monte Carlo Matchmaking and ELO Rating System</strong> Use Monte Carlo matchmaking to simulate various matchups between prompts and the ELO rating system to rank them based on their performance.</p><p><strong>7. User Interface Design and Development</strong> Create a user-friendly interface using web frameworks like Flask for backend and React for frontend. The interface allows users to input objectives, generate prompts, and view evaluation results seamlessly.</p><h3>Implementation Steps</h3><p>The implementation of our RAG system involves several key steps, each focusing on different aspects of the project:</p><p><strong>1. Set Up Development Environment and Dataset (PDF) </strong>Ensure all necessary libraries and tools are installed. This includes setting up virtual environments and installing dependencies and getting API keys like Pinecone, Langchain, OpenAI and Pandas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gq-16Idmx2_byOzrWjKzKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n31P5U_k61Q1UF78_O5OfQ.png" /><figcaption>pinecone API key and pdf document processing for easier storage</figcaption></figure><p><strong>Define the Function</strong></p><p>The code snippet defines a function named split_documents that takes an optional argument doc_path. The doc_path argument is a string representing the path to the document file. If no doc_path is provided when calling the function, it defaults to/data/10 Academy Cohort B - Weekly Challenge_ Week - 7.pdf.</p><p><strong>Load the Document</strong></p><p>Inside the try block, the code creates an instance of the PyPDFLoader class, passing the doc_path as an argument. This class is responsible for loading the raw documents from the specified file.</p><p><strong>Load Raw Documents</strong></p><p>The code then calls the load() method on the directory_loader object, which loads the raw documents from the file specified by doc_path. The raw documents are stored in the raw_docs variable.</p><p><strong>Split Text into Chunks</strong></p><p>Next, the code creates an instance of the RecursiveCharacterTextSplitter class, passing chunk_size=1000 and chunk_overlap=200 as arguments. This class is responsible for splitting the text into smaller chunks.</p><p><strong>Split Documents</strong></p><p>The code calls the split_documents() method on the text_splitter object, passing the raw_docs as an argument. This method splits the text in the raw_docs into smaller chunks, storing the split documents in the docs variable</p><p><strong>2. User Input Handling</strong> Define functions to handle user inputs, allowing them to provide objectives and scenarios. This forms the basis for generating and evaluating prompts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*J1Skx5fgzPzfHHyPuXT-jQ.png" /><figcaption>user objective input and upload pdf</figcaption></figure><p><strong>3. Prompt Generation Algorithm</strong> Develop algorithms to generate prompts based on user context and objective. Use pre-trained language models like GPT-3.5 to generate diverse and contextually relevant prompts.</p><pre>def get_test_prompts(num, Context, Objective):<br><br>    return f&quot;&quot;&quot;Understand the given context and generate {num} <br>    best test prompts based on the user&#39;s objective.<br><br>    Context:<br>    {Context}<br><br>    Objective:<br>    {Objective}<br>,<br>    ---<br><br>    Below is Instructions for LLM<br><br>    Based on the provided context and user&#39;s objective, generate <br>    a series of test prompts that could help in achieving the user&#39;s goal. <br>    The prompts should cover different aspects and scenarios to ensure <br>    comprehensive understanding and results. Here are some examples <br>    to guide you:<br><br>    1. **Summarization:**<br>    - Summarize the main points of the context related to the Objective.<br>    - Provide a brief summary focusing on specific aspect within the context.<br><br>    2. **Extraction:**<br>    - Extract key information about specific topic from the context.<br>    - List important facts or data points related to Objective.<br><br>    3. **Explanation:**<br>    - Explain how specific element in the context relates to Objective.<br>    - Describe the significance of particular detail in achieving Objective.<br><br>    4. **Clarification:**<br>    - Clarify the meaning of specific term or phrase mentioned in the context.<br>    - Provide additional details or background information about specific topic.<br><br>    5. **Question Generation:**<br>    - Generate questions that could help explore Objective further .<br>    - Create open-ended questions to facilitate deeper understanding of Objective.<br><br>    6. **Application:**<br>    - Suggest practical applications or implications of Objective.<br>    - Propose potential use cases or scenarios where Objective can be applied.<br><br>    OUTPUT FORMAT:<br>    Must be list of questions only<br>    No extra text<br>    No numbering or other sequential decorations<br>    All questions must be on their own lines<br><br>    EXAMPLE OUTPUT:<br>    Summarize the main points related to Objective.<br>    Extract key information about specific topic.<br>    Explain how specific element relates to Objective.<br>    Clarify the meaning of specific term or phrase mentioned.<br>    Generate questions that could help explore Objective further.<br>    Suggest practical applications or implications of Objective .<br><br>    &quot;&quot;&quot;</pre><p>from the above prompt we can generate a number of prompts based on the context that are fetched from the vector database specificaly pinecone.</p><p><strong>4. Evaluation Metrics Implementation</strong> Implement functions to evaluate the generated prompts based on relevance, clarity, context alignment, accuracy, and diversity. This ensures comprehensive assessment and ranking of prompts.</p><p><strong>5. Integration of Pinecone and LangChain</strong> Integrate Pinecone for vectorized data storage and retrieval and LangChain for interaction with the RAG framework. This enhances the system’s performance and scalability.</p><pre>import os<br>from langchain_openai import ChatOpenAI<br>from langchain.schema import (<br>    SystemMessage,<br>    HumanMessage,<br>    AIMessage<br>)<br><br>class RAG:<br>    def __init__(self):<br><br>        self.chat = ChatOpenAI(<br>            # model=&quot;gpt-4o&quot;,<br>            temperature=0,<br>            max_tokens=None,<br>            timeout=None,<br>            max_retries=2,<br>            # api_key=&quot;...&quot;,  # if you prefer to pass api key in directly instaed of using env vars<br>            # base_url=&quot;...&quot;,<br>            # organization=&quot;...&quot;,<br>            # other params...<br>        )<br><br>        self.messages = [<br>            SystemMessage(content=&quot;You are a helpful assistant. that generates a good prompt for the given context&quot;),<br>            HumanMessage(content=&quot;Hi AI, how are you today?&quot;),<br>            AIMessage(content=&quot;I&#39;m great thank you. How can I help you?&quot;),<br>        ]<br><br>    def generate_answer(self, augmented_query: str):<br><br>        self.messages.append(HumanMessage(content=augmented_query))<br>        response = self.chat(self.messages)<br>        self.messages.append(response)<br>        return response.content</pre><h4><strong>Pinecone Vector Database</strong></h4><p>Pinecone provides a highly efficient and scalable vector database that stores and retrieves vectorized data. By converting textual data into vectors, Pinecone enables fast and accurate retrieval of relevant information based on similarity searches.</p><p><strong>Key Features of Pinecone</strong></p><ul><li><strong>Scalability </strong>Pinecone scales effortlessly, handling large volumes of vector data without compromising performance.</li><li><strong>Real-Time Search </strong>Pinecone supports real-time search capabilities, ensuring quick retrieval of relevant documents for prompt generation.</li><li><strong>High Availability</strong> Pinecone ensures high availability and fault tolerance, making it a reliable choice for enterprise applications.</li></ul><p><strong>Integration with RAG System</strong> In our project, Pinecone was used to store vectorized representations of documents and retrieve the most relevant ones based on the input query. This integration significantly improved the accuracy and relevance of the generated prompts by leveraging the rich contextual information stored in the vectors.</p><p><strong>Implementation Example</strong> Here’s a brief overview of how Pinecone was integrated into the RAG system</p><pre>import time<br>import os<br>from pinecone import Pinecone, ServerlessSpec<br>from langchain_pinecone import PineconeVectorStore<br>from langchain_openai import OpenAIEmbeddings<br><br>class PineconeVector:<br>    def __init__(self, index_name):<br>        self.index_name = index_name<br>        self.embeddings = OpenAIEmbeddings()<br>    def create_pinecone_index(self):<br>        pinecone_api_key = os.environ.get(&quot;PINECONE_API_KEY&quot;)<br><br>        pc = Pinecone(api_key=pinecone_api_key)<br><br>        existing_indexes = [index_info[&quot;name&quot;] for index_info in pc.list_indexes()]<br><br>        if self.index_name not in existing_indexes:<br>            pc.create_index(<br>                name=self.index_name,<br>                dimension=1536,<br>                metric=&quot;cosine&quot;,<br>                spec=ServerlessSpec(cloud=&quot;aws&quot;, region=&quot;us-east-1&quot;),<br>            )<br>            while not pc.describe_index(self.index_name).status[&quot;ready&quot;]:<br>                time.sleep(1)<br><br>        index = pc.Index(self.index_name)<br><br>        return index, pc<br>    <br>    def insert(self, split_documents):<br>        self.pinecone_vectorstore = PineconeVectorStore.from_documents(<br>            split_documents, <br>            self.embeddings, <br>            index_name=self.index_name<br>        )<br><br>        return self.pinecone_vectorstore<br>        <br>    def search_vectorstore(self, query: str):<br>        <br>        # get top 3 results from knowledge base<br>        results = self.pinecone_vectorstore.similarity_search(query, k=3)<br>        # check if there are any results<br>        if not results:<br>            raise ValueError(&quot;No results found in the knowledge base&quot;)<br>        # get the text from the results<br>        source_knowledge = &quot;\n&quot;.join([x.page_content for x in results])<br><br>        return source_knowledge<br><br>  def retrieve_documents(query):<br>      query_embedding = model.encode(query)<br>      result = index.query(queries=[query_embedding], top_k=5)<br>      return [match[&#39;metadata&#39;][&#39;text&#39;] for match in result[&#39;matches&#39;]]</pre><p><strong>LangChain</strong></p><p><strong>Seamless Interaction with RAG Framework</strong> LangChain is a framework designed to facilitate seamless interaction with RAG systems. It provides tools and components that simplify the development of applications using language models.</p><p><strong>Key Features of LangChain</strong></p><ul><li><strong>Flexible Connectors</strong>: LangChain offers flexible connectors to various data sources, making it easy to integrate different components of the RAG system.</li><li><strong>Enhanced Usability</strong>: LangChain simplifies the development process, allowing developers to focus on building effective RAG systems without worrying about low-level implementation details.</li><li><strong>Support for Multiple Data Sources</strong>: LangChain supports multiple data sources, enhancing the flexibility and applicability of RAG systems.</li></ul><p>LangChain facilitated the seamless interaction between the retriever and generator components of the RAG system. By leveraging LangChain’s connectors and tools, we ensured smooth data flow and efficient processing within the system.</p><pre>import os<br>from langchain_openai import ChatOpenAI<br>from langchain.schema import (<br>    SystemMessage,<br>    HumanMessage,<br>    AIMessage<br>)<br><br>class RAG:<br>    def __init__(self):<br><br>        self.chat = ChatOpenAI(<br>            # model=&quot;gpt-4o&quot;,<br>            temperature=0,<br>            max_tokens=None,<br>            timeout=None,<br>            max_retries=2,<br>            # api_key=&quot;...&quot;,  # if you prefer to pass api key in directly instaed of using env vars<br>            # base_url=&quot;...&quot;,<br>            # organization=&quot;...&quot;,<br>            # other params...<br>        )<br><br>        self.messages = [<br>            SystemMessage(content=&quot;You are a helpful assistant. that generates a good prompt for the given context&quot;),<br>            HumanMessage(content=&quot;Hi AI, how are you today?&quot;),<br>            AIMessage(content=&quot;I&#39;m great thank you. How can I help you?&quot;),<br>        ]<br><br>    def generate_answer(self, augmented_query: str):<br><br>        self.messages.append(HumanMessage(content=augmented_query))<br>        response = self.chat(self.messages)<br>        self.messages.append(response)<br>        return response.content</pre><p><strong>6. Development of User Interface</strong> Create a user-friendly interface using Flask for backend and Vue React for frontend. The interface allows users to input objectives, generate prompts, and view evaluation results in real-time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnfEun6nx1FQMPKAhEdIOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6bjruGhkBfKCWpU1A9HZw.png" /></figure><p><strong>How We Used the Prompting Score Method</strong></p><p>To evaluate the effectiveness of the prompts generated by our RAG system, we implemented a scoring method based on log probabilities provided by the language model. This method helps in assessing the accuracy of the generated prompts. Here is a detailed explanation of the prompting score method we used:</p><p><strong>1. Log Probability Scoring</strong> The accuracy of the prompts is evaluated by analyzing the log probabilities returned by the language model. Log probabilities indicate how confident the model is about each token in the generated text. Higher log probabilities suggest higher confidence and better accuracy.</p><p><strong>2. Scoring Implementation</strong> We implemented the following code to score the generated prompts based on their log probabilities</p><p>In this implementation, we</p><ul><li>Extracted log probabilities from the API response.</li><li>Converted log probabilities to probabilities by exponentiating them.</li><li>Multiplied by 100 to convert to percentage accuracy.</li><li>Rounded the accuracy to two decimal places for readability.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rA2hRludn6DD_MBcwCYZHg.png" /></figure><p><strong>2. Scoring Implementation</strong> We implemented the following code to score the generated prompts based on their log probabilities</p><h3>Evaluation and Testing</h3><p>To ensure the effectiveness of our RAG system, we implemented comprehensive evaluation and testing methodologies</p><p><strong>1. Evaluation Metrics</strong> We defined several metrics to assess the performance of generated prompts using ragas</p><ul><li><strong>Relevance</strong> Measures how closely the prompts align with the input query.</li><li><strong>Clarity</strong> Assesses the readability and understandability of the prompts.</li><li><strong>Context Alignment</strong> Evaluates how well the prompts match the context of the query.</li><li><strong>Accuracy</strong> Checks the factual correctness of the generated prompts.</li><li><strong>Diversity</strong> Ensures the generated prompts are varied and not repetitive.</li></ul><h4>Using Promptfoo for Testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GeFKQkWYzgW7zBBOnHbTPw.png" /><figcaption>promptfoo workflow</figcaption></figure><p>Promptfoo is a CLI and library for evaluating LLM output quality.</p><p>With Promptfoo, we can</p><ul><li>Build reliable prompts, models, and RAGs with benchmarks specific to your use-case</li><li>Speed up evaluations with caching, concurrency, and live reloading</li><li>Score outputs automatically by defining <a href="https://promptfoo.dev/docs/configuration/expected-outputs">metrics</a></li><li>Use as a <a href="https://promptfoo.dev/docs/usage/command-line">CLI</a>, <a href="https://promptfoo.dev/docs/usage/node-package">library</a>, or in <a href="https://promptfoo.dev/docs/integrations/github-action">CI/CD</a></li><li>Use OpenAI, Anthropic, Azure, Google, HuggingFace, open-source models like Llama, or integrate custom API providers for <a href="https://promptfoo.dev/docs/providers">any LLM API</a></li></ul><p>We chose Promptfoo for its ease of use and its simple declarative test cases</p><h4>Methodologies Used for Testing</h4><p>As we mentioned earlier, we needed a way to test not only the LLM but also the output of the vector database</p><ol><li>Testing Document retrieval from the vector store</li><li>Testing LLM output generation</li></ol><h4>1. Testing Vector Store</h4><pre>prompts: [&#39;{{ query }}&#39;]<br>providers: [&#39;python:prompt_test\pinecone_retrieve.py&#39;]<br>tests:<br>  - description: Asking For Tutors in a Week7 Challege Document<br>    vars:<br>      query: Who are the tutors for this weeks challenge?<br>    assert:<br>      - type: contains-all<br>        value: [&#39;Yabebal&#39;, &#39;Emtinan&#39;, &#39;Rehmet&#39;]<br><br>  - description: Asking for Company Info in a Week7 Challege Document<br>    vars:<br>      query: What does the company PromptlyTech do?<br>    assert:<br>      - type: llm-rubric<br>        provider: openai:gpt-3.5-turbo-0125<br>        value: Answer Resembles - The company PromptlyTech is an innovative e-business specializing in providing AI-driven solutions for optimizing the use of Language Models (LLMs)<br><br>  - description: Asking for Submission Deadline in a Week7 Challege Document<br>    vars:<br>      query: When is the interim submission deadline?<br>    assert:<br>      - type: contains-all<br>        value: [&#39;Wednesday&#39;, &#39;8pm&#39;, &#39;UTC&#39;]</pre><p>Document retrieval is the first step of a RAG. It is possible to eval the retrieval step in isolation, in order to ensure that you are fetching the best documents</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZY2LM-rIH3-nKHwUolmNw.png" /></figure><p>We have a simple file pinecone_etrieve.py, which takes a query and outputs the content of the first of its 3 retrievals from the vector database</p><p>So after running the evaluation the test case shall look for each test cases and test against it.</p><p>For Example, In the above test declaration, the contains-all assertion ensures that the output from pinecone_retrieve.py contains all the listed substrings. llm-rubric makes sure that the context is the same</p><h3>Evaluating LLM output</h3><p>Once we are confident our vector retrieval step is performing well, it’s time to evaluate the LLM itself.</p><p>In this step, we are focused on evaluating whether the LLM output is correct given a query from the document.</p><p>First, we set up our prompt by creating a context_prompt.txt file</p><pre>You are a corporate intranet chat assistant.  The user has asked the following:<br><br>&lt;QUERY&gt;<br>{{ query }}<br>&lt;/QUERY&gt;<br><br>You have retrieved some documents to assist in your response:<br><br>&lt;DOCUMENTS&gt;<br>{{ context }}<br>&lt;/DOCUMENTS&gt;<br><br>You are always to the point and crisp and do not add any unnecessary informations<br>Think carefully and respond to the user concisely and accurately.<br>For each statement you output only what the QUERY asked only</pre><p>We actually created three (3) context adding prompts to evaluate the output to make sure we have the best prompt out of the three (3) but the above is the best one we chose</p><pre>prompts: [&#39;prompt_test\context_prompt.txt&#39;, &#39;prompt_test\context_prompt2.txt&#39;, &#39;prompt_test\context_prompt3.txt&#39;,]<br>providers: [&#39;openai:gpt-3.5-turbo-0125&#39;]<br>tests:<br>  - description: Asking For Tutors - LLM Rubric<br>    vars:<br>      query: Who are the tutors for this weeks challenge?<br>      context: file://prompt_test\load_context.py<br>    assert:<br>      - type: factuality<br>        provider: openai:gpt-3.5-turbo<br>        threshold: 0.6<br>        value: The tutors are Yabebal, Emtinan and Rehmet<br>      - type: answer-relevance<br>        provider: openai:gpt-3.5-turbo<br>        threshold: 0.8<br>      - type: contains-all<br>        value: [&#39;Yabebal&#39;, &#39;Emtinan&#39;, &#39;Rehmet&#39;]<br><br>  - description: Asking for Company Info in a Week7 Challege Document<br>    vars:<br>      query: What does the company PromptlyTech do?<br>      context: file://prompt_test\load_context.py<br>    assert:<br>      - type: llm-rubric<br>        provider: openai:gpt-3.5-turbo<br>        value: Answer should atleast be in context with - The company PromptlyTech is an innovative e-business specializing in providing AI-driven solutions for optimizing the use of Language Models (LLMs)<br><br>  - description: Asking for Submission Deadline in a Week7 Challege Document<br>    vars:<br>      query: When is the interim submission deadline?<br>      context: file://prompt_test\load_context.py<br>    assert:<br>      - type: factuality<br>        provider: openai:gpt-3.5-turbo<br>        value: It is on Wednesday 8pm UTC<br>      - type: answer-relevance<br>        provider: openai:gpt-3.5-turbo<br>        threshold: 0.8<br>      - type: similar<br>        value: The deadline for the interim submission is Wednesday 8pm UTC<br>        threshold: 0.7<br>      - type: contains-all<br>        value: [&#39;Wednesday&#39;, &#39;8pm&#39;, &#39;UTC&#39;]</pre><p>The above file tests the output of the LLM for factuality <strong>similarity</strong>, <strong>answer-relevancy, factuality </strong>and whether it <strong>contains </strong>the expected output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4Zt8q63zk8dr2aRAOQu5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3wLoAf9HE72nQN9Kc1bXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1UMidFOceCgLF70AfqJPVw.png" /></figure><p>As it can be seen from the above our prompts perform well on outputs and promptfoo makes it easier to track changes and with visualization</p><h3>User Interface Development</h3><p>A user-friendly interface is crucial for the effective interaction with the prompt engineering system. Here are the key aspects of our UI development</p><p><strong>1. Design Principles</strong></p><ul><li><strong>Simplicity </strong>Ensure the interface is clean and straightforward.</li><li><strong>Usability </strong>Make the interface easy to navigate and use.</li><li><strong>Responsiveness</strong> Ensure the interface works well on various devices and screen sizes.</li></ul><p><strong>2. Features</strong></p><ul><li><strong>Input Fields</strong> Allow users to input their objectives and scenarios.</li><li><strong>Generate Button</strong> Initiate the prompt generation process.</li><li><strong>Score Results</strong> Display the score results in a clear and understandable format.</li></ul><p><strong>3. Technologies Used</strong></p><ul><li><strong>Backend</strong> Implemented using Flask to handle user inputs and interact with the prompt engineering system.</li><li><strong>Frontend</strong> Developed using Vue+React and Tailwind CSS to create an interactive and responsive user interface.</li></ul><p><strong>4. Integration</strong></p><ul><li>The UI is seamlessly integrated with the backend prompt engineering system, providing real-time displaying of evaluation results.</li></ul><p>By focusing on these aspects, we created a user-friendly interface that enhances the user experience and facilitates efficient interaction with the prompt engineering system.</p><h3>Challenges and Solutions</h3><p>During the development of our RAG system, we encountered several challenges. Here are some of the key challenges and the solutions we implemented</p><p><strong>2. Evaluation Metrics Refinement</strong></p><ul><li>Challenge: Defining and refining evaluation metrics to accurately assess the performance of the RAG system.</li><li>Solution: Continuously refined the evaluation metrics based on performance analysis, ensuring they align with expectations and application requirements.</li></ul><p><strong>3. Limited Model Variability</strong></p><ul><li>Challenge: Relying on a single language model for all tasks.</li><li>Solution: Introduced an ensemble approach by incorporating multiple language models, leveraging their diverse capabilities to enhance overall performance.</li></ul><p><strong>4. User Customization and Knowledge source</strong></p><ul><li>Challenge: Providing flexibility for users to customize the evaluation process and limited knowledge source.</li><li>Solution: Developed a user-friendly interface that allows users to define and select their evaluation criteria, enabling customized evaluations based on specific needs.</li></ul><p>By addressing these challenges, we ensured the development of a robust and efficient RAG system.</p><h3>Future Work and Limitations</h3><p><strong>Limitations</strong></p><p><strong>1. Data Quality and Bias</strong> The effectiveness of the RAG system heavily relies on the quality and neutrality of the underlying data. Biases present in training data may result in biased responses, necessitating continuous monitoring and mitigation.</p><p><strong>2. Evaluation Metrics Refinement</strong> Continuous refinement of evaluation metrics is essential to accurately assess the performance of the RAG system. This involves adapting metrics to specific use cases and ensuring they align with user expectations and application requirements.</p><p><strong>3. Limited Model Variability</strong> Relying on a single language model introduces a limitation in terms of model variability. Different language models may have varying strengths and weaknesses, and a singular model may not provide optimal performance across all use cases.</p><p><strong>4. Limited User Customization</strong> Users may have specific preferences or requirements for evaluating the system, and a one-size-fits-all approach limits their ability to customize the evaluation process.</p><p><strong>Future Work</strong></p><p><strong>1. Enhanced Prompt Engineering Techniques</strong> Further research and development can focus on refining prompt engineering techniques, including more advanced methods for crafting instructive prompts, context inclusion, and iterative refinement.</p><p><strong>2. Dynamic RAG Systems</strong> Investigate methods to make RAG systems more dynamic by adapting to evolving datasets and knowledge sources, ensuring the system remains relevant over time.</p><p><strong>3. Emotional Prompting</strong> Research and implement techniques for emotional prompting, allowing the system to understand and respond to user emotions, enhancing applications where emotional understanding is crucial.</p><p><strong>4. User-Defined Evaluation Criteria</strong> Develop an interface that allows users to define and select their evaluation criteria, providing a range of testing methods and metrics</p><p><strong>5. Implement </strong>a robust testing mechanism such as <a href="https://github.com/promptfoo/promptfoo">promptfoo</a></p><h3>Conclusion</h3><p>Our project successfully navigated through various stages, from prompt engineering to RAG system evaluation, automated prompt generation, and user-friendly interface implementation.</p><p>The integration of Pinecone and LangChain played a crucial role in converting and storing vectorized data efficiently, enabling seamless interaction with the RAG framework. The automated prompt generation workflow showcased the ability to dynamically generate diverse and contextually relevant prompts, further enhancing the system’s efficiency.</p><p>As a result of this project, businesses can benefit from a robust and adaptable AI-driven solution that streamlines prompt engineering, leverages external knowledge retrieval, and integrates seamlessly with enterprise LLMOps. The future of AI interaction is indeed promising, with advancements in prompt engineering, RAG systems, and LLMOps converging to redefine how businesses harness the power of Language Models for unparalleled accessibility and effectiveness.</p><h3><strong>Connect with Me</strong></h3><p>Let’s continue the conversation!</p><p>Connect with me on <a href="https://www.linkedin.com/in/abubeker-shamil/">LinkedIn</a> to stay updated on my latest projects and insights.</p><p>Don’t forget to check out my work on <a href="https://github.com/dev-abuke">GitHub</a> and explore some cool code.</p><p>Hit that clap button if you found this interesting! 👏👏👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=947cf4e52e0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Finetuning: Enabling Quality Embedding and Text Generation for Amharic Language]]></title>
            <link>https://medium.com/@abubekershamil/llm-finetuning-enabling-quality-embedding-and-text-generation-for-amharic-language-22e4c4c3564d?source=rss-dec8d7adb524------2</link>
            <guid isPermaLink="false">https://medium.com/p/22e4c4c3564d</guid>
            <dc:creator><![CDATA[Abubeker]]></dc:creator>
            <pubDate>Sat, 01 Jun 2024 20:49:01 GMT</pubDate>
            <atom:updated>2024-06-01T21:18:36.033Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3fSe3ZEYbV7vC_4ipHLEw.png" /></figure><p>In this blog, we’ll walk through the process of preparing and tokenizing large text datasets for natural language processing (NLP) tasks using the Transformers and Datasets libraries. Handling large datasets efficiently is crucial for training robust models. We’ll cover loading data, preprocessing text, tokenizing, and creating datasets ready for training. By the end of this tutorial, you’ll be equipped with the knowledge to manage large text datasets and prepare them for training NLP models.</p><h3>Understanding the Project</h3><p>Imagine you are about to embark on a journey. Before you start, it’s essential to know where you are going and what you hope to achieve. Similarly, in our project, the first step is to understand what we are trying to accomplish.</p><p>In this case, our goal is to improve a system that helps people by using a language model, which is a kind of smart computer program that can understand and generate human language. We want to fine-tune this model to make it better at understanding and generating text in specific languages like Amharic, which are under-represented (which is a fancy way of saying there isn’t much data on the internet for the language and the base model isn’t trained on much data). Fine-tuning means we will adjust the model to work better for our particular needs, much like customizing a tool for a specific task.</p><h3>Gathering and Preparing the Data</h3><p>Imagine you are building a house. Before you start, you need to gather all the materials like bricks, cement, and wood. Similarly, in our project, we need to gather and prepare the data that our model will learn from. This data will be in the form of text written in the languages we are focusing on i.e. Amharic.</p><h3>Why is Quality DATA Important?</h3><ul><li><strong>Quality of Learning </strong>The quality and quantity of the data will directly affect how well our model learns and performs.</li><li><strong>Relevance </strong>We need data that is relevant to our goals, meaning it should be in the languages we are targeting and cover the kinds of conversations or texts our model will encounter.</li></ul><h3>What We Need to Do</h3><ol><li><strong>Collect Data </strong>Gather a large amount of text data in Amharic, Swahili, and Yoruba. This could be from books, articles, social media, or any other sources where these languages are used.</li><li><strong>Preprocess the Data</strong> Clean and prepare the data so that it is in a suitable format for training our model. This involves:</li></ol><ul><li><strong>Removing Unnecessary Parts </strong>Get rid of any irrelevant information, such as advertisements, links, emojis, or unrelated text.</li><li><strong>Formatting</strong> Ensure the text is consistently formatted, for example, removing extra spaces and correcting any errors.</li><li><strong>Splitting into Chunks</strong> Break the text into manageable pieces, as the model can only process a certain amount of text at a time.</li></ul><h4>Practical Steps</h4><p>Now for the fun part,</p><ol><li><strong>Load the Data</strong> Use Python to read in the text data.</li><li><strong>Clean the Data </strong>Apply preprocessing techniques to clean the data. This could include removing special characters, correcting misspellings, and standardizing the text.</li><li><strong>Organize the Data</strong> Split the data into chunks or segments that the model can handle during training.</li></ol><h4>Prerequisites</h4><p>Before we begin, ensure you have the following tools installed and a basic understanding of</p><ul><li>Python programming</li><li>Pandas library for data manipulation</li><li>Transformers library for tokenization</li><li>Datasets library for dataset management</li><li>PyTorch for tensor operations</li></ul><p>Also make sure to refer to the previous guide on data preparation <a href="https://medium.com/@abubekershamil/enhancing-nlp-capabilities-for-ethiopian-languages-amharic-a-scalable-data-warehouse-project-c2735e9a844f">here</a></p><p>Install the necessary libraries using pip</p><pre>pip install pandas transformers datasets torch scikit-learn</pre><h3>Loading and Preprocessing Data</h3><p>We’ll start by loading a CSV file containing our dataset and performing basic preprocessing. For this tutorial, we’ll assume the dataset has two columns — <strong>text</strong> and <strong>summary</strong>.</p><pre>import pandas as pd<br><br># Load the dataset<br>data = pd.read_csv(&#39;your_dataset.csv&#39;)<br><br># Display the first few rows of the dataset<br>print(data.head())<br>print(data.info())</pre><p>Next, we’ll define a preprocessing function to clean the text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RwdlDlXMpBlkvkWsKsk9lw.png" /><figcaption>cleaning functions</figcaption></figure><pre>def preprocess_text(text):<br>    text = text.replace(&quot;\n&quot;, &quot; &quot;).strip()<br>    return text<br><br># Apply preprocessing to text and summary columns<br>data[&#39;text&#39;] = data[&#39;text&#39;].apply(preprocess_text)<br>data[&#39;summary&#39;] = data[&#39;summary&#39;].apply(preprocess_text)</pre><h3><strong>Tokenizing Text Data</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h6bizUKOOKK7sv7-9df3RA.png" /><figcaption>tokenized data</figcaption></figure><p>Tokenizing is like translating sentences into a language that the computer model can understand. Instead of working with full sentences or paragraphs, the model works with smaller units called <strong><em>tokens</em></strong>. These tokens are often words or sub-words, and they represent the text in a format that a machine learning model can process.</p><h4>Why Tokenize?</h4><ul><li><strong>Standardization </strong>Tokenizing ensures that all text data is converted into a consistent format.</li><li><strong>Model Compatibility</strong> Machine learning models require input in the form of numerical data, and tokenizing helps achieve this by converting text into numerical tokens.</li><li><strong>Efficiency</strong> Working with tokens is more efficient than working with raw text, especially for large datasets.</li></ul><p>Next, we’ll initialize a tokenizer from the Transformers library and use it to tokenize our text data. Tokenization converts text into numerical tokens that can be processed by NLP models.</p><pre>from transformers import AutoTokenizer<br><br># Initialize the tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(&quot;Samuael/llama-2-7b-tebot-amharic&quot;)</pre><p>We need to convert our text and summary columns to lists of strings to prepare them for tokenization.</p><pre># Convert columns to lists of strings<br>texts = data[&#39;text&#39;].tolist()<br>summaries = data[&#39;summary&#39;].tolist()</pre><h4>Splitting the Data into Training and Validation Sets</h4><pre>from sklearn.model_selection import train_test_split<br><br># Split the dataset into training and validation sets<br>train_texts, val_texts, train_summaries, val_summaries = train_test_split(<br>    texts, summaries, test_size=0.1, random_state=42<br>)<br><br># Define chunk size<br>chunk_size = 1000  # Adjust based on available memory</pre><p>As you can see from the above code, we divided the data into <strong>training </strong>and <strong>evaluation</strong>. Think of this step like preparing for an exam. You use some of your study material to learn (<strong>train</strong>) and some to test yourself (<strong>validate</strong>) to see how well you’ve learned.</p><p>In our project, we split our data into two parts for a similar reason- <strong>training </strong>and <strong>validation</strong>.</p><h4>Here’s how we would do it in practice</h4><ol><li><strong>Determine the Split Ratio</strong> Decide what percentage of the data will be used for training and what percentage will be used for validation. A common split is 90% for training and 10% for validation.</li><li><strong>Implement the Split </strong>Use a tool such as <strong><em>train_test_split</em></strong> from <strong><em>sklearn</em></strong> to divide the data into the two sets just like in our case.</li></ol><h4>Handling Large Datasets</h4><p>For large datasets, processing everything in one go can be memory intensive. We’ll split the dataset into smaller chunks to manage memory usage more effectively.</p><pre># Split data into chunks<br>train_chunks = [train_texts[i:i + chunk_size] for i in range(0, len(train_texts), chunk_size)]<br>train_summary_chunks = [train_summaries[i:i + chunk_size] for i in range(0, len(train_summaries), chunk_size)]<br>val_chunks = [val_texts[i:i + chunk_size] for i in range(0, len(val_texts), chunk_size)]<br>val_summary_chunks = [val_summaries[i:i + chunk_size] for i in range(0, len(val_summaries), chunk_size)]</pre><h4>Creating Datasets for Training</h4><p>We’ll create a function to tokenize text and summaries and convert them into a format suitable for training with PyTorch.</p><pre>python<br>Copy code<br>import torch<br>from datasets import Dataset<br><br># Function to tokenize and create dataset<br>def tokenize_and_create_dataset(texts, summaries):<br>    encodings = tokenizer(texts, padding=True, truncation=True)<br>    labels = tokenizer(summaries, padding=True, truncation=True)<br>    <br>    encodings = {<br>        &#39;input_ids&#39;: torch.tensor(encodings[&#39;input_ids&#39;]),<br>        &#39;attention_mask&#39;: torch.tensor(encodings[&#39;attention_mask&#39;]),<br>        &#39;labels&#39;: torch.tensor(labels[&#39;input_ids&#39;])<br>    }<br>    return Dataset.from_dict(encodings)</pre><p>We’ll then process each chunk incrementally to create training and validation datasets.</p><pre>from datasets import DatasetDict, concatenate_datasets<br><br># Initialize lists to store datasets<br>train_datasets = []<br>val_datasets = []<br><br># Process training chunks<br>for i in range(len(train_chunks)):<br>    print(f&quot;Processing train chunk {i}&quot;)<br>    train_dataset_chunk = tokenize_and_create_dataset(train_chunks[i], train_summary_chunks[i])<br>    train_datasets.append(train_dataset_chunk)<br><br># Process validation chunks<br>for i in range(len(val_chunks)):<br>    print(f&quot;Processing val chunk {i}&quot;)<br>    val_dataset_chunk = tokenize_and_create_dataset(val_chunks[i], val_summary_chunks[i])<br>    val_datasets.append(val_dataset_chunk)<br><br># Concatenate the datasets<br>train_dataset = concatenate_datasets(train_datasets)<br>val_dataset = concatenate_datasets(val_datasets)<br><br># Combine into a DatasetDict<br>dataset = DatasetDict({<br>    &#39;train&#39;: train_dataset,<br>    &#39;validation&#39;: val_dataset<br>})</pre><p>After creating the training and validation datasets, the next step is to save them to disk.</p><p>Storing the dataset in a file so that we can easily load and use it later without having to reprocess everything. Think of it like saving a document on your computer — you can open it and continue working on it anytime you want.</p><p>This allows us to reuse the datasets without reprocessing the raw data saving time and compute power.</p><pre># Save the dataset to disk<br>dataset.save_to_disk(&#39;tokenized_dataset&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERKCVvYCnDGDdqbRDIMAEw.png" /><figcaption>saving the tokenized dataset</figcaption></figure><p>To load the dataset later, we can use the load_from_disk method from the datasets library.</p><pre># Load the dataset from disk<br>from datasets import load_from_disk<br><br>dataset = load_from_disk(&#39;tokenized_dataset&#39;)</pre><h4>Sample Inspection</h4><p>It’s a good practice to inspect a sample from the dataset to ensure everything is correctly processed and tokenized.</p><pre># Print a sample from the dataset<br>print(dataset[&#39;train&#39;][0])<br>print(dataset[&#39;validation&#39;][0])</pre><h3>Building and Training the Model</h3><p>Now that our data is tokenized and stored, we can proceed with the next steps in our NLP pipeline, such as training a model.</p><p>Think of this as teaching a computer to understand and generate summaries based on the text it has learned from. It’s similar to how you might train for a marathon by running a little bit each day until you can run long distances comfortably.</p><p>Training phases are as follows</p><ul><li><strong>Learning</strong> The model learns to understand the relationship between the texts and their summaries.</li><li><strong>Prediction</strong> After training, the model can predict summaries for new, unseen texts.</li></ul><p>Here are the general steps we might follow next</p><p><strong>Define the Model</strong></p><ul><li>Choose a pre-trained model from the Transformers library suitable for our task.</li></ul><p><strong>Fine-Tuning the Model</strong></p><ul><li>Fine-tune the model on our tokenized training data.</li></ul><p><strong>Evaluation</strong></p><ul><li>Evaluate the model on the validation dataset to ensure it generalizes well.</li></ul><p><strong>Prediction</strong></p><ul><li>Use the fine-tuned model to generate predictions or summaries on new, unseen data.</li></ul><h3>Defining and Fine-Tuning the Model</h3><p>Now that our data is prepared, we can move on to defining and fine-tuning a pre-trained model for our summarization task. We will use Hugging Face’s transformers library to achieve this.</p><h4>Load Pre-trained Model</h4><p>First, we load a pre-trained model suitable for summarization. For this example, we’ll use<em> </em><strong><em>Samuael/llama-2–7b-tebot-amharic</em> </strong>from the huggingface library.</p><p><strong>Initialize the Model</strong></p><ul><li>We will use a pre-trained model from Hugging Face and fine-tune it on our dataset.</li></ul><pre>from transformers import AutoModelForCausalLM, AutoTokenizer<br><br># Replace with the chosen model name<br>model_name = &quot;Samuael/llama-2-7b-tebot-amharic&quot; <br>model = AutoModelForCausalLM.from_pretrained(model_name)<br>tokenizer = AutoTokenizer.from_pretrained(model_name)</pre><h4>Prepare the Training and Validation Datasets</h4><p>We need to create a DataLoader to feed our datasets into the model during training. This involves defining a custom collate_fn to handle padding.</p><pre>from torch.utils.data import DataLoader<br><br># Define collate function for padding<br>def collate_fn(batch):<br>    input_ids = torch.stack([example[&#39;input_ids&#39;] for example in batch])<br>    attention_mask = torch.stack([example[&#39;attention_mask&#39;] for example in batch])<br>    labels = torch.stack([example[&#39;labels&#39;] for example in batch])<br>    return {&#39;input_ids&#39;: input_ids, &#39;attention_mask&#39;: attention_mask, &#39;labels&#39;: labels}<br><br># Create DataLoader for training and validation datasets<br>train_dataloader = DataLoader(dataset[&#39;train&#39;], batch_size=8, shuffle=True, collate_fn=collate_fn)<br>val_dataloader = DataLoader(dataset[&#39;validation&#39;], batch_size=8, shuffle=False, collate_fn=collate_fn)</pre><h4><strong>Define Training Parameters</strong></h4><ul><li>This includes how many times the model should look at our data (epochs), how many samples it should process at once (batch size), and other settings to control the learning process.</li></ul><pre>from transformers import Trainer, TrainingArguments<br># Define training parameters<br>training_args = TrainingArguments(<br>    output_dir=&#39;./results&#39;,<br>    num_train_epochs=3,<br>    per_device_train_batch_size=8,<br>    per_device_eval_batch_size=8,<br>    warmup_steps=500,<br>    weight_decay=0.01,<br>    logging_dir=&#39;./logs&#39;,<br>)</pre><h4>Fine-Tuning the Model</h4><p>We use the Trainer API from the transformers library for fine-tuning. This requires defining the training arguments and initializing the Trainer.</p><pre><br># Initialize Trainer<br>trainer = Trainer(<br>    model=model,                         # The instantiated 🤗 Transformers model to be trained<br>    args=training_args,                  # Training arguments, defined above<br>    train_dataset=dataset[&#39;train&#39;],      # Training dataset<br>    eval_dataset=dataset[&#39;validation&#39;],  # Evaluation dataset<br>    tokenizer=tokenizer,                 # Tokenizer used for preprocessing<br>)</pre><p>Now we can start the training, make sure GPU is Up</p><pre># Start training<br>trainer.train()</pre><h4>Evaluate the Model</h4><p>After training, we evaluate the model on the validation dataset to check its performance on validation data to ensure it has learned effectively.</p><pre># Evaluate the model<br>eval_results = trainer.evaluate()<br><br># Print evaluation results<br>print(eval_results)</pre><h4>Save the Fine-Tuned Model</h4><p>Finally, we save the fine-tuned model and tokenizer to disk for future use.</p><pre># Save the model and tokenizer<br>model.save_pretrained(&#39;fine_tuned_model&#39;)<br>tokenizer.save_pretrained(&#39;fine_tuned_model&#39;)</pre><h3>Pushing the Model to Hugging Face</h3><p>After training our model, we need to save it so we can use it later without retraining. Additionally, we can share our model with the world by pushing it to Hugging Face’s model hub. This is like publishing a book after writing it, so others can read it.</p><p>some of the importance of pushing to huggingface are</p><ul><li><strong>Reusability </strong>Save the trained model to reuse it without retraining.</li><li><strong>Sharing </strong>Publish the model on Hugging Face to share with the community and for easy deployment.</li></ul><p><strong>Save the Model Locally</strong></p><ul><li>This ensures we can reload and use our trained model in the future without retraining</li></ul><pre># Save the model to disk<br>model.save_pretrained(&#39;./trained_model&#39;)<br>tokenizer.save_pretrained(&#39;./trained_model&#39;)</pre><p><strong>Push the Model to Hugging Face</strong></p><ul><li>First, you need to create an account on Hugging Face and install the huggingface_hub library.</li><li>Login to your Hugging Face account from the terminal using huggingface-cli loginor if you are on notebook, use notebook_login function</li></ul><pre>from huggingface_hub import notebook_login<br><br># Log in to Hugging Face<br>notebook_login()</pre><p>Save and push the model after training and evaluation.</p><pre># Push the model to Hugging Face<br>model.push_to_hub(&quot;your-username/your-model-name&quot;)<br>tokenizer.push_to_hub(&quot;your-username/your-model-name&quot;)</pre><h3>Summary</h3><p>In this project, we went through several crucial steps to fine-tune a large language model for text summarization. Here’s a brief recap of what we did</p><h4><strong>Project Setup</strong></h4><ul><li>Set up our working environment, installed necessary libraries, and loaded the dataset.</li></ul><h4><strong>Data Preparation</strong></h4><ul><li>Preprocessed the text data by cleaning it and splitting it into training and validation sets.</li></ul><h4><strong>Tokenization</strong></h4><ul><li>Used a tokenizer to convert our text data into a format suitable for the model.</li></ul><h4><strong>Model Initialization</strong></h4><ul><li>Chose a pre-trained model suitable for text summarization tasks.</li></ul><h4><strong>Training Setup</strong></h4><ul><li>Defined training arguments and created a trainer to manage the training process.</li></ul><h4><strong>Model Training</strong></h4><ul><li>Trained our model using the training dataset.</li></ul><h4><strong>Evaluation</strong></h4><ul><li>Evaluated the model’s performance on the validation set.</li></ul><h4><strong>Saving and Sharing</strong></h4><ul><li>Saved the trained model locally and pushed it to Hugging Face’s model hub for sharing and future use.</li></ul><h3>Key Takeaways</h3><ul><li><strong>Preprocessing </strong>Proper data cleaning and preparation are critical for model performance.</li><li><strong>Tokenization</strong> Efficient tokenization is essential for handling large text data.</li><li><strong>Training</strong> Careful selection of training parameters can significantly impact model outcomes.</li><li><strong>Evaluation</strong> Regular evaluation helps in understanding model performance and making necessary adjustments.</li><li><strong>Sharing </strong>Publishing models on platforms like Hugging Face enables collaboration and reuse.</li></ul><h3>Future Directions</h3><ul><li><strong>Hyperparameter Tuning</strong> Experiment with different hyperparameters to further improve model performance.</li><li><strong>Data Augmentation</strong> Use data augmentation techniques to increase the diversity and size of the dataset.</li><li><strong>Model Architecture</strong> Explore other model architectures that might be more effective for text summarization.</li><li><strong>Incremental Data Ingestion</strong> Make use of different real time data for further finetuning since the data used are low and the project focuses on low resource language the bigger the data the better</li></ul><h3>Key Limitations</h3><h4><strong>Data Availability</strong></h4><ul><li><strong>Limited Resources </strong>The availability of high-quality Amharic language datasets is limited. This scarcity restricts the diversity and quantity of training data, which is crucial for building robust models.</li><li><strong>Quality of Data </strong>The data used may contain noise, inconsistencies, and biases that can negatively impact model performance.</li></ul><h4><strong>Model Performance</strong></h4><ul><li><strong>Generalization </strong>With limited training data, the model might struggle to generalize well to new, unseen texts. This can result in lower accuracy and effectiveness in real-world applications.</li><li><strong>Overfitting </strong>The model may overfit the small dataset, learning specific patterns rather than general language rules, leading to poor performance on new data.</li></ul><h4><strong>Technical Constraints</strong></h4><ul><li><strong>Computational Resources</strong> Fine-tuning large language models requires significant computational power and memory, which might not be accessible to everyone.</li><li><strong>Infrastructure </strong>Setting up the necessary infrastructure for training and deploying models can be complex and resource intensive.</li></ul><h4><strong>Language-Specific Challenges</strong></h4><ul><li><strong>Complex Morphology </strong>Amharic, with its complex morphology and unique script, poses additional challenges for tokenization and model training.</li><li><strong>Lack of Pre-trained Models</strong> There are fewer pre-trained models available for Amharic compared to more widely spoken languages, which limits starting points for fine-tuning.</li></ul><h3>Conclusion - Feasibility of Working on Limited Data for Amharic Language</h3><p>Given the current limitations, is it feasible to work with limited data for the Amharic language? The answer is nuanced</p><h4><strong>Feasibility</strong></h4><ul><li><strong>Possible but Challenging </strong>It is feasible to work on Amharic language projects with limited data, but it comes with significant challenges. The lack of ample, high-quality data and pre-trained models means that the outcomes might not be as accurate or reliable as those for more widely studied languages.</li></ul><h4><strong>Considerations</strong></h4><ul><li><strong>Enhanced Efforts</strong> To mitigate these limitations, one can focus on data augmentation, transfer learning from related languages, and community efforts to collect and share more Quality Amharic data.</li><li><strong>Realistic Expectations</strong> It’s important to set realistic expectations regarding the model’s performance and to continuously iterate and improve as more data becomes available.</li></ul><h4><strong>Future Prospects</strong></h4><ul><li><strong>Community and Collaboration </strong>Encouraging collaboration among researchers and developers can help in pooling resources and improving the quality and quantity of available datasets.</li><li><strong>Technological Advancements </strong>Advances in machine learning and natural language processing will likely continue to improve, making it easier to work with limited data in the future.</li></ul><h3>Final Thoughts</h3><p>While the path is challenging, working on Amharic language projects with limited data is certainly possible. It requires careful consideration of the limitations, innovative approaches to overcome data scarcity, and a commitment to continuous improvement. By leveraging community efforts and staying abreast of technological advancements, significant progress can be made in this area.</p><p><strong>Abubeker Shamil</strong></p><p>Gen AI Engineer| AI Enthusiast | Tech Blogger</p><p>🔍 Exploring the intersection of AI and language technologies. Passionate about leveraging AI to solve real-world problems.</p><p>📫 Connect with me</p><ul><li><a href="https://www.linkedin.com/in/abubeker-shamil/">LinkedIn</a></li><li><a href="https://github.com/dev-abuke">GitHub</a></li></ul><p>👏 Don’t forget to drop a clap if you like this blog!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22e4c4c3564d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginners Step-by-Step Guide to Finetuning a Model — How To]]></title>
            <link>https://medium.com/@abubekershamil/beginners-step-by-step-guide-to-finetuning-a-model-how-to-827eac8a7bd7?source=rss-dec8d7adb524------2</link>
            <guid isPermaLink="false">https://medium.com/p/827eac8a7bd7</guid>
            <dc:creator><![CDATA[Abubeker]]></dc:creator>
            <pubDate>Thu, 30 May 2024 09:15:18 GMT</pubDate>
            <atom:updated>2024-05-30T09:40:24.370Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beginners Step-by-Step Guide to Finetuning a Model — How To</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*Jy68k2xD71Vxp_CxXtVJyA.png" /><figcaption>image credit to <a href="https://intellipaat.com/blog/fine-tuning/">https://intellipaat.com/blog/fine-tuning/</a></figcaption></figure><h3>Understanding the LLM Landscape and Concepts</h3><p>Start by reviewing the key concepts related to LLMs, transformers, and fine-tuning. Focus on the following</p><ul><li><strong>LLMs and Transformers </strong>Understand the architecture, including encoders, decoders, self-attention mechanisms, and positional embeddings.</li><li><strong>Fine-Tuning Techniques </strong>Learn about <a href="https://huggingface.co/docs/peft/en/index">PEFT</a>, <a href="https://zohaib.me/a-beginners-guide-to-fine-tuning-llm-using-lora/#:~:text=Low%2DRank%20Adaptation%20aka%20LoRA,lot%20of%20time%20and%20money.">LoRA</a>, and other parameter-efficient tuning methods.</li><li><strong>Amharic or Other Language Processing</strong> Look for resources and research papers that discuss NLP in your given language.</li></ul><h3>Set Up Your Environment</h3><p>Ensure you have a suitable environment for running the models:</p><p><strong>Create a Virtual Environment</strong></p><pre>python -m venv llm_env source llm_env/bin/activate  </pre><p><strong>Install Necessary Libraries</strong></p><pre>pip install transformers datasets tokenizers torch</pre><p><strong>Ensure GPU Availability:</strong> If you have a GPU, ensure CUDA is installed and configured properly. Check GPU availability in your environment:</p><pre>import torch print(torch.cuda.is_available())</pre><h3>Data Preparation</h3><ol><li><strong>Load and Explore the Data </strong>Load the dataset you collected in the previous week. Ensure the data is clean and formatted correctly.</li><li><strong>Preprocess the Data</strong></li></ol><ul><li>Tokenize the text data.</li><li>Remove any special characters, HTML tags, or irrelevant content.</li><li>Convert text to a format suitable for model training.</li></ul><p>Example code for data preprocessing</p><pre>from transformers import AutoTokenizer<br><br>tokenizer = AutoTokenizer.from_pretrained(&quot;your-model-name&quot;)<br><br>def preprocess_text(text):<br>    # Add your preprocessing steps here<br>    return text<br><br>dataset = [&quot;Sample text 1&quot;, &quot;Sample text 2&quot;]  # Replace with your actual dataset<br>processed_dataset = [preprocess_text(text) for text in dataset]<br>tokenized_dataset = tokenizer(processed_dataset, padding=True, truncation=True)</pre><h3>Model Selection and Loading</h3><ol><li><strong>Choose a Pre-trained Model </strong>Select a pre-trained model from Huggingface that supports Amharic, such as the finetuned versions of LLama-2 for Amharic.</li><li><strong>Load the Model and Tokenizer</strong></li></ol><pre>from transformers import AutoModelForCausalLM, AutoTokenizer  <br>model_name = &quot;your-model-name&quot;  # Replace with the chosen model name <br>model = AutoModelForCausalLM.from_pretrained(model_name) <br>tokenizer = AutoTokenizer.from_pretrained(model_name)</pre><h3>Fine-Tuning the Model</h3><ol><li><strong>Prepare for Fine-Tuning </strong>Set up the training configuration, including training data, batch size, learning rate, and number of epochs.</li><li><strong>Apply Fine-Tuning Techniques </strong>Use techniques like PEFT and LoRA to efficiently fine-tune the model.</li></ol><p>Example fine-tuning script</p><pre>from transformers import Trainer, TrainingArguments<br><br>training_args = TrainingArguments(<br>    output_dir=&quot;./results&quot;,<br>    num_train_epochs=3,<br>    per_device_train_batch_size=8,<br>    per_device_eval_batch_size=8,<br>    warmup_steps=500,<br>    weight_decay=0.01,<br>    logging_dir=&quot;./logs&quot;,<br>    logging_steps=10,<br>)<br><br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_dataset,  # Replace with your actual tokenized dataset<br>)<br><br>trainer.train()</pre><h3>Inference, Evaluate and Repeat</h3><p><strong>Test the Model</strong> Use the fine-tuned model to generate text, summarize, or answer questions.</p><p>Example inference code</p><pre>input_text = &quot;Your input text here&quot;<br>inputs = tokenizer(input_text, return_tensors=&quot;pt&quot;)<br>output = model.generate(**inputs, max_length=50)<br><br>generated_text = tokenizer.decode(output[0], skip_special_tokens=True)<br>print(generated_text)</pre><p><strong>Evaluate Performance</strong> Assess the model’s performance on various tasks and adjust training parameters if needed.</p><h3><strong>References</strong></h3><ul><li><a href="https://docs.ragas.io/en/stable/">Introduction | Ragas</a></li><li><a href="https://intellipaat.com/blog/fine-tuning/">What is Fine Tuning in Deep Learning? How Does It Work | Intellipaat</a></li><li><a href="https://medium.com/opla/transformers-made-easy-architecture-and-data-flow-f79f11961942">https://medium.com/opla/transformers-made-easy-architecture-and-data-flow-f79f11961942</a></li><li><a href="https://huggingface.co/docs/peft/index">PEFT (huggingface.co)</a></li><li><a href="https://harrisonpim.com/blog/understanding-positional-embeddings-in-transformer-models">https://harrisonpim.com/blog/understanding-positional-embeddings-in-transformer-models</a></li><li><a href="https://huggingface.co/blog/4bit-transformers-bitsandbytes">https://huggingface.co/blog/4bit-transformers-bitsandbytes</a></li></ul><p><strong>Please note this is a guide, not a comprehensive tutorial. It is intended for beginners.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=827eac8a7bd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing NLP Capabilities for Ethiopian Languages - Amharic: A Scalable Data Warehouse Project]]></title>
            <link>https://medium.com/@abubekershamil/enhancing-nlp-capabilities-for-ethiopian-languages-amharic-a-scalable-data-warehouse-project-c2735e9a844f?source=rss-dec8d7adb524------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2735e9a844f</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[data-ingestion]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[scraping]]></category>
            <dc:creator><![CDATA[Abubeker]]></dc:creator>
            <pubDate>Sat, 25 May 2024 19:52:57 GMT</pubDate>
            <atom:updated>2024-05-25T19:52:57.124Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s technology-driven world, the ability to process and understand text in multiple languages is critical for developing innovative applications. Roots Tech Solutions embarked on a mission to enhance its Natural Language Processing (NLP) capabilities Amharic language. This blog post details our journey in building a scalable data warehouse to support these efforts, focusing on high throughput data ingestion and Retrieval-Augmented Generation (RAG) retrieval.</p><h3>Business Need</h3><p>Roots Tech Solutions aims to develop a comprehensive data corpus to support various NLP applications, such as semantic search, content generation, chatbot support, sentiment analysis, and speech recognition. The current lack of extensive, high-quality text/audio datasets for Swahili, Yoruba, and Amharic is a significant bottleneck. By collecting and processing vast amounts of text/audio data from diverse online sources, we aim to overcome this challenge and significantly enhance our NLP capabilities.</p><h3>Project Design</h3><p>To achieve our goals, we designed a multi-stage pipeline comprising data collection, processing, API development, and automation. The project was divided into the following stages</p><h4><strong>Data Collection and Storage</strong></h4><ul><li><strong>Tools Used </strong>Selenium for web scraping, PostgreSQL for data storage.</li><li><strong>Implementation </strong>We identified and listed potential data sources such as news websites, blogs, and social media platforms. Web scraping scripts were developed to collect text data, which was then stored in a structured database.</li></ul><h4><strong>Data Processing</strong></h4><ul><li><strong>Tools Used</strong> Python for data cleaning and preprocessing.</li><li><strong>Implementation</strong>: Raw text data was cleaned and processed to remove HTML tags, special characters, and normalize whitespace. The cleaned data was stored back into the database.</li></ul><h4><strong>API Development for Data Access</strong></h4><ul><li><strong>Tools Used</strong> Flask for RESTful APIs; React for the frontend interface.</li><li><strong>Implementation </strong>APIs were developed to enable querying and retrieving data from the database. A frontend interface was created to interact with the API and display the data.</li></ul><h4><strong>Automation &amp; Stream Processing</strong></h4><ul><li><strong>Tools Used</strong> Apache Airflow for workflow automation and Docker for containerization.</li><li><strong>Implementation</strong> An automated pipeline was set up to ensure continuous data collection, processing, and access. Workflow automation was achieved using Apache Airflow, and the pipeline was containerized with Docker for easy deployment.</li></ul><h3>Code Implementation</h3><p>Below is the implementation of the web scraping code using Selenium for extracting news articles from a website. The code handles various aspects of scraping, including initialization, navigation, data extraction, and pagination.</p><pre>from enum import Enum<br>import re<br>from selenium import webdriver<br>from selenium.webdriver.common.by import By<br>from selenium.webdriver.chrome.service import Service<br>from webdriver_manager.chrome import ChromeDriverManager<br>from selenium.webdriver.remote.webelement import WebElement<br>from selenium.common.exceptions.WebDriverException<br><br>class AlainNewsCategory(Enum):<br>    POLITICS = &#39;politics&#39;<br>    SOCIAL = &#39;social&#39;<br>    ECONOMY = &#39;economy&#39;<br>    VARIETIES = &#39;varieties&#39;<br>    SPORT = &#39;sports&#39;<br><br>class AlainNewsButton(Enum):<br>    LOADING = &quot;ተጨማሪ ጫን&quot;<br>    NEXT_PAGE = &#39;next page&#39;<br><br>class AlainNewsScraper:<br>    def __init__(self, url: str, headless: bool = True, number_of_pages_to_scrape: int = 1) -&gt; None:<br>        options = webdriver.ChromeOptions()<br>        if headless:<br>            options.add_argument(&quot;--headless&quot;)<br>        self.driver = webdriver.Chrome(<br>            options=options, <br>            service=Service(ChromeDriverManager().install())<br>        )<br>        self.url = url<br>        self.number_of_pages_to_scrape = number_of_pages_to_scrape<br><br>    def scroll_to_bottom(self) -&gt; None:<br>        try:<br>            self.driver.execute_script(&quot;window.scrollTo(0, document.body.scrollHeight);&quot;)<br>        except WebDriverException as e:<br>            print(&quot;Error while scrolling to the bottom of the page:&quot;, e)<br>            raise<br><br>    def initialize_driver(self, category: AlainNewsCategory) -&gt; None:<br>        category_page_url = f&quot;{self.url}/section/{category.value}/&quot;<br>        try:<br>            self.driver.get(category_page_url)<br>        except WebDriverException as e:<br>            print(&quot;Error while navigating to the category page:&quot;, e)<br>            raise<br><br>    def get_all_articles_on_page_by_category(self) -&gt; list[WebElement]:<br>        try:<br>            self.scroll_to_bottom()<br>        except WebDriverException as e:<br>            print(&quot;Error while scrolling to the bottom of the page:&quot;, e)<br>            raise<br><br>        next_page = self.get_next_page_element()<br>        while next_page.text == AlainNewsButton.LOADING.value:<br>            try:<br>                next_page = self.get_next_page_element()<br>            except WebDriverException as e:<br>                print(&quot;Error while waiting for the next page element to load:&quot;, e)<br>                raise<br><br>        try:<br>            return self.get_articles_element()<br>        except WebDriverException as e:<br>            print(&quot;Error while retrieving the article elements:&quot;, e)<br>            raise<br><br>    def get_articles_element(self) -&gt; list[WebElement]:<br>        try:<br>            row_element = self.driver.find_element(By.XPATH, &#39;//div[@class=&quot;row loadmore&quot;]&#39;)<br>            articles = row_element.find_elements(By.TAG_NAME, &#39;article&#39;)<br>            if not articles:<br>                print(&quot;No articles found on the page.&quot;)<br>            return articles<br>        except WebDriverException as e:<br>            print(&quot;Error while retrieving the article elements:&quot;, e)<br>            return []<br><br>    def get_next_page_element(self) -&gt; WebElement:<br>        try:<br>            footer_element = self.driver.find_elements(By.TAG_NAME, &#39;footer&#39;)[0]<br>            return footer_element.find_element(By.TAG_NAME, &#39;a&#39;)<br>        except WebDriverException as e:<br>            print(&quot;Error while retrieving the next page element:&quot;, e)<br>            raise<br><br>    def get_image_url(https://medium.com/self,%20article:%20WebElement) -&gt; str:<br>        try:<br>            image_element = article.find_element(By.TAG_NAME, &#39;img&#39;)<br>            image_url = image_element.get_attribute(&#39;srcset&#39;)<br>            image_url = re.sub(r&#39;\s\d+w&#39;, &#39;&#39;, image_url).split(&#39;,&#39;)[0]<br>            return image_url.strip()<br>        except WebDriverException as e:<br>            print(&quot;Error while retrieving the image URL of the article:&quot;, e)<br>            return &quot;&quot;<br><br>    def get_title(self, article: WebElement) -&gt; str:<br>        try:<br>            title_element = article.find_element(By.CLASS_NAME, &#39;card-title&#39;).find_element(By.TAG_NAME, &#39;a&#39;)<br>            return title_element.text<br>        except WebDriverException as e:<br>            print(&quot;Error while retrieving the title of the article:&quot;, e)<br>            return &quot;&quot;<br><br>    def get_article_url(https://medium.com/self,%20article:%20WebElement) -&gt; str:<br>        try:<br>            title_element = article.find_element(By.CLASS_NAME, &#39;card-title&#39;).find_element(By.TAG_NAME, &#39;a&#39;)<br>            return title_element.get_attribute(&#39;href&#39;)<br>        except WebDriverException as e:<br>            print(&quot;Error while retrieving the article URL of the article:&quot;, e)<br>            return &quot;&quot;<br><br>    def get_highlight(self, article: WebElement) -&gt; str:<br>        try:<br>            highlight_element = article.find_element(By.CLASS_NAME, &#39;card-text&#39;)<br>            return highlight_element.text<br>        except WebDriverException as e:<br>            print(&quot;Error while retrieving the highlight of the article:&quot;, e)<br>            return &quot;&quot;<br><br>    def get_time_publish(self, article: WebElement) -&gt; str:<br>        try:<br>            time_element = article.find_element(By.TAG_NAME, &#39;time&#39;)<br>            return time_element.text<br>        except WebDriverException as e:<br>            print(&quot;Error while retrieving the time published of the article:&quot;, e)<br>            return &quot;&quot;<br><br>    def get_news(self) -&gt; list[dict]:<br>        news = []<br>        for category in AlainNewsCategory:<br>            self.initialize_driver(category)<br>            pages_to_scrape = self.number_of_pages_to_scrape<br>            while pages_to_scrape &gt; 0:<br>                pages_to_scrape -= 1<br>                articles = self.get_all_articles_on_page_by_category()<br>                if not articles:<br>                    print(f&quot;No articles found on page {pages_to_scrape + 1} of category {category.value}&quot;)<br>                else:<br>                    for article in articles:<br>                        try:<br>                            news.append(<br>                                {<br>                                    &quot;image_url&quot;: self.get_image_url(https://medium.com/article),<br>                                    &quot;title&quot;: self.get_title(article),<br>                                    &quot;article_url&quot;: self.get_article_url(https://medium.com/article),<br>                                    &quot;highlight&quot;: self.get_highlight(article),<br>                                    &quot;time_publish&quot;: self.get_time_publish(article),<br>                                    &quot;category&quot;: category.value<br>                                }<br>                            )<br>                        except (WebDriverException, AttributeError, Exception) as e:<br>                            print(f&quot;Error while scraping article on page {pages_to_scrape + 1} of category {category.value}:&quot;, e)<br>                next_page = self.get_next_page_element()<br>                if next_page.text == AlainNewsButton.NEXT_PAGE.value and pages_to_scrape &gt; 0:<br>                    self.driver.execute_script(&quot;arguments[0].click();&quot;, next_page)<br>                else:<br>                    break<br>        return news<br><br>    def get_full_news(self) -&gt; list[dict]:<br>        news = self.get_news()<br>        for n in news:<br>            try:<br>                self.driver.get(n.get(&#39;article_url&#39;))<br>                detail_content = self.driver.find_element(By.ID, &#39;content-details&#39;).text<br>                publisher_name = self.driver.find_element(By.CLASS_NAME, &#39;card-author&#39;).text<br>                date_published = self.driver.find_element(By.CLASS_NAME, &#39;tags&#39;).find_element(By.TAG_NAME, &#39;time&#39;).text<br><br>                n[&quot;date_published&quot;] = date_published<br>                n[&quot;publisher_name&quot;] = publisher_name<br>                n[&quot;detail_content&quot;] = detail_content<br>            except (WebDriverException, AttributeError, Exception) as e:<br>                print(f&quot;Error while scraping content page of category {n.get(&#39;category&#39;)} and url {n.get(&#39;article_url&#39;)}:&quot;, e)<br>        return news<br><br>    def quit_driver(self):<br>        self.driver.quit()</pre><h3>Why We Chose to Start with a News Website</h3><ol><li><strong>Rich and Structured Data </strong>News websites typically have a well-defined structure with articles organized into categories, making it easier to navigate and extract information systematically. This structured format is ideal for developing and testing web scraping methodologies.</li><li><strong>Availability of Diverse Content </strong>News websites provide a wide range of topics, including politics, social issues, economy, sports, and more. This diversity allows us to test the versatility and robustness of our scraping tools across various types of content.</li><li><strong>Low Risk of API Rate Limiting</strong> Unlike social media platforms, which often have strict API rate limits and access restrictions, news websites generally do not impose such limits. This enables continuous and uninterrupted data collection, which is crucial for comprehensive data analysis.</li></ol><h3>Data Collection and Processing Methodologies</h3><p>The process of collecting and processing data for Amharic language NLP involved several steps</p><h4><strong>Setup and Configuration</strong></h4><ul><li>Installed Selenium for web scraping and PostgreSQL for database management.</li><li>Configured version control with Git for collaborative development.</li></ul><h4><strong>Web Scraping</strong></h4><ul><li>Developed scripts using Selenium to scrape text data from various sources, including news websites and telegram channels.</li><li>Implemented error handling and retries to ensure robustness and continuity in data collection.</li></ul><h4><strong>Data Cleaning and Preprocessing</strong></h4><ul><li>Normalized text by removing punctuation and special characters.</li><li>Filtered the data to focus on Amharic content, minimizing contamination by other languages.</li></ul><h4><strong>API Development (Collaboration)</strong></h4><ul><li>Developed APIs using FastAPI to provide access to the collected data.</li><li>Implemented endpoints for searching and retrieving data based on keywords and metadata.</li></ul><h4><strong>Storing and Managing Data</strong></h4><ul><li>Designed an SQL schema for structured storage of the raw and processed data in PostgreSQL.</li><li>Ensured efficient retrieval and management of large datasets.</li></ul><h3>Expanding Scraping Efforts</h3><p>After establishing a reliable scraping pipeline for news websites, the next step is to extend our efforts to social media platforms like Telegram. These platforms offer valuable real-time data and user-generated content that can enhance our NLP tasks. Here are the key reasons for expanding to social media:</p><ol><li><strong>Real-Time Data </strong>Social media platforms provide up-to-date information, which is crucial for applications like sentiment analysis and trend detection.</li><li><strong>User-Generated Content</strong> The diverse and unstructured nature of social media content offers a rich dataset for training NLP models.</li><li><strong>Broader Coverage</strong> By including social media data, we can cover a wider range of topics and perspectives, improving the comprehensiveness of our data corpus.</li><li><strong>Engagement Insights</strong> Social media interactions can provide insights into user behavior and preferences, which are valuable for developing more effective NLP applications.</li></ol><h3>Frontend Development</h3><p>For the frontend, we used React with Vite to create a responsive and interactive interface for accessing and displaying the collected data. The following code snippet demonstrates the implementation of the frontend component that fetches data from our API and displays it with search functionality.</p><p><strong>Frontend Code Implementation</strong></p><pre>import { useState, useEffect } from &quot;react&quot;;<br>import { data } from &quot;./data.js&quot;;<br>//import axios from &quot;axios&quot;;<br>import &quot;./App.css&quot;;<br>import DataList from &quot;./search.jsx&quot;;<br>import Table from &quot;./table.jsx&quot;;<br>// import Api_using_axios from &quot;./Components/Api_using_axios.jsx&quot;;<br>function App() {<br>  const [search, setSearch] = useState(&quot;&quot;);<br>  console.log(search);<br>  return (<br>      &lt;div className=&quot;flex flex-col&quot;&gt;<br>        &lt;DataList /&gt;<br>        &lt;Table /&gt;<br>      &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><h4><strong>State Management</strong></h4><ul><li>We use the useState hook to manage the state for the fetched data and the search query.</li></ul><h4><strong>Data Fetching</strong></h4><ul><li>The useEffect hook fetches data from the API endpoint (http://localhost:8000/data/articles) when the component mounts. The fetched data is then stored in the data state.</li><li>The axios library is used for making HTTP requests.</li></ul><h4><strong>Search Functionality</strong></h4><ul><li>The handleSearch function is triggered when the search form is submitted. It sends a request to the search endpoint (http://localhost:8000/search?query=${query}) with the search query.</li><li>The search results are then stored in the data state.</li></ul><h4><strong>Rendering Data</strong></h4><ul><li>The fetched data is displayed in a list. Each item in the data array is rendered as a list item with the title and content.</li></ul><h4><strong>Styling</strong></h4><ul><li>The component is styled using Tailwind CSS classes to ensure a responsive and visually appealing interface.</li></ul><h3>Automation &amp; Orchestration with Apache Airflow</h3><p><strong>Automation &amp; Orchestration:</strong></p><p>To ensure continuous data collection, cleaning, processing, and access, we set up an automated pipeline using Apache Airflow. The following sections describe the setup and implementation of Airflow, along with the corresponding DAGs and Dockerfile.</p><p><strong>Setting Up Apache Airflow:</strong></p><h4><strong>Install and Configure Apache Airflow</strong></h4><h4>Install Airflow using Docker</h4><p>Use the below compose file for docker and create a DAG folder</p><ul><li><a href="https://airflow.apache.org/docs/apache-airflow/2.9.1/docker-compose.yaml">airflow.apache.org/docs/apache-airflow/2.9.1/docker-compose.yaml</a></li></ul><h4>Initialize the Airflow database</h4><ul><li>docker-compose up airflow-init</li></ul><h4><strong>Define the Workflow DAG</strong></h4><ul><li>In your created DAG folder create a DAG file (data_pipeline_dag.py) to define the sequence of tasks for data collection, cleaning, processing, and storage</li></ul><p><strong>DAG Implementation (</strong><strong>pipeline_dag.py)</strong></p><pre>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br>from datetime import datetime, timedelta<br>from airflow.models import Variable<br>from db.connection.db_conn import DatabaseLoader<br># from api.models.database import Database<br>from sqlalchemy.orm import sessionmaker<br>from scrapper.news_sites.alain import AlainNewsScraper<br>from api.controllers.article_controller import create_data<br>import os<br>import logging<br><br># Set default arguments for the DAG<br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;start_date&#39;: datetime(2024, 5, 1),<br>    &#39;email_on_failure&#39;: False,<br>    &#39;email_on_retry&#39;: False,<br>    &#39;retries&#39;: 1,<br>    &#39;retry_delay&#39;: timedelta(minutes=5),<br>}<br><br># Initialize database connection<br>db_loader = DatabaseLoader()<br>db_loader.set_connection_url_from_dbname(Variable.get(&quot;db_database&quot;))<br>db_loader.connect()<br>SessionLocal = sessionmaker(bind=db_loader.engine)<br><br>def scrape_news(url, **kwargs):<br>    logging.info(f&quot;Starting scraping news from {url}&quot;)<br>    scraper = AlainNewsScraper(url=url)<br>    news_data = scraper.get_full_news()<br>    logging.info(f&quot;Scraped {len(news_data)} articles&quot;)<br>    # Push the result to XCom<br>    kwargs[&#39;ti&#39;].xcom_push(key=&#39;news_data&#39;, value=news_data)<br><br>def save_to_database(**kwargs):<br>    # Pull the news data from XCom<br>    news_data = kwargs[&#39;ti&#39;].xcom_pull(task_ids=&#39;scrape_news_task&#39;, key=&#39;news_data&#39;)<br>    if not news_data:<br>        logging.error(&quot;No news data found in XCom&quot;)<br>        return<br><br>    session = SessionLocal()<br>    try:<br>        for article in news_data:<br>            db_data = create_data(session, article)<br>            session.add(db_data)<br>        session.commit()<br>        logging.info(&quot;News data saved to database successfully&quot;)<br>    except Exception as e:<br>        session.rollback()<br>        logging.error(f&quot;Error saving to database: {e}&quot;)<br>        raise e<br>    finally:<br>        session.close()<br><br># Define the DAG<br>with DAG(&#39;news_pipeline&#39;, default_args=default_args, schedule_interval=&#39;@daily&#39;, catchup=False) as dag:<br>    scrape_task = PythonOperator(<br>        task_id=&#39;scrape_news_task&#39;,<br>        python_callable=scrape_news,<br>        op_kwargs={&#39;url&#39;: Variable.get(&quot;news_scraper_url&quot;)},<br>        provide_context=True,<br>    )<br><br>    initialize_db_task = PythonOperator(<br>        task_id=&#39;initialize_db_task&#39;,<br>        python_callable=db_loader.connect(),<br>        provide_context=True,<br>    )<br><br>    scrape_task &gt;&gt; initialize_db_task<br><br>    save_to_db_task = PythonOperator(<br>        task_id=&#39;save_to_db_task&#39;,<br>        python_callable=save_to_database,<br>        provide_context=True,<br>    )<br><br>    [scrape_task, initialize_db_task] &gt;&gt; save_to_db_task</pre><h3>Challenges Faced</h3><p>Throughout the project, we encountered several challenges:</p><ul><li><strong>Data Quality</strong> Ensuring the quality and relevance of the collected data was a significant challenge. We implemented rigorous cleaning and preprocessing steps to address this.</li><li><strong>Scalability </strong>Handling large-scale data access requests efficiently required careful design and optimization of our APIs and database schema.</li><li><strong>Automation</strong> Setting up and managing an automated pipeline involved complexities in workflow orchestration and monitoring.</li></ul><h3>Results and Lessons Learned</h3><p>The project will significantly enhance our NLP capabilities for Amharic languages. We successfully developed a scalable data warehouse and automated pipeline, enabling efficient data collection, processing, and access. Key lessons learned include the importance of robust data cleaning processes, the benefits of containerization for deployment, and the value of automation in maintaining an efficient workflow.</p><h3>Future Plans</h3><p>Looking ahead, we plan to</p><ul><li>Expand our data collection to include more diverse sources.</li><li>Improve our data annotation processes to create labeled datasets for various NLP tasks.</li><li>Explore advanced NLP techniques and models to further enhance our capabilities.</li><li>Expand the languages in Ethiopian ethnic languages as there are more than 80</li></ul><h3>Conclusion</h3><p>This project marks a significant step forward in our mission to enhance NLP capabilities for African languages. By building a scalable data warehouse and automating our data pipeline, we have laid a strong foundation for developing sophisticated NLP applications. We are excited about the potential impact of this work and look forward to continuing our efforts in this area.</p><h4>References</h4><ul><li><a href="https://www.selenium.dev/">Selenium</a></li><li><a href="https://scrapy.org/">Scrapy</a></li><li><a href="https://beautiful-soup-4.readthedocs.io/en/latest/">BeautifulSoup</a></li><li><a href="https://prometheus.io/">Prometheus</a></li><li><a href="https://airflow.apache.org/">Apache Airflow</a></li><li><a href="https://prodi.gy/">Prodigy</a></li><li><a href="https://medium.com/@swalperen3008/what-is-dockerize-and-dockerize-your-project-a-step-by-step-guide-899c48a34df6">Docker</a></li></ul><p>For more details on the work, visit our <a href="https://github.com/dev-abuke">GitHub repository</a> and connect on <a href="https://www.linkedin.com/in/abubeker-shamil/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2735e9a844f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overview of Methodologies and Tools Used for Data Collection to Aid in Amharic Language NLP]]></title>
            <link>https://medium.com/@abubekershamil/overview-of-methodologies-and-tools-used-for-data-collection-to-aid-in-amharic-language-nlp-c5663aa23ef4?source=rss-dec8d7adb524------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5663aa23ef4</guid>
            <category><![CDATA[data-collection]]></category>
            <category><![CDATA[scrapping]]></category>
            <category><![CDATA[amharic]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Abubeker]]></dc:creator>
            <pubDate>Wed, 22 May 2024 19:16:16 GMT</pubDate>
            <atom:updated>2024-05-22T19:16:16.404Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Project Overview</strong></h3><p>This project aims to enhance Natural Language Processing (NLP) capabilities for Amharic languages by developing a comprehensive data corpus. This involves collecting text/audio datasets from online sources to support various NLP applications like semantic search, content generation, chatbot support, sentiment analysis, and speech recognition.</p><h4><strong>Introduction</strong></h4><p>This report provides an overview of the methodologies and tools used for data collection through web scraping. It details the approach taken, the technologies employed, and a comparison of the web scraping tools used.</p><h4><strong>Methodologies and Tools</strong></h4><p>The data collection process involved automated web scraping using Selenium, a powerful web browser automation tool. The primary steps included:</p><ul><li>Initialization of the web driver</li><li>Navigation to the target website</li><li>Extraction of relevant data elements</li><li>Handling pagination</li><li>Storing extracted data for analysis</li></ul><p><strong>Selenium WebDriver </strong>was chosen for its robustness and ability to interact with web pages dynamically. It allows for automated browsing, form submissions, and interaction with JavaScript-heavy websites, making it ideal for complex scraping tasks.</p><p><strong>Python </strong>was used as the programming language due to its simplicity and the rich ecosystem of libraries available for data processing and web scraping.</p><p><strong>Pandas </strong>library was employed for data manipulation and analysis, enabling efficient handling of large datasets extracted through scraping.</p><h3><strong>Comparison of Web Scraping Tools</strong></h3><h4><strong>Selenium WebDriver</strong> <strong>Pros</strong></h4><ul><li><strong>Dynamic Interaction</strong> Can interact with JavaScript-heavy websites, handle form submissions, and simulate user actions.</li><li><strong>Flexibility</strong> Supports multiple browsers and programming languages.</li><li><strong>Detailed Control</strong> Allows fine-grained control over web page interactions.</li></ul><h4>Selenium WebDriver <strong>Cons</strong></h4><ul><li><strong>Resource Intensive </strong>Requires more system resources compared to other tools like BeautifulSoup.</li><li><strong>Complex Setup</strong> Initial setup and configuration can be more complex.</li></ul><h4><strong>BeautifulSoup</strong> <strong>Pros</strong></h4><ul><li><strong>Simplicity</strong>: Easy to learn and use, making it ideal for beginners.</li><li><strong>Efficiency</strong>: Less resource-intensive compared to Selenium.</li><li><strong>HTML Parsing</strong>: Excellent for parsing static HTML pages.</li></ul><h4><strong>BeautifulSoup Cons</strong></h4><ul><li><strong>Limited to Static Pages</strong>: Cannot interact with dynamic content that requires JavaScript execution.</li><li><strong>Dependency</strong>: Often used in combination with other tools like Requests for complete scraping solutions.</li></ul><h3><strong>Code Implementation</strong></h3><p>The scraping code was implemented as follows</p><pre>from enum import Enum<br>import re<br>from selenium import webdriver<br>from selenium.webdriver.common.by import By<br>from selenium.webdriver.chrome.service import Service<br>from webdriver_manager.chrome import ChromeDriverManager<br>from selenium.webdriver.remote.webelement import WebElement<br>from selenium.common.exceptions import WebDriverException<br><br>class AlainNewsCategory(Enum):<br>    POLITICS = &#39;politics&#39;<br>    SOCIAL = &#39;social&#39;<br>    ECONOMY = &#39;economy&#39;<br>    VARIETIES = &#39;varities&#39;<br>    SPORT = &#39;sports&#39;<br><br>class AlainNewsButton(Enum):<br>    LOADING = &quot;ተጨማሪ ጫን&quot;<br>    NEXT_PAGE = &#39;next page&#39;<br><br>class AlainNewsScraper:<br>    def __init__(<br>        self, <br>        url: str, <br>        headless: bool = True, <br>        number_of_pages_to_scrape: int = 1<br>    ) -&gt; None:<br>        &quot;&quot;&quot;<br>        Initialize the AlainNewsScraper object<br><br>        Args:<br>            url (str): The URL of the Alain news website<br>            headless (bool, optional): Whether to run the web driver in headless mode. Defaults to True.<br>            number_of_pages_to_scrape (int, optional): The number of pages of articles to scrape. Defaults to 1.<br>        &quot;&quot;&quot;<br>        # Create a new instance of the Chrome web driver<br>        # We use headless mode to avoid seeing the browser window pop up<br>        # in the background while the script is running<br>        options = webdriver.ChromeOptions()<br>        if headless:<br>            options.add_argument(&quot;--headless&quot;)<br>        self.driver = webdriver.Chrome(<br>            options=options, <br>            service=Service(ChromeDriverManager().install())<br>        )<br>        # Store the URL of the website we&#39;re scraping and the number of<br>        # pages of articles to scrape<br>        self.url = url<br>        self.number_of_pages_to_scrape = number_of_pages_to_scrape<br><br>    def scroll_to_bottom(self) -&gt; None:<br>        &quot;&quot;&quot;<br>        Scrolls the web page to the bottom using JavaScript.<br><br>        This function executes a JavaScript command to scroll the web page to the bottom.<br>        It uses the `execute_script` method of the `driver` object to execute the command.<br>        The command is `&quot;window.scrollTo(0, document.body.scrollHeight);&quot;`, which scrolls the page<br>        to the bottom by setting the scroll position to the maximum height of the document body.<br><br>        Raises:<br>            WebDriverException: If an error occurs while scrolling to the bottom of the page.<br><br>        Returns:<br>            None<br>        &quot;&quot;&quot;<br>        try:<br>            self.driver.execute_script(&quot;window.scrollTo(0, document.body.scrollHeight);&quot;)<br>        except WebDriverException as e:<br>            print(&quot;WebDriverException error occurred while scrolling to the bottom of the page:&quot;, e)<br>            raise<br><br>    def initialize_driver(self, category: AlainNewsCategory) -&gt; None:<br>        &quot;&quot;&quot;<br>        Initializes the web driver and navigates to the specified category page.<br><br>        Args:<br>            category (AlainNewsCategory): The category to navigate to.<br><br>        Raises:<br>            WebDriverException: If an error occurs while navigating to the category page.<br><br>        Returns:<br>            None<br>        &quot;&quot;&quot;<br>        category_page_url = f&quot;{self.url}/section/{category.value}/&quot;<br>        <br>        try:<br>            self.driver.get(category_page_url)<br>        except WebDriverException as e:<br>            print(&quot;WebDriverException error occurred while navigating to the category page:&quot;, e)<br>            raise<br><br>    def get_all_articles_on_page_by_category(self) -&gt; list[WebElement]:<br>        &quot;&quot;&quot;<br>        Retrieves all the articles on the current page for a given category.<br><br>        This function performs the following steps:<br><br>            1. Scrolls to the bottom of the page to load more articles, if available.<br>            2. Retrieves the next page element and checks if it is still loading.<br>            3. If it is, waits until the loading is complete and retrieves the articles element.<br><br>        Returns:<br>            list[WebElement]: A list of WebElement objects representing the articles on the current page for the given category.<br><br>        Raises:<br>            WebDriverException: If an error occurs while retrieving the article elements.<br>        &quot;&quot;&quot;<br><br>        # Scroll to the bottom of the page to load more articles<br>        try:<br>            self.scroll_to_bottom()<br>        except WebDriverException as e:<br>            print(&quot;WebDriverException error occurred while scrolling to the bottom of the page:&quot;, e)<br>            raise<br><br>        # Retrieve the next page element and check if it is still loading<br>        next_page = self.get_next_page_element()<br>        while next_page.text == AlainNewsButton.LOADING.value:<br>            try:<br>                # If it is, wait until the loading is complete and retrieve the articles element<br>                next_page = self.get_next_page_element()<br>            except WebDriverException as e:<br>                print(&quot;WebDriverException error occurred while waiting for the next page element to load:&quot;, e)<br>                raise<br><br>        # Return the articles element<br>        try:<br>            return self.get_articles_element()<br>        except WebDriverException as e:<br>            print(&quot;WebDriverException error occurred while retrieving the article elements:&quot;, e)<br>            raise<br><br><br>    def get_articles_element(self) -&gt; list[WebElement]:<br>        try:<br>            row_element = self.driver.find_element(By.XPATH, &#39;//div[@class=&quot;row loadmore&quot;]&#39;)<br>            articles = row_element.find_elements(By.TAG_NAME, &#39;article&#39;)<br>            if not articles:<br>                print(&quot;No articles found on the page.&quot;)<br>            return articles<br>        except WebDriverException as e:<br>            print(&quot;WebDriverException error occurred while retrieving the article elements:&quot;, e)<br>            return []<br><br>    def get_next_page_element(self) -&gt; WebElement:<br>        try:<br>            footer_element = self.driver.find_elements(By.TAG_NAME, &#39;footer&#39;)[0]<br>            return footer_element.find_element(By.TAG_NAME, &#39;a&#39;)<br>        except WebDriverException as e:<br>            print(&quot;WebDriverException error occurred while retrieving the next page element:&quot;, e)<br>            raise<br><br>    def get_image_url(https://medium.com/self,%20article:%20WebElement) -&gt; str:<br>        try:<br>            image_element = article.find_element(By.TAG_NAME, &#39;img&#39;)<br>            image_url = image_element.get_attribute(&#39;srcset&#39;)<br>            image_url = re.sub(r&#39;\s\d+w&#39;, &#39;&#39;, image_url).split(&#39;,&#39;)[0]<br>            return image_url.strip()<br>        except WebDriverException as e:<br>            print(&quot;WebDriverException error occurred while retrieving the image url of the article:&quot;, e)<br>            return &quot;&quot;<br><br>    def get_title(self, article: WebElement) -&gt; str:<br>        try:<br>            title_element = article.find_element(By.CLASS_NAME, &#39;card-title&#39;).find_element(By.TAG_NAME, &#39;a&#39;)<br>            return title_element.text<br>        except WebDriverException as e:<br>            print(&quot;WebDriverException error occurred while retrieving the title of the article:&quot;, e)<br>            return &quot;&quot;<br><br>    def get_article_url(https://medium.com/self,%20article:%20WebElement) -&gt; str:<br>        try:<br>            title_element = article.find_element(By.CLASS_NAME, &#39;card-title&#39;).find_element(By.TAG_NAME, &#39;a&#39;)<br>            return title_element.get_attribute(&#39;href&#39;)<br>        except WebDriverException as e:<br>            print(&quot;WebDriverException error occurred while retrieving the article url of the article:&quot;, e)<br>            return &quot;&quot;<br><br>    def get_highlight(self, article: WebElement) -&gt; str:<br>        try:<br>            highlight_element = article.find_element(By.CLASS_NAME, &#39;card-text&#39;)<br>            return highlight_element.text<br>        except WebDriverException as e:<br>            print(&quot;WebDriverException error occurred while retrieving the highlight of the article:&quot;, e)<br>            return &quot;&quot;<br><br>    def get_time_publish(self, article: WebElement) -&gt; str:<br>        try:<br>            time_element = article.find_element(By.TAG_NAME, &#39;time&#39;)<br>            return time_element.text<br>        except WebDriverException as e:<br>            print(&quot;WebDriverException error occurred while retrieving the time publish of the article:&quot;, e)<br>            return &quot;&quot;<br><br>    def get_news(self) -&gt; list[dict]:<br>        &quot;&quot;&quot;<br>        Retrieves news articles from various categories using web scraping.<br><br>        This function first initializes the web driver for each category in the AlainNewsCategory enum.<br>        Then, it navigates to each page of the given category and retrieves all the articles on that page.<br>        For each article, it retrieves the following information:<br><br>            - The image URL of the article<br>            - The title of the article<br>            - The URL of the article<br>            - The highlight/summary of the article<br>            - The time the article was published<br>            - The category of the article<br><br>        Raises:<br>            WebDriverException: If there is an error with the web driver.<br>            AttributeError: If an attribute is not found.<br>            Exception: If any other error occurs during scraping.<br>        &quot;&quot;&quot;<br>        news = []  # List to store all the news articles<br>        for category in AlainNewsCategory:  # Iterate through all categories<br>            self.initialize_driver(category)  # Initialize the web driver for the given category<br>            pages_to_scrape = self.number_of_pages_to_scrape  # Get the number of pages to scrape for the given category<br>            while pages_to_scrape &gt; 0:  # While there are still pages to scrape<br>                pages_to_scrape -= 1  # Decrement the number of pages to scrape<br>                articles = self.get_all_articles_on_page_by_category()  # Get all the articles on the current page<br>                if not articles:  # If there are no articles on the current page<br>                    print(f&quot;No articles found on page {pages_to_scrape + 1} of category {category.value}&quot;)  # Print an error message<br>                else:  # If there are articles on the current page<br>                    for article in articles:  # Iterate through all the articles on the current page<br>                        try:<br>                            news.append(  # Create a dictionary for the current article<br>                                {<br>                                    &quot;image_url&quot;: self.get_image_url(https://medium.com/article),  # The URL of the article&#39;s image<br>                                    &quot;title&quot;: self.get_title(article),  # The title of the article<br>                                    &quot;article_url&quot;: self.get_article_url(https://medium.com/article),  # The URL of the article<br>                                    &quot;highlight&quot;: self.get_highlight(article),  # The highlight/summary of the article<br>                                    &quot;time_publish&quot;: self.get_time_publish(article),  # The time the article was published<br>                                    &quot;category&quot;: category.value  # The category of the article<br>                                }<br>                            )<br>                        except (WebDriverException, AttributeError, Exception) as e:  # Catch any errors during scraping<br>                            print(f&quot;An error occurred while scraping article on page {pages_to_scrape + 1} of category {category.value}:&quot;, e)  # Print an error message<br>                next_page = self.get_next_page_element()  # Get the next page element<br>                if next_page.text == AlainNewsButton.NEXT_PAGE.value and pages_to_scrape &gt; 0:  # If the next page element says &quot;Next Page&quot; and there are still pages to scrape<br>                    self.driver.execute_script(&quot;arguments[0].click();&quot;, next_page)  # Click the next page element<br>                else:  # If the next page element does not say &quot;Next Page&quot; or there are no more pages to scrape<br>                    break  # Break out of the loop<br>        return news  # Return the list of news articles<br><br><br>    def get_full_news(self) -&gt; list[dict]:<br>        &quot;&quot;&quot;<br>        Retrieves all the news articles and their corresponding content.<br><br>        This function first retrieves all the news articles using the `get_news` method.<br>        Then, for each article, it navigates to the content page of the article and retrieves<br>        the following information:<br><br>            - The date the article was published<br>            - The name of the publisher of the article<br>            - The content of the article<br><br>        The retrieved information is then added to the existing information of the article<br>        as a dictionary and the updated dictionary is returned.<br><br>        Returns:<br>            list[dict]: A list of dictionaries, where each dictionary represents a news article<br>                and its corresponding content.<br>        &quot;&quot;&quot;<br>        news = self.get_news()<br>        for n in news:<br>            # print(&quot;The article on page of category {} is: {}&quot;.format(n.get(&#39;category&#39;), n.get(&#39;article_url&#39;)))<br>            try:<br>                # Navigate to the content page of the article<br>                self.driver.get(n.get(&#39;article_url&#39;))<br><br>                # Retrieve the content of the article<br>                detail_content = self.driver.find_element(By.ID, &#39;content-details&#39;).text<br><br>                # Retrieve the publisher name of the article<br>                publisher_name = self.driver.find_element(By.CLASS_NAME, &#39;card-author&#39;).text<br><br>                # Retrieve the date the article was published<br>                date_published = self.driver.find_element(By.CLASS_NAME, &#39;tags&#39;).find_element(By.TAG_NAME, &#39;time&#39;).text<br><br>                # Add the retrieved information to the existing information of the article<br>                # as a dictionary<br>                n[&quot;date_published&quot;] = date_published<br>                n[&quot;publisher_name&quot;] = publisher_name<br>                n[&quot;detail_content&quot;] = detail_content<br><br>            except (WebDriverException, AttributeError, Exception) as e:<br>                print(f&quot;An error occurred while scraping content page of category {n.get(&#39;category&#39;)} and url {n.get(&#39;article_url&#39;)}:: {e}&quot;)<br>        return news<br><br><br>    # Quit the web driver<br>    # This method closes the web driver and terminates the underlying browser process<br>    # It is generally a good practice to quit the web driver as soon as you are<br>    # finished using it to free up system resources<br>    def quit_driver(self):<br>        &quot;&quot;&quot;<br>        Quit the web driver<br><br>        This method closes the web driver and terminates the underlying browser process<br>        It is generally a good practice to quit the web driver as soon as you are<br>        finished using it to free up system resources<br>        &quot;&quot;&quot;<br>        self.driver.quit()</pre><h3>Why We Chose to Start with a News Website</h3><h4><strong>Rich and Structured Data</strong></h4><ul><li>News websites typically have a well-defined structure with articles organized into categories, making it easier to navigate and extract information systematically. This structured format is ideal for developing and testing web scraping methodologies.</li></ul><h4><strong>Availability of Diverse Content</strong></h4><ul><li>News websites provide a wide range of topics, including politics, social issues, economy, sports, and more. This diversity allows us to test the versatility and robustness of our scraping tools across various types of content.</li></ul><h4><strong>Low Risk of API Rate Limiting</strong></h4><ul><li>Unlike social media platforms, which often have strict API rate limits and access restrictions, news websites generally do not impose such limits. This enables continuous and uninterrupted data collection, which is crucial for comprehensive data analysis.</li></ul><h4><strong>Accessibility</strong></h4><ul><li>News websites are easily accessible without requiring authentication or special permissions, unlike some social media platforms. This simplifies the initial setup and reduces barriers to starting the scraping process.</li></ul><h3><strong>Data Collection and Processing Methodologies</strong></h3><ul><li>Installed Selenium, and database management systems — PostgreSQL.</li><li>Configured version control with Git.</li></ul><h4><strong>Web Scraping</strong></h4><ul><li>Developed scripts to scrape text data from various sources using the tools mentioned.</li><li>Implemented error handling and retries for robustness.</li></ul><h4><strong>Data Cleaning and Preprocessing</strong></h4><ul><li>Normalized text by removing punctuation and special characters.</li><li>Filtered data to focus on Amharic.</li></ul><h4><strong>API Development (</strong><a href="https://github.com/jadmassu"><strong>Collaboration</strong></a><strong>)</strong></h4><ul><li>Developed APIs using FastAPI to provide access to the collected data.</li><li>Implemented endpoints for searching and retrieving data based on keywords and metadata.</li></ul><h3>Expanding Scraping Efforts</h3><h4><strong>Social Media Platforms</strong></h4><ul><li>After establishing a reliable scraping pipeline for news websites, we plan to extend our efforts to social media platforms like Telegram. These platforms offer valuable real-time data and user-generated content that can provide a great souce for our NLP tasks.</li></ul><h3><strong>Conclusion</strong></h3><p>The use of Selenium WebDriver for this web scraping project provided robust interaction capabilities with dynamic web pages. While it is resource-intensive and has a steeper learning curve, the flexibility and control it offers make it suitable for complex scraping tasks. Alternatively, tools like BeautifulSoup are ideal for simpler, static content scraping tasks due to their ease of use and lower resource requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5663aa23ef4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Redash Setup for Efficient Development]]></title>
            <link>https://medium.com/@abubekershamil/automating-redash-setup-for-efficient-development-1bb0f8f90c81?source=rss-dec8d7adb524------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bb0f8f90c81</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[reda]]></category>
            <category><![CDATA[redash]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Abubeker]]></dc:creator>
            <pubDate>Wed, 15 May 2024 20:27:34 GMT</pubDate>
            <atom:updated>2024-05-15T20:27:34.441Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*g-ogvVusf9CpZms5u1UhwQ.png" /></figure><p>Hello there! <br>If you’re tired of constantly running make up, make down, or make compose_build commands, you&#39;re not alone.</p><p>Compiling Redash can be frustrating, especially with the long wait times just to see your code changes. After enduring the waiting times and terminal commands, I found that my database was wiped clean, forcing me to re-register with email and password each time. I also had to reconnect the data source by entering passwords and other fields that I could barely remember.</p><p>I decided to streamline this repetitive process by automating these tasks with code. Here’s a guide to automate the setup of your Redash LLM Chatbot so you can focus on more productive aspects of your project.</p><h3>Automating Redash Setup with Python</h3><p>We need two files: a Python script to run commands and create the DataSource, and an SQL file for setup.</p><h4>Python Script</h4><p>First, create a Python script to automate the setup process:</p><pre>from redashAPI import RedashAPIClient<br>import os<br># Terminal command to run<br># Customize the setup.sql to change default login credentials and API key<br># TODO: Generate setup.sql file based on given arguments<br>command = &quot;make down &amp;&amp; make compose_build &amp;&amp; make up &amp;&amp; docker compose exec -u postgres -T postgres psql postgres &lt; setup.sql&quot;<br># Run the command in the terminal of the current working directory<br># Ensure your current working directory is the Redash source code directory<br># TODO: Update to add a path to the Redash source code directory<br>os.system(command)<br>Redash = RedashAPIClient(&quot;uwgC6V8ipibQbru2Y02R4bnjqjeOLwkcQc1pSECs&quot;, &quot;http://localhost:5001/&quot;)<br>data_source = Redash.post(&#39;data_sources&#39;, {<br>    &quot;name&quot;: &quot;__YOUR_DATA_SOURCE_NAME__&quot;,  # Update to your data source name<br>    &quot;type&quot;: &quot;pg&quot;,  # Update to your data source type<br>    &quot;options&quot;: {<br>        &quot;dbname&quot;: &quot;__DB_NAME__&quot;,  # Update to your database name<br>        &quot;host&quot;: &quot;__HOST__&quot;,  # Update to your database host<br>        &quot;user&quot;: &quot;__USER__&quot;,  # Update to your database user<br>        &quot;passwd&quot;: &quot;__PASSWORD__&quot;,  # Update to your database password<br>        &quot;port&quot;: 5432  # Update to your database port<br>    }<br>})<br>print(data_source)</pre><p>Before running the script, make sure you have the setup.sql file in the same folder as the Redash source. You can place them anywhere, but ensure the working directory is set to the Redash source because we will be running make up and other commands to compile Redash. Also, install the Redash API client using pip install redash-api-client.</p><p>The API key uwgC6V8ipibQbru2Y02R4bnjqjeOLwkcQc1pSECs is used here because it will be added to the setup.sql configuration, ensuring the API key is available when initializing the RedashAPIClient.</p><h4>Setup SQL File</h4><p>Next, create the setup.sql file with the following content:</p><pre>INSERT INTO public.organizations (updated_at, created_at, id, name, slug, settings)<br>    VALUES (now(), now(), 1, &#39;_ORGANIZATION_&#39;, &#39;default&#39;,<br>            &#39;{&quot;settings&quot;: {&quot;beacon_consent&quot;: false}}&#39;);<br><br>INSERT INTO public.groups (id, org_id, type, name, permissions, created_at)<br>    VALUES (1, 1, &#39;builtin&#39;, &#39;admin&#39;, &#39;{admin,super_admin}&#39;, now());<br><br>INSERT INTO public.groups (id, org_id, type, name, permissions, created_at)<br>    VALUES (2, 1, &#39;builtin&#39;, &#39;default&#39;, &#39;{create_dashboard,create_query,edit_dashboard,edit_query,view_query,view_source,execute_query,list_users,schedule_query,list_dashboards,list_alerts,list_data_sources}&#39;,<br>            &#39;2024-04-21 23:25:13.827925+00&#39;);<br><br>INSERT INTO public.users (updated_at, created_at, id, org_id, name, email, password_hash, groups,<br>                          api_key, details)<br>    VALUES (now(), now(), 1, 1, &#39;_USER_NAME_&#39;, &#39;_EMAIL_&#39;, <br>    &#39;$6$rounds=656000$eU6sYb5n7K.K6hZ0$tNLgO3gqYkCJnjVvdGiW7TluHeWv/3fB5J29byOmnVU66LRYuEzAoXmh/2LSRDReXdfzSg1t7pFncP03os49r0&#39;, <br>    -- password: test123<br>    &#39;{1,2}&#39;, &#39;uwgC6V8ipibQbru2Y02R4bnjqjeOLwkcQc1pSECs&#39;, format(&#39;{&quot;active_at&quot;: &quot;%s&quot;}&#39;, now())::json);</pre><p>Customize _ORGANIZATION_, _USER_NAME_, and _EMAIL_ with your preferred configurations. This setup ensures that your first user or admin is created automatically. The default password is set to test123, but you can change it by hashing your preferred password using the following method from Redash documentation:</p><pre># Generate hashed password<br>from passlib.apps import custom_app_context as pwd_context<br>pwd_context.hash(&quot;your_password&quot;)</pre><h3>Conclusion</h3><p>By automating these tasks, you can significantly reduce the manual overhead and streamline your Redash development process. This allows us to focus on building your Redash LLM Chatbot without the hassle of repetitive setup tasks.</p><h3>Limitations</h3><p>While this automation simplifies the setup process, it assumes a static configuration that might need adjustments for different environments or more complex setups. Additionally, the script does not handle errors or edge cases, so further enhancements may be required to ensure robustness and flexibility.</p><p>For more insights and code, visit my GitHub <a href="https://github.com/dev-abuke">here</a>. <br>Connect with me on LinkedIn <a href="https://www.linkedin.com/in/abubeker-shamil/">here</a>.</p><p>If you find my posts insightful drop a 👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bb0f8f90c81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualization for Everyone: Redash Chatbot for Advanced Data Analytics, Visualization, and Insight…]]></title>
            <link>https://medium.com/@abubekershamil/visualization-for-everyone-redash-chatbot-for-advanced-data-analytics-visualization-and-insight-7fb5657dc885?source=rss-dec8d7adb524------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fb5657dc885</guid>
            <dc:creator><![CDATA[Abubeker]]></dc:creator>
            <pubDate>Sat, 11 May 2024 20:33:37 GMT</pubDate>
            <atom:updated>2024-05-15T16:48:09.787Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Visualization for Everyone: Redash Chatbot for Advanced Data Analytics, Visualization, and Insight Extraction</strong></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoCy6BEjwJAU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoCy6BEjwJAU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoCy6BEjwJAU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bca97e18900ad50085de63dd2c25be51/href">https://medium.com/media/bca97e18900ad50085de63dd2c25be51/href</a></iframe><h3>Introduction</h3><blockquote><strong>Democratizing visualization for non-technical individuals</strong></blockquote><p>In today’s data-driven landscape, the ability to quickly access and interpret data is paramount for maintaining a competitive edge. However, the complexity of traditional data analytics tools can be a significant barrier for non-technical team members. Our organization faces challenges in enabling team members to perform ad-hoc data analysis without extensive SQL knowledge, which slows down decision-making processes.</p><h3>Vision and Objectives</h3><p>Our project’s primary vision is to bridge the gap between complex data queries and intuitive user interfaces. Traditional data analytics often require a deep understanding of SQL and data visualization tools, which can be a barrier for non-technical users. By integrating natural language processing (NLP) capabilities into Redash, we aim to democratize data analytics, making it accessible to everyone in the organization regardless of their technical proficiency.</p><p>The core objective is to enable users to interact with their data using everyday language. This means that instead of writing complex SQL queries, users can simply ask questions in plain English and receive actionable insights. For instance, a user could ask, “What were our total sales last quarter?” and the system would interpret this query, generate the necessary SQL command, and provide the relevant data.</p><p>This approach not only makes data analysis more accessible but also speeds up the decision-making process. Users no longer need to rely on technical teams to generate reports; they can quickly obtain the information they need, leading to more timely and informed business decisions. Additionally, this project aims to enhance the overall efficiency of data analysis workflows, promoting a culture of data-driven decision-making across the organization.</p><p>By making data exploration more intuitive and user-friendly, we anticipate significant improvements in productivity and engagement. The integration of NLP with Redash will empower all team members to leverage data insights, ultimately driving better business outcomes and fostering innovation.</p><blockquote><strong>Proposed Solution Overview</strong></blockquote><p>To address this, we will be developing a Redash chat add-on that allows users to interact with our <a href="https://github.com/getredash/redash/"><em>open-source</em></a><em> </em>business intelligence (BI) platform called Redash through natural language queries. This tool will enable team members to ask questions directly and receive insights without needing to understand the underlying data structure or query language.</p><blockquote><strong>Solution Impact</strong></blockquote><p>The implementation of this chat add-on is expected to democratize data analytics in our organization, making it faster and easier for all team members to access the information they need. By reducing the time to insight, we aim to enhance our overall responsiveness to market changes and improve the strategic decision-making capabilities. Additionally, this project will serve as a stepping-stone towards integrating more advanced AI-driven analytics across our various data systems.</p><h3>Why Redash?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fFBvnfYDeD2gMD4W22guA.png" /></figure><p>In the vast landscape of business intelligence (BI) tools, choosing the right platform can significantly impact how effectively an organization can visualize and analyze its data. Our company required a BI tool that could not only handle complex data from multiple sources but also integrate new technologies to enhance accessibility and usability for all team members.</p><p><strong>Redash’s</strong> browser-based interface allows easy access and sharing of visualizations, making collaboration straightforward. Users can quickly generate insightful visualizations from various data sources, thanks to its intuitive query editor and a wide range of visualization options.</p><p>Redash also supports scheduled refreshes, ensuring that data remains current, and allows setting up alerts for real-time monitoring of key metrics. Its REST API further extends its functionality, enabling integration with other tools and custom workflows. By leveraging Redash’s capabilities, our project aims to integrate natural language processing (NLP) features to make data analysis even more accessible and intuitive.</p><h4>Why Not Other BI Tools?</h4><p>Many BI tools offer robust data processing and visualization capabilities, but they often require considerable technical know-how to operate effectively. This creates a barrier for non-technical team members who could benefit from direct access to data insights. Additionally, our need to integrate advanced natural language processing (NLP) features posed a unique challenge that not all BI tools could easily accommodate without substantial customization.</p><h4>Redash to The Rescue</h4><p>Redash stands out as the optimal solution for several compelling reasons:</p><ul><li><strong>Open Source and Customizable</strong> Redash is open-source, allowing us to customize the tool according to our specific needs. This flexibility is crucial for integrating the NLP capabilities required for our chat add-on.</li><li><strong>User-Friendly Interface</strong> Redash provides a user-friendly interface that simplifies the creation and sharing of dashboards. This makes it accessible to all team members, regardless of their technical skills.</li><li><strong>Real-Time Query Execution</strong> It supports real-time query execution, which is essential for generating immediate insights from live data, enhancing decision-making processes.</li><li><strong>Wide Range of Integrations</strong> Redash supports integrations with various <a href="https://redash.io/integrations/">data sources</a> and databases, which is vital for our diverse data environment.</li><li><strong>Community and Support</strong> Being a widely used tool, Redash has a strong community and extensive documentation, which facilitates troubleshooting and enhances the tool’s reliability and performance over time.</li></ul><h3>Redash Rest API</h3><p>Integrating Redash with a React Client API opens new possibilities for automated dashboards and dynamic SQL query generation. At the core of this integration is the RedashAPIClient, which facilitates seamless communication between Redash and our application.</p><h4>Here’s how we can utilize this API</h4><p><strong>Creating the API Client Instance</strong></p><pre>from redashAPI import RedashAPIClient<br># Initialize API client<br>Redash = RedashAPIClient(API_KEY, REDASH_HOST)</pre><p><strong>Listing All Data Sources</strong></p><pre>res = Redash.get(&#39;data_sources&#39;)<br>print(res.json())</pre><p><strong>Retrieving a Specific Data Source</strong></p><pre>res = Redash.get(&#39;data_sources/1&#39;)<br>print(res.json())</pre><p><strong>Creating a New Data Source</strong></p><pre>Redash.post(&#39;data_sources&#39;, {<br>    &quot;name&quot;: &quot;New Data Source&quot;,<br>    &quot;type&quot;: &quot;pg&quot;,<br>    &quot;options&quot;: {<br>        &quot;dbname&quot;: DB_NAME,<br>        &quot;host&quot;: DB_HOST,<br>        &quot;user&quot;: DB_USER,<br>        &quot;passwd&quot;: DB_PASSWORD,<br>        &quot;port&quot;: DB_PORT<br>    }<br>})</pre><p><strong>Creating a Data Source Using Method</strong></p><pre>Redash.create_data_source(&quot;pg&quot;, &quot;First Data Source&quot;, {<br>    &quot;dbname&quot;: DB_NAME,<br>    &quot;host&quot;: DB_HOST,<br>    &quot;user&quot;: DB_USER,<br>    &quot;passwd&quot;: DB_PASSWORD,<br>    &quot;port&quot;: DB_PORT<br>})</pre><p><strong>Creating a Query</strong></p><pre>Redash.create_query(1, &quot;First Query&quot;, &quot;SELECT * FROM table_name;&quot;)</pre><p><strong>Refreshing a Query</strong></p><pre>Redash.refresh_query(1)</pre><p><strong>Generating Query Results</strong></p><pre>Redash.generate_query_results(1)</pre><p><strong>Creating a Visualization</strong></p><pre>Redash.create_visualization(1, &quot;line&quot;, &quot;Sales Over Time&quot;, x_axis=&quot;date&quot;, y_axis=[<br>    {&quot;type&quot;: &quot;line&quot;, &quot;name&quot;: &quot;sales&quot;, &quot;label&quot;: &quot;Sales&quot;}<br>])</pre><p><strong>Creating a Dashboard</strong></p><pre>Redash.create_dashboard(&quot;Sales Dashboard&quot;)</pre><p><strong>Adding a Widget to the Dashboard</strong></p><pre>Redash.add_widget(1, visualization_id=1, full_width=True)</pre><p><strong>Publishing a Dashboard</strong></p><pre>url = Redash.publish_dashboard(1)<br>print(f&quot;Dashboard published at: {url}&quot;)</pre><p>By leveraging these functionalities, we can automate data source management, query execution, and dashboard creation, making data visualization workflows more efficient and responsive. This integration not only enhances the user experience but also empowers users to interact dynamically with their data.</p><h3>Approaches on Data Analytics</h3><p>Data analytics is essential for interpreting and leveraging business data. It involves multiple approaches to convert raw data into actionable insights.</p><p><strong>Exploratory Analysis </strong>provides a snapshot of past performance, revealing patterns and trends through visualizations and reports. For example, analyzing sales data over the last quarter helps businesses understand their performance.</p><p><strong>Causal Analysis </strong>digs deeper to uncover the reasons behind observed trends. By investigating underlying factors, such as market dynamics or customer preferences, it explains why certain outcomes occurred.</p><p><strong>Forecasting </strong>looks ahead, using historical data to predict future trends. Advanced algorithms and statistical models help anticipate future events, like predicting next quarter’s sales or identifying potential market shifts.</p><p><strong>Optimization </strong>goes a step further by recommending actions to improve outcomes. It uses complex models to suggest the best strategies for enhancing business performance, such as optimizing inventory levels or refining marketing tactics.</p><p>By leveraging these approaches, businesses can gain a comprehensive understanding of their operations and make informed decisions. Initially, our project will focus on enhancing exploratory analysis using large language models (LLMs), setting the stage for more advanced forecasting and optimization in the future.</p><h3>Overview of YouTube Data</h3><blockquote>Unlocking Viewer Insights with YouTube Data</blockquote><p>For content creators and marketers of our organization using YouTube, data isn’t just numbers — it’s the story of your audience. Here’s how some the data is structured.</p><h3>Extracting the Zipped Files</h3><p>Using file extraction software or programming tools, the zipped files were then opened. In a more automated or programming-focused approach, tools like Python’s zipfile library can be used to extract all contents programmatically. Here’s a brief outline of how this can be done in Python:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAv6iUHqzqxK9F7sKvSzqA.png" /></figure><p>This script sets up a directory for the extracted files and then extracts them, preserving the directory structure contained within the zip file.</p><p>The zipped data provided contains various datasets, each with specific types of YouTube analytics data. These datasets are structured into separate zipped files, each representing a unique aspect of viewer interaction and behavior on YouTube. Here’s a summary of the types of data included based on the filenames and our previous exploration:</p><ol><li>Viewer Age: This dataset includes details about the age distribution of viewers, which can help in understanding which age groups are mostly engaged with the content. Analyzing this data helps in tailoring content and marketing strategies to specific age demographics.</li><li>Viewership by Date: This data tracks the daily viewership metrics, providing insights into how viewership varies over time. It’s useful for identifying trends, such as peak viewing times, and can influence decisions on when to release new content or run promotional campaigns.</li><li>Device Type: Knowing which devices viewers are using to watch content can help optimize video formats and quality settings for popular devices, ensuring the best possible user experience.</li><li>Traffic Source: Understanding where viewers are coming from — whether from direct links, search engines, or social media — can assist in optimizing marketing strategies and understanding how viewers discover content.</li><li>Subscription Source: This dataset likely details how viewers subscribe to your channel, which can be crucial for optimizing how you encourage subscriptions throughout your content and across various platforms.</li><li>Content Type: Insights into what types of content (e.g., tutorials, entertainment, informational) perform best can guide content creation strategies.</li><li>Operating System: Similar to device type, knowing which operating systems viewers are using can help tailor content and viewer experiences, especially when considering app development or optimizations.</li><li>Geographic Data (Cities, Geography): Geographic data allows for localization of content and marketing efforts. Knowing where viewers are geographically can help create more relevant content and targeted advertisements.</li><li>Viewer Gender: Gender distribution data can assist in understanding who your audience is more comprehensively, allowing for gender-targeted marketing and content customization.</li><li>New and Returning Viewers: This metric is crucial for gauging viewer loyalty and retention strategies. Understanding the balance between new and returning viewers can help in crafting strategies to increase viewer retention.</li><li>Subtitles and CC: Insights into how often subtitles and closed captions are used can inform decisions on accessibility and may highlight the need for investing in better quality translations or more language options.</li><li>Other Metrics (Sharing Service, Subscription Status, etc.): Additional datasets like these can provide deeper insights into how viewers interact with your content, including how often they share it and their subscription behaviors.</li></ol><h4>Diving into the Data: What We’ve Learned</h4><p><strong>City Slickers</strong> — Geographical Gems Imagine knowing exactly which cities love your content the most or which ones could use a little more love. That’s what our “Cities” data offers. From <strong>Addis Ababa</strong> to <strong>Manchester</strong>, we track views, watch time, and engagement levels across the globe.</p><p><strong>Applications</strong> — Tailor video content to regional preferences or run city-specific promotions. It’s all about making each viewer feel like your video was made just for them.</p><p><strong>Viewer Age</strong> — Demographic Dives Our “Viewer Age” data breaks down who’s watching, from teens to the more seasoned viewers. Understanding the age demographics that interact most with your content can transform how you approach your next video.</p><p><strong>Applications — </strong>Create content that caters to the specific interests and viewing habits of these age groups. Maybe it’s more animated explainer videos for younger viewers or deeper dive documentaries for an older audience.</p><p><strong>Viewership by Date — </strong>Viewership Trends Over Time “Viewership by Date” data is like having a time machine. It shows when your viewers tune in the most, helping you pinpoint the best times to release new content or push advertisements.</p><p><strong>Applications — </strong>Planning a big video release? Check when your viewers are most active and schedule it for maximum impact. Or use this data to understand the best times for live streams.</p><h4>Bringing Data to Life with Redash</h4><p>All this data is good, but making it work for you is where Redash comes in. By integrating these insights into Redash dashboards, we’re not just looking at data; we’re interacting with it. Our chat add-on goes even further as we will be addressing it in a few minutes, letting anyone on the team — tech-savvy or not — ask the LLM questions and get answers right from the data.</p><h3>Recommendations for Data Utilization</h3><ol><li><strong>Interactive Dashboards — </strong>Develop dashboards for each data set that allow users to explore trends and drill down into specifics, such as particular cities or age groups.</li><li><strong>Natural Language Querying</strong> — Enhance the Redash chat add-on to handle queries specific to these data sets, enabling questions like “What was the viewership on holidays?” or “Show me the viewer distribution in major cities.”</li><li><strong>Data-Driven Decisions </strong>— Utilize these insights to inform content creation, scheduling, marketing, and promotional strategies, ensuring they are backed by concrete viewer data.</li></ol><h3>Project Structure: How We Aim for Implementation</h3><p>The development of our Redash add-on follows a structured plan, divided into four key phases to ensure thorough implementation and integration of advanced capabilities.</p><p><strong>Tools Availability: OpenAi and Langchain</strong></p><p>Establishing a strong foundation is critical. Initially, we will utilize Python, OpenAI API, and LangChain to develop basic natural language processing (NLP) capabilities. Familiarizing ourselves with these tools is essential for accurate SQL translations. We will also review relevant documentation and summarize findings to ensure comprehensive understanding. As we progress, LangChain will be embedded into the Python backend to enhance NLP functionalities.</p><p><strong>LLamaIndex: Data management</strong></p><p>Optimizing data management is the next step. We will implement LLamaIndex to streamline data access and integrate multiple data sources. Utilizing vector databases, we will store and search transcribed text, comments, and metadata, improving data retrieval efficiency. Semantic search capabilities will be incorporated using vector similarity techniques, enabling more accurate and relevant search results.</p><p><strong>Redash: Dashboard and Backend Development</strong></p><p>Understanding Redash’s capabilities from its source code is crucial for seamless integration of out chatbot. We will design a user-friendly dashboard for our YouTube data, focusing on data visualization and analytics. Developing a robust backend system with Quart (an async version of Flask) will facilitate efficient data storage and processing. The architecture for the Redash add-on will be outlined, ensuring compatibility and smooth operation.</p><p><strong>LLM and Programmatic Dashboard Generation</strong></p><p>Integrating language models for natural language understanding is the final phase. We will incorporate OpenAI’s language models to interpret user queries and automate visualization generation. This involves converting natural language queries into SQL, ensuring compatibility with Redash. Rapid testing and improvement will be facilitated by tools like Flowise AI. Automatic generation of visualizations based on user queries and existing context will enhance the overall user experience.</p><h3>LLMs in Redash</h3><p>Large Language Models (LLMs) like OpenAI’s GPT come into play. Integrated within Redash, these models are not just tools; they are game changers in how we interact with data.</p><h4>Enhancing Redash with LLM Capabilities</h4><p>Redash, our go-to business intelligence tool, is already a powerhouse for data visualization and analysis. By infusing LLM capabilities, we’ve taken its functionality to new heights. Here’s how:</p><ol><li><strong>Natural Language Processing</strong> for Easy Queries Forget complex SQL queries; ask plain English questions. Whether it’s “What were the top-performing videos in June?” or “Compare viewer engagement between Q1 and Q2,” the LLM handles it all. This accessibility means that every team member, regardless of their technical skill level, can make data-driven decisions quickly and independently.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q3KFqIj0dE4WOwbWKg-n5w.png" /></figure><p>2. <strong>Advanced Analytics</strong> On-the-Fly LLMs not only understand your questions but also provide deep analytics instantaneously. They can summarize data trends, predict future patterns, and even suggest actionable steps. This level of analysis, which once took hours of manual labor, is now just a conversation away.</p><p>3. <strong>Continuous Learning and Adaptation</strong> One of the most exciting aspects of LLMs is their ability to learn and adapt. As they are exposed to more data and queries, their accuracy and helpfulness improve, making them an ever-more valuable asset in our BI toolkit.</p><blockquote><strong>Ready to talk to your data? Let’s make data queries as easy as asking a question at a meeting.</strong></blockquote><h3>Implementing an AI-Driven Chatbot in Redash</h3><p>We embarked on integrating a cutting-edge AI chatbot powered by OpenAI’s large language models. This blog post delves into the tools we used, the modifications we made, and the challenges we navigated through.</p><h4>Tools and Technologies</h4><p>Leveraging Redash’s open-source platform, we employed Python for scripting, with the OpenAI Python package and SQLAlchemy playing pivotal roles. These tools were instrumental in integrating AI capabilities and managing database operations efficiently.</p><p>Backend Enhancements Our first task was to create a seamless connection between the frontend chatbot and the backend. By introducing a POST method in the backend, we established a robust link that allowed the frontend to communicate user queries effectively. Further enhancing the chatbot, we integrated OpenAI’s LLM, enabling it to understand and generate SQL queries through sophisticated prompt engineering.</p><h4>Challenges in Development</h4><p>One of the most daunting challenges was the prolonged build times of Redash, which significantly slowed our testing and development phases. Recognizing the need for efficiency, we are exploring methods like incremental builds and mock testing to streamline our development process for future enhancements.</p><h4>Constructing the Chatbot: A Dual-Front Approach</h4><p><strong>Frontend Innovation — </strong>Leveraging the robust Redash source code, we embarked on crafting a dynamic and responsive frontend using React.js. This allowed us to create components that not only respond to user interactions but also adapt to varying data demands seamlessly. To add a layer of sophistication and aesthetic appeal, we employed Less CSS, enhancing the overall styling and user interface.</p><p><strong>Backend Robustness — </strong>Parallel to the frontend, the backend was architected using the Flask framework, renowned for its versatility and reliability. This choice laid a solid foundation for handling the complexities of chatbot functionality, ensuring that every operation from data fetching to processing is executed seamlessly. The integration of Axios, a potent HTTP client, was crucial in enabling efficient communication and data exchanges between the frontend and backend, thus ensuring that user queries were handled promptly and accurately.</p><p>Certainly! Here’s a draft section that explains the methodology used in setting up and running Redash on an Ubuntu VM, utilizing Render for hosting services for better collaboration, and automating the setup processes:</p><h3>Methodology: Streamlining Redash Deployment and Data Management</h3><p>We adopted a comprehensive and systematic approach to set up and manage our data analytics environment. Here’s how we effectively implemented our system on an Ubuntu virtual machine (VM), utilized Render for hosting, and automated our processes to enhance efficiency and collaboration.</p><h4>Running Redash on Ubuntu VM</h4><p>To ensure a stable and controlled development environment, we chose to run Redash on an Ubuntu VM. Ubuntu offers a robust, secure, and user-friendly platform which is ideal for managing the dependencies and intricacies of Redash. The VM environment allowed us to encapsulate our development environment, making it easily replicable and isolating it from individual system variations. This setup ensured that all team members had a consistent development experience and could test changes in a controlled environment, leading to fewer discrepancies and issues.</p><h4>Utilizing Render for Enhanced Collaboration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozLntcB2C8GDWX5uxc-Abg.png" /></figure><p>Recognizing the need for seamless collaboration and continuous integration, we utilized <a href="https://dashboard.render.com/">Render</a>, a cloud hosting service known for its simplicity and scalability. Render enabled us to host our Redash instance and associated databases in the cloud, allowing team members to access and interact with the latest version of our project without the need for complex local setups. This was particularly beneficial for non-technical team members who needed to access Redash dashboards and data insights. Render’s deployment features also allowed us to scale our resources as needed, ensuring that performance remained optimal as our data volume and user base grew.</p><h4><strong>Setting Up GitHub Organization: </strong><a href="https://github.com/10Accademy-InsightStreamInc/Redash-LLM-Chatbot-Add-on"><strong>Organization Link</strong></a></h4><p>We also began by setting up a GitHub organization for version control and team collaboration. This allowed us to manage our codebase efficiently and track changes seamlessly.</p><h4>Dev Environment</h4><p>Embarking on Redash development, we established a local environment by installing essential packages such as Docker, NodeJS, and Yarn. We cloned the Redash source code, installed dependencies, and configured local environment variables. This enabled us to compile the frontend and build a local Redash Docker image, which facilitated easy testing and configuration.</p><h4>Chat Bot Frontend</h4><p>To integrate the chatbot with Redash, we developed the frontend using React.js and Less CSS, while the backend was built on Flask. We incorporated OpenAI’s GPT-3.5 Turbo to enable dynamic SQL query generation and utilized Axios for efficient communication between the frontend and backend.</p><p>This comprehensive methodology ensured a seamless development process, fostering collaboration and efficiency while integrating advanced NLP capabilities into Redash.</p><h4>Prompting for SQL Generation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eL7BkJ7gzF-6uYrLxIuRdQ.png" /><figcaption>Giving Context for LLM based on the Tables and Columns of Youtube Data</figcaption></figure><p>Incorporating natural language processing (NLP) for SQL generation enables users to interact with databases through simple language prompts. Effective prompting is crucial for generating accurate SQL queries.</p><p><strong>Designing Effective Prompts</strong></p><ol><li><strong>Specificity</strong> Be specific in your query. Instead of “Get subscriber data,” use “Show total subscribers in January 2024.”</li><li><strong>Context</strong> Provide necessary context. For example, “What were the total download in the last year for top performing X in region Y?” gives the system clear parameters.</li><li><strong>Simplicity</strong> Use straightforward language. Avoid jargon or complex sentences. For instance, “List all subscribers who viewed on Linux on April 1, 2024.”</li><li><strong>Iterative Refinement</strong> Refine prompts based on initial responses. If “What were the views?” is too broad, narrow it down to “What were the total views of X last month?”</li></ol><p><strong>Example Prompts</strong></p><ul><li>“Retrieve the top five Operating Systems.”</li><li>“Display the monthly views by city.”</li><li>“How many new subscribers were acquired in May 2024?”</li></ul><p>By guiding users to frame their prompts effectively, we ensure the NLP system generates precise and relevant SQL queries, enhancing data retrieval and analysis.</p><h4>Automating the Build and Deployment Process</h4><p>To streamline the setup and update processes, we wrote scripts to automate the building of Redash and the configuration of our databases. These scripts handled everything from installing dependencies to configuring database schemas and importing initial data sets. By automating these tasks, we significantly reduced the manual overhead and potential human errors associated with setting up and updating our environment. Automation ensured that any team member could deploy a fresh instance of Redash or update an existing setup with minimal effort, leading to a more agile and flexible development cycle.</p><p>Here’s a brief outline of what our automation scripts accomplished:</p><ul><li><strong>Automated Redash Setup</strong> The script installed Redash and all its dependencies on the Ubuntu VM, configured necessary environment variables, and set up initial user accounts.</li><li><strong>Database Configuration and Deployment </strong>Another script automatically set up the database schemas based on our predefined structure, handled migrations, and loaded initial datasets into the system. This ensured that our data was structured and accessible right from the start.</li><li><strong>Continuous Integration and Deployment</strong> Integration with our version control system allowed these scripts to run whenever changes were made, ensuring that our hosting environment on Render was always up-to-date with the latest changes.</li></ul><h4>Future Directions: Towards Predictive Analytics</h4><p>As we look to the future, our vision for the chatbot extends beyond just analytical capabilities. We plan to evolve the system into a more predictive tool, integrating machine learning models to forecast trends and suggest actions based on historical data. This shift will not only enhance the chatbot’s utility but also transform it into a proactive participant in data-driven decision-making.</p><p><strong>Predictive Capabilities </strong>By incorporating a machine learning model, the chatbot will not just respond to queries but anticipate user needs, offering insights and recommendations before they are even requested. This proactive approach aims to redefine how data is interacted with, making it not just responsive but also anticipatory.</p><h4>Lessons Learned and Path Forward</h4><p>This project has been a profound learning experience, underscoring the importance of adaptability and meticulous planning. Collaborative problem-solving emerged as a key theme, with every challenge presenting an opportunity to innovate. As we continue to refine our integration, our focus remains on enhancing the chatbot’s capabilities, ensuring it remains a cutting-edge tool in the ever-evolving landscape of data analytics.</p><h3>Limitations, Future Directions, and Final Words</h3><h4>Acknowledging Limitations</h4><p>While our project has yielded significant benefits, it is important to recognize its limitations. Running Redash on an Ubuntu VM, although beneficial for consistency and control, may present scalability challenges as user demand increases. Furthermore, while Render facilitates easy access and collaboration, reliance on cloud services means we must be vigilant about service outages and connectivity issues. Lastly, while automation has streamlined many processes, it introduces a layer of complexity in troubleshooting and requires rigorous testing to ensure reliability.</p><h4>Envisioning the Future</h4><p>Looking ahead, we are excited about the potential enhancements to our Redash integration:</p><ul><li><strong>Advanced Predictive Analytics</strong> Incorporating more sophisticated machine learning models to predict user behaviors and preferences, allowing for even more targeted data insights.</li><li><strong>Enhanced Automation Features</strong> Expanding our automation scripts to include more intelligent error handling and recovery processes, making our systems even more robust and less prone to downtime.</li><li><strong>Greater Integration with Additional Data Sources</strong> Expanding the capability to seamlessly integrate more diverse data sources into Redash, providing a richer, more comprehensive data analysis experience.</li></ul><h4>Additional Features on the Horizon</h4><p>We are also exploring the introduction of new features that will further enhance the utility and user-friendliness of our system</p><ul><li><strong>Interactive AI Features </strong>Further developing the chatbot’s capabilities to include interactive AI features that engage users in more meaningful ways, potentially transforming passive data consumption into an interactive dialogue.</li></ul><h4>Final Word</h4><p>As we reflect on the journey of integrating an AI-driven chatbot into Redash, it is clear that this is just the beginning. Each challenge we faced and every limitation we recognized has paved the way for future improvements. Our commitment to evolving and enhancing our tools ensures that we will continue to provide our users with the best possible data analysis experience.</p><h4>Conclusion</h4><p>In conclusion, this project not only transformed our analytical capabilities but also taught us invaluable lessons about innovation, collaboration, and the endless possibilities of technology. As we move forward, we remain excited about the future of data analytics and are committed to staying at the forefront of technological advancements. We welcome our users and stakeholders to join us on this continuing journey, as we explore new ways to make data not just informative, but truly transformative.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fb5657dc885" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>