<?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 Elias Assamnew on Medium]]></title>
        <description><![CDATA[Stories by Elias Assamnew on Medium]]></description>
        <link>https://medium.com/@elias.assamnew?source=rss-bd07403bb0c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*r5fg0DAvAAamd9Oc</url>
            <title>Stories by Elias Assamnew on Medium</title>
            <link>https://medium.com/@elias.assamnew?source=rss-bd07403bb0c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:01:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elias.assamnew/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[Contract Advisor RAG: Towards Building]]></title>
            <link>https://medium.com/@elias.assamnew/contract-advisor-rag-towards-building-642389ab74cb?source=rss-bd07403bb0c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/642389ab74cb</guid>
            <dc:creator><![CDATA[Elias Assamnew]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 19:56:13 GMT</pubDate>
            <atom:updated>2024-06-10T08:24:10.445Z</atom:updated>
            <content:encoded><![CDATA[<h3>Contract Advisor RAG</h3><h4>Towards Building A High-Precision Legal Expert LLM APP</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YW5tkBe7_afOdmbG.jpg" /><figcaption>source <a href="https://stablediffusionweb.com/app/image-generator?prompt=Your+AI+Contract+Assistant&amp;ratio=1%3A1&amp;style=cinematic-default">stable diffusion</a></figcaption></figure><p>GitHub link to the project:</p><p><a href="https://github.com/gelifatsy/LegalAI-RAG-Contract-Advisor/tree/all_experiments">GitHub - gelifatsy/LegalAI-RAG-Contract-Advisor at all_experiments</a></p><h3>Introduction</h3><p>Harnessing the power of artificial intelligence, Lizzy AI seeks to revolutionize the legal landscape with a first-of-its-kind “contract lawyer” application. This project focuses on building the initial foundation — a Retrieval Augmented Generation (RAG) system for Contract Q&amp;A. Unlike traditional chatbots, this system empowers users to seamlessly interact with contracts through natural language questions, receiving accurate and context-rich answers drawn from the contract itself.</p><h3>Business Objective</h3><p>Lizzy AI’s ultimate goal is to develop a fully autonomous contract bot capable of handling the entire contract life cycle, from drafting and reviewing to negotiation. This initial RAG system serves as a crucial stepping stone, fostering legal expertise and laying the groundwork for future automation. By successfully creating a high-precision RAG system, Lizzy AI aims to:</p><ul><li>Increase accessibility to legal expertise:Empower individuals and businesses<br>with a user-friendly tool to understand and navigate contracts more efficiently.</li><li>Reduce legal costs: Provide a cost-effective alternative to traditional legal services, particularly for simpler contracts and common inquiries.</li><li>Improve legal process efficiency:Streamline contract workflows by automating repetitive tasks, allowing legal professionals to focus on complex matters.</li><li>Advance AI legal solutions:Contribute to the development of future<br>generations of automated legal tools, shaping the future of the legal industry.</li></ul><h4>What is RAG</h4><p>Although Large Language Models (LLMs) are powerful and capable of generating creative content, they can produce outdated or incorrect information as they are trained on static data. To overcome this limitation, Retrieval Augmented Generation (RAG) systems can be used to connect the LLM to external data and obtain more reliable answers. RAG is a method that boosts the precision and dependability of generative AI models by incorporating factual information retrieved from external sources.</p><h4><strong>RAG and Beyond: Unpacking the Technical Foundations of Advanced Language Models</strong></h4><p><strong>Chunking</strong></p><p>Before feeding a document into the RAG model, it’s essential to break it down into smaller, manageable chunks. This process, known as chunking, enables the model to focus on specific parts of the document and extract relevant information more efficiently. By dividing the document into smaller chunks, we can create a more granular representation of the text, making it easier to process and analyze.</p><p><strong>Vector Database</strong></p><p>Once the document is chunked, we can embed each chunk into a vector database. This database stores dense vector representations of the text data, allowing for fast similarity searches and efficient retrieval of relevant information. The vector database acts as a knowledge repository, providing the RAG model with a rich source of information to draw upon when generating responses.</p><p><strong>Retrieval</strong></p><p>During the RAG process, the model retrieves relevant information from the vector database, using the input prompt as a query. The retrieval component is responsible for searching the database and retrieving the most relevant chunks of text, which are then used to generate a response. Efficient retrieval is critical to the RAG process, as it enables the model to access the information it needs to generate accurate and informative responses.</p><p><strong>Prompt Engineering</strong></p><p>The prompt is the input text or query that triggers a response from the RAG model. The prompt provides the model with the context and information it needs to generate a response, and its quality and relevance can significantly impact the accuracy and informativeness of the response.</p><p><strong>RAG Evaluation</strong></p><p>Evaluating the performance and quality of RAG models is a critical step in their development and deployment. RAG evaluation involves assessing the model’s ability to generate accurate and informative responses, as well as its efficiency and scalability. Evaluation metrics include accuracy, fluency, relevance, and coherence, providing a comprehensive understanding of the model’s strengths and weaknesses.</p><p><strong>RAGAS</strong></p><p>Ragas is a framework that helps you evaluate your Retrieval Augmented Generation (RAG) pipelines. RAG denotes a class of LLM applications that use external data to augment the LLM’s context. There are existing tools and frameworks that help you build these pipelines but evaluating it and quantifying your pipeline performance can be hard. This is where Ragas (RAG Assessment) comes in.</p><p><strong>Langchain</strong></p><p>Langchain is a framework for building and evaluating language models that incorporates RAG and other techniques. This framework enables the creation of large-scale language models that can handle complex tasks and datasets, providing a comprehensive platform for building and deploying advanced language models. By leveraging the strengths of RAG and other techniques, Langchain has the potential to revolutionize the field of natural language processing.</p><h3>Project Implementation</h3><p><strong>Chunking</strong><br>I experimented with three chunking approaches from Langchain’s library: Our goal was to split the input text into manageable chunks while preserving semantic relationships.</p><ul><li>CharacterTextSplitter: CharacterTextSplitter split the text into chunks using a fixed-size window. This approach preserved local context and semantics.</li><li>RecursiveCharacterTextSplitter: used to recursively split the text based on character-level granularity. This approach preserved sentence structure and semantics.</li><li>SemanticChunker: used semantic segmentation to identify meaningful chunks. This approach preserved context-dependent meanings and ambiguities.</li></ul><p>From the experiment RecursiveCharacterTextSplitter slightly work better on context recall and faithfulness.</p><pre>from langchain.text_splitter import RecursiveCharacterTextSplitter<br><br><br>def text_splitter(documents):<br>    text_splitter = RecursiveCharacterTextSplitter(<br>        separators = [&quot;\n\n&quot;, &quot;\n&quot;, &quot; &quot;, &quot;&quot;],    <br>        chunk_size = 1600,<br>        chunk_overlap= 200<br>    )<br>    chunks = text_splitter.split_documents(documents=documents)<br>    return chunks </pre><p><strong>Embedding</strong></p><p>For the embedding stage of our RAG model, I experimented with three different approaches: OpenAI’s embedding, Hugging Face’s embedding, and Google’s GoogleGenerativeAIEmbeddings. Our goal was to find an embedding approach that effectively captures the semantic meaning of the input text.</p><p>I chose OpenAI’s text-embedding-ada-002 as my final embedding approach, as it demonstrated better semantic embedding quality compared to the other approaches. This embedding approach uses a transformer-based model to generate dense vector representations of text data, which are then used to compute semantic similarities.</p><pre>import os<br>from langchain.embeddings.openai import OpenAIEmbeddings<br><br><br>from dotenv import load_dotenv, find_dotenv<br>_ = load_dotenv(find_dotenv()) # read local .env file<br>import openai<br>openai_api_key=openai.api_key = os.environ[&#39;OPENAI_API_KEY&#39;]<br><br>def select_embeddings_model(LLM_service=&quot;OpenAI&quot;):<br>    if LLM_service == &quot;OpenAI&quot;:<br>        openai_api_key = os.environ.get(&quot;OPENAI_API_KEY&quot;)<br>        embeddings = OpenAIEmbeddings(<br>            model=&#39;text-embedding-ada-002&#39;,<br>            api_key=openai_api_key<br>        )<br><br>    if LLM_service == &quot;Google&quot;:<br>        embeddings = GoogleGenerativeAIEmbeddings(<br>            model=&quot;models/embedding-001&quot;,<br>            google_api_key=google_api_key<br>        )<br>    if LLM_service == &quot;HuggingFace&quot;:<br>        embeddings = HuggingFaceInferenceAPIEmbeddings(    <br>            api_key=HF_key, <br>            model_name=&quot;thenlper/gte-large&quot;<br>        )<br>         <br>    return embeddings</pre><p><strong>Vector Database</strong></p><p>FAISS (Facebook AI Similarity Search) stands out among other vector databases due to its high-performance indexing and search capabilities tailored to large-scale vector data. Its efficiency lies in implementing advanced algorithms like Product Quantization and Locality-Sensitive Hashing (LSH), enabling rapid similarity searches even in high-dimensional spaces. While other specialized vector databases like Annoy and Milvus also target similar use cases, FAISS often outperforms them regarding scalability and search accuracy, especially in scenarios with massive datasets and high-dimensional feature spaces. <a href="https://www.projectpro.io/article/faiss-vector-database/1009#:~:text=Comparing%20FAISS%20with%20Other%20Vector%20Databases,-FAISS%20(Facebook%20AI&amp;text=While%20other%20specialized%20vector%20databases,and%20high%2Ddimensional%20feature%20spaces."><em>[1]</em></a></p><h4><strong>1. Applying simple RAG with vector database backed retriever</strong></h4><pre>def load_document(document_path):<br>    # Load a document from the specified path<br>    loader = Docx2txtLoader(document_path)<br>    documents = loader.load()<br>    return documents<br><br>def split_document(documents, chunk_size=700, chunk_overlap=50):<br>    # Split a document into text fragments<br>    text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)<br>    texts = text_splitter.split_documents(documents)<br>    return texts<br><br>def create_embeddings(texts):<br>    # Generate embeddings for the text fragments<br>    embeddings = OpenAIEmbeddings(model=&#39;text-embedding-ada-002&#39;)<br>    return embeddings<br><br>def create_vector_store(documents, embeddings):<br>    # Create a vector store using the documents and embeddings<br>    vector_store = FAISS.from_documents(documents, embeddings)<br>    return vector_store<br><br>def create_retriever(vector_store, k=3):<br>    # Create a retriever from the vector store with the specified k value<br>    retriever = vector_store.as_retriever(search_kwargs={&quot;k&quot;: k})<br>    return retriever<br><br>def create_qa_system(retriever):<br>    # Create a RetrievalQA system using the retriever and LLM<br>    qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type=&quot;question_answering&quot;, retriever=retriever)<br>    return qa<br><br>def main(document_path):<br>    documents = load_document(document_path)<br>    texts = split_document(documents, chunk_size=700, chunk_overlap=50)<br>    embeddings = create_embeddings(texts)<br>    vector_store = create_vector_store(documents, embeddings)<br>    retriever = create_retriever(vector_store, k=3)<br>    qa_system = create_qa_system(retriever)<br>    return qa_system<br><br>if __name__ == &quot;__main__&quot;:<br>    document_path = input(&quot;Enter the path to your document: &quot;)<br>    qa_system = main(document_path)</pre><p>Initialize question and answer chain:</p><pre>qa_system = main(&quot;path/to/your/document.docx&quot;)<br>query = &quot;WHO ARE THE PARTIES TO THE AGREEMENT AND WHAT ARE THEIR DEFINED NAMES?&quot;<br>answer = qa_system.run(query)<br>print(answer)</pre><p>Output:</p><pre>&#39; The parties to the agreement are Cloud Investments Ltd. and Mr. Jack Robinson. <br>Their defined names are &quot;Company&quot; and &quot;Advisor,&quot; respectively. &#39;</pre><p>A simple RAG pipeline has been successfully implemented, and now we can evaluate how well the performance is by assessing its ability to accurately retrieve relevant information from the document and generate coherent and informative responses to user queries.</p><p><strong>RAG Evaluation</strong><br>The evaluation is done using RAG Evaluation with various metrics, including <strong><em>context precision, context recall, faithfulness, and answer relevance</em></strong>. We have prepared an evaluation dataset consisting of a given question and ground truth pair extracted from the embedded documents, and we will evaluate the RAG pipeline using this dataset to measure its performance and identify areas for improvement. more about the evaluation metrics can be found <a href="https://docs.ragas.io/en/stable/concepts/metrics/index.html"><strong>here</strong></a><strong>.</strong></p><p>Data preparation for the evaluation:</p><p>Load the evaluation</p><pre>import json<br><br>json_file=&quot;/path/to/your/evaluation_data.docx&quot;  # Replace with your actual path<br><br>with open(json_file, &quot;r&quot;) as f:<br>    data = json.load(f)<br><br>questions = []  # List to store extracted questions<br>for item in data:<br>    if &quot;question&quot; in item:<br>        questions.append(item[&quot;question&quot;])</pre><p>My evaluation dataset in question and ground truth pair in JSON format</p><pre>questions, ground_truth = [], []<br><br>for item in data:<br>    if &quot;question&quot; in item:  # Check if &quot;question&quot; key exists<br>        questions.append(item[&quot;question&quot;])<br>    if &quot;answer&quot; in item:  # Check if &quot;answer&quot; key exists<br>        ground_truth.append(item[&quot;answer&quot;])<br><br>print(&quot;Questions:&quot;)<br>for question in questions:<br>    print(question)<br><br>print(&quot;\nGround Truth:&quot;)<br>for answer in ground_truth:<br>    print(answer)</pre><p>sample question and ground truth pair</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDCgTBUPY1VzGkSZaUJFKg.png" /></figure><p>Preparing answer from the LLM and context retrieved with our retriever in the RAG pipeline.</p><pre><br>answers = []  # Create an empty list to store answers for each question<br>for question in questions:<br>    # Preprocess question (e.g., lowercase, remove punctuation)<br>    processed_question = question.lower().strip()<br><br>    # Call retriever function with processed question and context (if needed)<br>    answer = qa.run(processed_question)  # Include context if necessary<br><br>    # Append answer to the answers list<br>    answers.append(answer)<br><br>answers  # This will print a list of answers for each question<br>context_lists = []<br><br>for question in questions:<br>    # Preprocess question (e.g., lowercase, remove punctuation)<br>    processed_question = question.lower().strip()<br><br>    # Call retriever function with processed question<br>    relevant_docs = retriever.get_relevant_documents(processed_question)<br><br>    # Create a new list for this question&#39;s context<br>    context_for_question = []<br><br>    # Extract and store only page_content (assuming Document has a page_content attribute)<br>    context_for_question.extend([doc.page_content for doc in relevant_docs])<br><br>    # Append the question&#39;s context list with only page_content to the main list<br>    context_lists.append(context_for_question)<br><br># Now context_lists contains lists of page_content strings for each question<br><br>context_lists<br>ground_truths_lists = [[item] for item in ground_truth]</pre><p>Preparing evaluation dataset to be use in our evalation with RAGAS and setting the metrics</p><pre>from datasets import Dataset<br>data = {<br>    &quot;question&quot;: questions, # list <br>    &quot;answer&quot;: answers, # list<br>    &quot;contexts&quot;: context_lists, # list list<br>    &quot;ground_truths&quot;: ground_truths_lists # list Lists<br>}<br><br># Convert dict to dataset<br>dataset = Dataset.from_dict(data)<br><br><br>from ragas import evaluate<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>    metrics=[<br>        context_precision,<br>        context_recall,<br>        faithfulness,<br>        answer_relevancy,<br>        <br>    ],<br>)<br><br>df = result.to_pandas()</pre><p>Sample result of our RAG evaluation with vector databased backed retriever</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pK7F8vt4n1B8RfwMC8gVlw.png" /></figure><p>the Average performance of the retriever with the four metrics</p><pre>Average:<br>context_precision    0.44<br>context_recall       0.78<br>faithfulness         0.86<br>answer_relevancy     0.96<br>Name: Average, dtype: float64</pre><p>As the result suggest there is much room for improvement and the RAG pipeline is not answering much of the questions from the evaluation dataset</p><p>Sample result of our RAG evaluation with vector data based backed retriever</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*fgp8pI_9Xlt6N6-dz8_TMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArAcWV2q79ieXjc-lTiabA.png" /></figure><p>Our RAG can’t answer some of the questions like the above one</p><h3>Optimizing Chunking and Retrieval in RAG Pipeline</h3><p>The RAG pipeline has shown great promise in generating coherent and informative text. However, there’s still room for improvement, particularly in the chunking and retrieval stages.</p><p>1. <strong>Better Chunking and Overlap Size</strong>: Experimenting with different chunking sizes and overlap strategies can significantly impact the quality of retrieved texts. Finding the optimal chunk size and overlap ratio can lead to more relevant and contextualized retrievals.</p><p>2. <strong>Keyword Search Method</strong>: Enhancing the retriever with keyword search capabilities can improve the accuracy of retrieved texts. This involves identifying key phrases and entities in the input prompt and using them to guide the retrieval process.</p><p>3. Query Optimization Tools: Leveraging query optimization tools can refine the retrieval process by rephrasing or expanding the input query. This can help retrieve more relevant texts and reduce noise in the results.</p><p>4. Context Optimization Tools: Incorporating context optimization tools can further improve the retrieval process by considering the surrounding context of the input prompt. This can help disambiguate queries and retrieve texts that better match the intended meaning.</p><p>By addressing these areas of improvement, the RAG pipeline can become even more effective in generating high-quality, contextually relevant text.</p><h4><strong>Implementing Chunking and Query Optimization in RAG Pipeline</strong></h4><p>To improve the performance of the RAG pipeline, we implemented <strong>two</strong> key optimizations: chunking size optimization and query optimization using the MultiQueryRetriever from the Langchain library.</p><ol><li>Optimized Chunking Size:<br>Through experimentation, we found that a chunk size of 700 and an overlap of 50 yielded the best results for our dataset and RAG pipeline. This optimized chunking strategy allows for more efficient processing of input texts while maintaining contextual relevance.</li></ol><p>This made the pipeline answer some of the question</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*fgp8pI_9Xlt6N6-dz8_TMQ.png" /></figure><h4>2. MultiQueryRetriever for Query Optimization:</h4><p>To enhance the retrieval process, I leveraged the MultiQueryRetriever from the Langchain library. This tool automates prompt tuning by generating multiple queries from different perspectives for a given user input query. By retrieving a set of relevant documents for each query and taking the unique union across all queries, we can obtain a larger set of potentially relevant documents. This approach mitigates the limitations of distance-based retrieval and provides a richer set of results. <a href="https://python.langchain.com/v0.2/docs/how_to/MultiQueryRetriever/#simple-usage">[2]</a></p><p>code implementation</p><pre>from langchain.retrievers.multi_query import MultiQueryRetriever<br>from langchain_openai import ChatOpenAI<br><br>llm = ChatOpenAI(temperature=0)<br>retriever_from_llm = MultiQueryRetriever.from_llm(<br>    retriever=compression_retriever, llm=llm<br>)<br><br>question = &quot;What is the termination notice?&quot;<br><br>unique_docs = retriever_from_llm.get_relevant_documents(query=question)<br>len(unique_docs)</pre><p>The output queries from this:</p><pre>INFO:langchain.retrievers.multi_query:Generated queries: <br>[&#39;1. Can you explain the process of issuing a termination notice?&#39;, <br>&#39;2. How is a termination notice typically handled in legal agreements?&#39;, <br>&#39;3. What are the key components of a termination notice and how is it delivered to the relevant parties?&#39;]</pre><p>The retriever then retrieves relevant document based on this generated query. This approach resulted the RAG evaluation significant improvement with RAGAS evaluation metrics as:</p><pre>Average:<br>context_precision    0.54<br>context_recall       0.78<br>faithfulness         0.96<br>answer_relevancy     0.74<br>Name: Average, dtype: float64</pre><h4>3. Context Compression and Reranking</h4><p>Re-ranking involves reordering nodes based on relevance to the query and choosing top n nodes. Since the number of nodes can reduce once the re-ranking is complete, we perform the following evaluations:</p><ul><li><a href="https://docs.uptrain.ai/predefined-evaluations/context-awareness/context-reranking">Context Reranking</a>: Checks if the order of re-ranked nodes is more relevant to the query than the original order.</li><li><a href="https://docs.uptrain.ai/predefined-evaluations/context-awareness/context-conciseness">Context Conciseness</a>: Examines whether the reduced number of nodes still provides all the required information. <a href="https://python.langchain.com/v0.2/docs/integrations/callbacks/uptrain/#3-context-compression-and-reranking">[4]</a></li></ul><p>The compression retriever work on top of the base retriever</p><p>the base retriever:</p><pre>retriever = FAISS.from_documents(split_texts, OpenAIEmbeddings()).as_retriever(<br>    search_kwargs={&quot;k&quot;: 5}<br>)<br><br>query = &quot;How much is the escrow amount?&quot;<br>docs = retriever.get_relevant_documents(query)<br>pretty_print_docs(docs)<br></pre><p>The output context:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTFftcCRSVxHnMKdii65-A.png" /></figure><p>the compression retriever:</p><pre>compressor = CohereRerank()<br>compression_retriever = ContextualCompressionRetriever(<br>    base_compressor=compressor, base_retriever=retriever<br>)<br><br>compressed_docs = compression_retriever.get_relevant_documents(<br>    &quot;How much is the escrow amount?&quot;<br>)<br>pretty_print_docs(compressed_docs)</pre><p>The resulted output after compression and reranking:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3488rlTjODRkOL1LdOo0g.png" /></figure><p>The Improvement is done with cohere reranker and llm chain Extractor and multiQuery and the resulting improvement on the RAG performance presented below</p><pre>                   Cohere_mean  llmExtaractor_mean  multipleQuery_Mean<br>context_precision     0.648148            0.583333            0.539493<br>context_recall        0.740741            0.722222            0.777778<br>faithfulness          0.857143            0.958333            0.958333<br>answer_relevancy      0.834971            0.733552            0.744699</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*pDtA4N-xLRWS-ZYf-w-enw.png" /></figure><h3>Th front End and backend implementation for the project</h3><p>The backend is implemented with FAST API and the front end is implemented by React with type script.</p><p>The homepage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WYVk4aUt7AnG8Sj2PWvmA.png" /></figure><p>The chat page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*34mItr-EjFfSRPqUNMr_Ug.png" /></figure><h3>Conclusion</h3><p>In this project, we implemented a Retrieval-Augmented Generation (RAG) pipeline, optimizing its key components to improve performance. We experimented with chunking approaches, selecting the RecursiveCharacterTextSplitter from Langchain’s library, which preserved sentence structure and semantics. We also chose OpenAI’s text-embedding-ada-002 for its effective semantic embedding.</p><p>We leveraged FAISS, a high-performance vector database, for efficient indexing and search. By integrating these optimized components, we established a robust RAG pipeline capable of accurately retrieving relevant information and generating coherent responses.</p><p>The implementation of the MultiQueryRetriever from Langchain’s library further enhanced our pipeline’s performance, mitigating limitations of distance-based retrieval. Through these optimizations, our RAG pipeline demonstrated significant improvements in context recall and faithfulness, leading to more accurate and informative responses.</p><p>This project showcases the potential for refinement in retrieval-augmented generation models, highlighting the importance of careful component selection and optimization in achieving high-performance results.</p><p><strong>Reference:<br>1. Langchain documentation </strong><a href="https://python.langchain.com/v0.2/docs/introduction/"><strong>link</strong></a><strong><br>2. RAGAS documentation </strong><a href="https://docs.ragas.io/en/stable/"><strong>link</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=642389ab74cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web3: Refund by Location: Smart Contract]]></title>
            <link>https://medium.com/@elias.assamnew/web3-refund-by-location-smart-contract-466f3c27e821?source=rss-bd07403bb0c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/466f3c27e821</guid>
            <dc:creator><![CDATA[Elias Assamnew]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 19:27:20 GMT</pubDate>
            <atom:updated>2024-06-08T10:16:51.724Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/848/0*DTT6_yWfR8OUGTW_.jpg" /><figcaption>Image from <a href="https://www.simplilearn.com/tutorials/blockchain-tutorial/what-is-smart-contract">link</a></figcaption></figure><h3>Business Background</h3><p>The logistics and delivery industry faces challenges like inefficient payments, lack of transparency, and driver motivation. GeoLogix Solutions tackles these issues with a state-of-the-art system built on blockchain technology and smart contracts.</p><p>The solution automates payments based on drivers’ adherence to designated zones using GPS data. A transparent and verifiable record of each delivery builds trust between drivers and GeoLogix. Additionally, a driver rating system incentivizes compliance through token rewards, while real-time data optimizes routes and ensures timely deliveries.</p><p>Overall, GeoLogix Solutions has the potential to revolutionize the industry by improving efficiency, transparency, and driver motivation. However, questions regarding scalability, security, legal compliance, and token adoption need to be addressed for wider implementation.</p><h3>Introduction</h3><h4>Blockchain</h4><blockquote>A blockchain is simply a “cryptographically secure transactional singleton machine with shared-state.”</blockquote><p>A blockchain is a system where transactions are secured through complex mathematical algorithms, making it extremely difficult to manipulate. It operates as a single unified entity for all transactions, ensuring a universal truth that is accessible to all participants. The data stored within this system is shared and transparent to all users involved.</p><p><strong>Ethereum blockchain</strong></p><p>The Ethereum blockchain is a transaction-based state machine where there are a series of inputs and, based on those inputs, will transition to a new state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*5VvL9FUHgduEETno" /></figure><p>Ethereum starts with a “genesis state,” like a blank slate, before any transactions occur. As transactions take place, this genesis state evolves into a final state, which reflects the current state of the Ethereum network at any given moment.</p><p>In Ethereum, transactions are grouped into blocks, which are then chained together. Valid transactions undergo a mining process where nodes compete to create and validate blocks by providing mathematical proofs. This process, known as <strong>proof of work</strong>, ensures the validity of each block added to the main blockchain.</p><p><strong>Ethereum Accounts and Payments</strong></p><p>Ethereum has two types of accounts:</p><ul><li>Externally owned accounts (EOAs) are controlled by private keys and are used for value transfers.</li><li>Contract accounts are controlled by contract code and can perform various actions based on incoming messages.</li></ul><p><strong>Gas and Payments</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*HHrDaSolZVVg_WV9" /></figure><p>On the Ethereum network, “gas” acts as a digital fuel, measuring the resources needed for processing transactions and storing data. Both the gas price and limit influence the transaction cost, ultimately rewarding miners with these gas fees. This fee system not only discourages network abuse but also acts as a security measure against malicious activities like endless loops.</p><p><strong>Ethereum Transaction Execution</strong></p><p>Executing an Ethereum transaction is like clearing a complex checkpoint. Before starting, your transaction needs a valid format, signature, and sufficient gas (fuel) to run. Then, the network tracks key details while processing the transaction’s steps. Unused gas gets refunded, miners get paid, and the network updates according to the transaction’s impact. Imagine this happening millions of times per day, all meticulously managed for a secure and efficient blockchain!</p><p><strong>Ethereum Virtual Machine (EVM)</strong></p><p>The Ethereum Virtual Machine (EVM) acts as the brain of Ethereum, executing code (bytecode) created in languages like Solidity. It’s powerful but limited by “gas” (like fuel) for computations. Think of it like a special computer with:</p><ul><li><strong>Stack:</strong> Holds temporary data (max 1024 items).</li><li><strong>Memory:</strong> Temporary storage, wiped clean after each use.</li><li><strong>Storage:</strong> Permanent data saved as part of the system state.</li><li><strong>Code:</strong> Instructions stored separately and accessed specially.</li></ul><p>The EVM carefully manages gas, tracks execution steps, and updates the system state based on the code’s outcome. While understanding all the details might not be crucial for everyone, it’s essential for deep-level Ethereum development.</p><p><strong>Smart Contract Security</strong></p><p>Smart contracts, the self-executing code on blockchains, hold immense potential but also face unique security challenges. Their immutability and public nature mean errors are unforgiving, demanding meticulous attention to security.</p><p>This text delves deeper into the vulnerabilities and preventative techniques crucial for securing smart contracts:</p><p><strong>Key Vulnerabilities:</strong></p><ul><li><strong>Reentrancy Attacks:</strong> These exploit interactions between contracts and external entities. Malicious actors can manipulate the contract’s state and steal its assets by triggering multiple calls within a single transaction.</li></ul><p><strong>Preventative Techniques:</strong></p><ul><li><strong>Use of </strong>transfer<strong> function:</strong> This built-in function limits gas sent with external calls, reducing reentrancy risks.</li><li><strong>Checks-effects-interactions pattern:</strong> Execute state-changing logic before external calls or sending ether, ensuring actions occur in the desired order.</li><li><strong>Mutex:</strong> Introduce a “lock” variable that temporarily disables other functions while one is executing, preventing concurrent access and reentrancy.</li><li><strong>SafeMath library:</strong> Replace standard math operators with secure versions from libraries like SafeMath to prevent arithmetic overflows and underflows.</li><li><strong>Avoid </strong>this.balance<strong>:</strong> Track ether balances using self-defined variables updated in payable functions for accurate and reliable data.</li></ul><p><strong>Additional Best Practices:</strong></p><ul><li><strong>Minimalism:</strong> Keep code simple and focused, reducing attack surface area.</li><li><strong>Code reuse:</strong> Use and improve well-tested, audited code whenever possible.</li><li><strong>Code quality:</strong> Write clean, readable, and well-documented code for easier auditing and maintenance.</li><li><strong>Thorough testing:</strong> Employ manual and automated testing to identify and address vulnerabilities before deployment.</li></ul><p><strong>Embrace Security Throughout the Development Process:</strong></p><p>Security shouldn’t be an afterthought. By integrating these practices throughout the development cycle, from design to testing and deployment, you can build robust and trustworthy smart contracts, fostering confidence and mitigating risks in the ever-evolving blockchain landscape.</p><h3>Project Methodology</h3><p><strong>I. Setup Smart Contract Development Environment</strong></p><p>Set up a local development environment using either Brownie, Hardhat, or Truffle. Build a test suite to ensure everything functions as expected. Finally, put on your security hat and analyze the code for potential vulnerabilities, using available tools and best practices.</p><p><strong>II. Build frontend mobile dApp and backend smart contract</strong></p><p>Craft a smart contract with specific roles: “Admin” to deploy and manage, and “Device” to send GPS data and receive refunds. Remember, at least two states are required. Build an app that accesses GPS, sends data to the contract, and interacts with your device account. I used flutter to build the app.</p><p><strong>III. Enrich Refund By Location smart contract</strong></p><p>Build an API to enable seamless data exchange between the assistant and your smart contract. Make the AI assistant listen: implement a mechanism for it to react to real-time events emitted by the contract (like location updates or refund status). Finally, integrate the assistant smoothly into the dApp’s user interface, offering a more interactive and informative experience.</p><p><strong>IV. Build, test, and deploy the Refund By Location smart contract</strong></p><p>Prepare for deployment: choose a testnet like Rinkeby or Ropsten, considering gas fees and network limitations. Finally, deploy your mobile and web dApps, allowing them to interact with the deployed smart contract and bring your project to life.</p><h4>Project Implementation</h4><p>I. setting up Environment</p><p>I have experimented with development environments like Hardhat and Truffle for Ethereum smart contract development and I have decided to use Truffle for this project. I have created an account on MetaMask and pin some Ethers form sepholia.</p><p>II. Back-End smart contract using solidity</p><p>In the Solidity smart contract called manages contracts between an employer and employees. It includes data structures to store contract details, modifiers to restrict access to certain functions, and functions to handle various operations related to employee contracts. The contract allows the employer to set up employee accounts, track completion counts, calculate distances, and pay employees based on predefined conditions. Additionally, it provides functions to retrieve information about the employer and the list of employees stored in the contract.</p><pre>// SPDX-License-Identifier: SEE LICENSE IN LICENSE<br>pragma solidity ^0.8.13;<br><br>contract RefundContract {<br>    address[] public employees;<br>    address public employeer;<br><br>    struct ContractStatus {<br>        int8 latitude;<br>        int8 longitude;<br>        int8 maxRadius;<br>        uint256 payment;<br>        uint8 compCount;<br>        uint8 reqAmount;<br>    }<br>    mapping (address =&gt; ContractStatus) public empContractStatus;<br>    constructor() {<br>        employeer = msg.sender;<br>    }<br>    <br>    modifier onlyEmployeer() {<br>        require(msg.sender == employeer, &quot;Only employeer has access to this function&quot;);<br>        _;<br>    }<br><br>    modifier onlyEmployee(address _addr) {<br><br>        bool exists = false;<br><br>        if(msg.sender == _addr){<br>            exists = true;<br>        }<br><br>        for (uint256 i = 0; i &lt; employees.length; i++) {<br>            if (employees[i] == _addr) {<br>                exists = true;<br>                break;<br>            }<br>        }<br><br>        require(exists, &quot;Only an  employee has access to this function_2&quot;);<br>        _;<br>    }<br>    <br>    // Modifiers can take inputs. This modifier checks that the<br>    // address passed in is not the zero address.<br>    modifier validAddress(address _addr) {<br>        require(_addr != address(0), &quot;Not valid address&quot;);<br>        _;<br>    }<br><br>    function getSqrt(int256 input) private pure returns (int256  output ) {<br>        int256 temp = (input + 1) / 2;<br>        output = input;<br>        while (temp &lt; output) {<br>            output = temp;<br>            temp = ((input / output) * 2) / 2;<br>        }<br>    }<br><br>    function calculateDistance(int8 _latitude, int8 _longitude) private view  returns (int256 dist) {<br>        int256 x = _latitude - empContractStatus[msg.sender].latitude;<br>        int256 y = _longitude - empContractStatus[msg.sender].longitude;<br>        dist = getSqrt(x**2 + y**2);<br>        return dist;<br>    }<br>    function updateCompCountStatus(int8 _latitude, int8 _longitude) public {<br>            int256 dist = calculateDistance(_latitude, _longitude);<br>            if (dist &lt; empContractStatus[msg.sender].maxRadius) {<br>                empContractStatus[msg.sender].compCount = empContractStatus[msg.sender].compCount + 1;<br>            }<br>    }<br><br>    function payEmployee(address payable _to) public payable onlyEmployee(_to) {<br>        require(empContractStatus[_to].compCount &gt; empContractStatus[_to].reqAmount,&quot;The employee did not remain in compliance with all the agreements.&quot;);<br>        bool sent = _to.send(empContractStatus[_to].payment);<br>        require(sent, &quot;Failed to send Ether&quot;);<br>    }<br><br>    function setEmployeeAccount(<br>        address _empAddr,<br>        int8 _latitude,<br>        int8 _longitude,<br>        int8 _maxRadius,<br>        uint8 _payAmount,<br>        uint8 _reqAmount<br>        // Should also set the duration the contract will be checking for<br>        ) public onlyEmployeer() {<br>            employees.push(_empAddr); // should delete if it is already in the list<br>            empContractStatus[_empAddr].latitude = _latitude;<br>            empContractStatus[_empAddr].longitude = _longitude;<br>            empContractStatus[_empAddr].maxRadius = _maxRadius;<br>            empContractStatus[_empAddr].payment = _payAmount;<br>            empContractStatus[_empAddr].compCount = 0;<br>            empContractStatus[_empAddr].reqAmount = _reqAmount;<br>    }<br><br>    function getAdmin() public view returns(address) {<br>        return employeer;<br>    }<br>    function getEmployees() public view returns(address[] memory){<br>        return employees;<br>    }<br><br>    <br>}</pre><p>The Smart contract functionality tested on remix Ethereum</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nOsIV7qWz8MoKTY353MZDw.png" /></figure><p>III. Front-End</p><p>A flutter mobile app with Admin and employee login options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*JQqZA0s7xNGmY7CHbE71CA.png" /></figure><p>Admin Dashboard</p><p>The Admin has a privilege of adding new employees (driver) and monitor the location of the driver. If the driver manages to stay in the provided</p><p>Employee</p><p>The Employee has ability to track his/her location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*ITapwR2SS8m4CtinbALJvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*tLK6MuUfoScFxf2MPKUyYA.png" /></figure><h3>Conclusion</h3><p>In conclusion, the project outlined a comprehensive approach to developing a smart contract system for managing contracts between employers and employees in the logistics and delivery industry. By setting up a development environment, crafting smart contracts with specific roles, testing, and deploying the system, the project aimed to address challenges like inefficient payments, lack of transparency, and driver motivation. The integration of blockchain technology, smart contracts, GPS data, and real-time event handling demonstrated a promising solution to revolutionize industry practices.</p><h3>Future work</h3><p>For future work on the project, potential areas of focus could include:</p><ul><li>Enhancing Security: Conducting thorough security audits to identify and address any vulnerabilities in the smart contract code and system architecture.</li><li>Scalability Improvements: Exploring solutions to enhance the scalability of the system to handle a larger volume of transactions and users efficiently.</li><li>User Experience Enhancements: Iterating on the frontend mobile dApp to improve user experience, add more features, and make it more intuitive for both administrators and employees.</li><li>Regulatory Compliance: Ensuring that the system complies with relevant regulations and standards in the logistics and delivery industry, especially concerning data privacy and security.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=466f3c27e821" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Precision RAG: Building Enterprise Grade RAG Systems]]></title>
            <link>https://medium.com/@elias.assamnew/precision-rag-52151c17b80a?source=rss-bd07403bb0c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/52151c17b80a</guid>
            <dc:creator><![CDATA[Elias Assamnew]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 15:14:01 GMT</pubDate>
            <atom:updated>2024-01-26T18:06:17.618Z</atom:updated>
            <content:encoded><![CDATA[<h3>Precision RAG: Prompt Tuning For Building Enterprise Grade RAG Systems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7JTiSa5PuFI8yI4k.png" /><figcaption>RAG</figcaption></figure><h3>The objective of the project</h3><p>The project objective for PromptlyTech is to develop and implement AI-driven solutions that streamline the prompt engineering process for Language Models (LLMs). This includes creating effective prompts, automating the generation of evaluation data, and testing and ranking prompts for optimal performance. The primary goal is to enhance the accessibility, efficiency, and effectiveness of LLMs across various industries, ultimately improving decision-making, operational efficiency, and customer experience.</p><p>By focusing on Automatic Prompt Generation, Automatic Evaluation Data Generation, and Prompt Testing and Ranking services, the project aims to address the challenges associated with prompt engineering, saving time, enhancing LLM productivity, and making advanced AI capabilities more accessible to a broader range of users in a digitally-driven business landscape.</p><h3><strong>Background</strong></h3><p>Businesses have eagerly adopted Large Language Models (LLMs) like ChatGPT to enhance operations, but there are challenges. Pretrained LLMs may not meet specific needs due to the requirement for tailored outputs, potential lack of knowledge about contextually important documents, and difficulties in handling specialized vocabulary, unique terminologies, and industry-specific concepts.</p><p>To align a Large Language Model (LLM) with specific requirements, tuning methods can be employed, including Full Fine-tuning, Parameter-efficient Fine-tuning (PEFT), Prompt Engineering, and RAG (Retrieval Augmented Generation).</p><p>To align a Large Language Model (LLM) with specific requirements, tuning is essential. There are four prominent tuning methods:</p><ul><li>Full Fine-tuning: Adjusts all parameters of the LLM using task-specific data.</li><li>Parameter-efficient Fine-tuning (PEFT): Modifies select parameters for more efficient adaptation.</li><li>Prompt Engineering: Refines the model’s input to guide its output.</li><li>RAG (Retrieval Augmented Generation): Merges prompt engineering with database querying for context-rich answers.</li></ul><p>They vary in expertise needed, cost, and suitability for different scenarios. This article explores each, shedding light on their nuances, costs, and optimal use cases. Dive in to discover which method is the best fit for your project.</p><h3>What is Retrieval-augmented generation (RAG)</h3><p>Retrieval-augmented generation (RAG) is a natural language processing technique that merges information retrieval with text generation. In the business world, RAG is vital for implementing generative AI across various tasks like onboarding, question-answering, chatbots, content generation, document summarization, and service-agent support.</p><p>RAG’s strength lies in its capacity to fetch contextually relevant information from additional sources such as documents and databases, and integrate it into human-like text. In simple terms, it enables AI systems to access an organization’s own data and utilize that knowledge to improve the quality and accuracy of the content they produce.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6jwThBCG1_zG3TeD.png" /><figcaption>RAG process</figcaption></figure><h3>Methodology</h3><p>The first part of the project neeeds to explore various components to be implemented.</p><ul><li>Explore the evolutionary landscape of automatic prompt engineering tailored for Language Models (LLMs) and Retrieval-Augmented Generation (RAG) systems within the context of enterprise AI applications. Gain insights into the fundamental components that constitute enterprise-grade RAG systems, and delve into the specifics of Langchain Retrievers. Investigate the advancements in RAG, focusing on both Large Language Models (LLMs) and Small Language Models (SLMs), with a particular emphasis on their applications in text generation processes within the business domain.</li><li>Recognize the crucial role of advanced prompt engineering in building robust enterprise-grade Retrieval-Augmented Generation (RAG) systems. Compare Full Fine-Tuning, PEFT, Prompt Engineering, and RAG, assessing their suitability for different scenarios.</li><li>RAG Evaluation: Comprehend the importance of evaluating RAG components. Explore various evaluation approaches, including benchmarking with LLMs and specific tools like RAGAs and LangChain,</li><li>Generating RAG Evaluation Data: Understand tools and techniques for automatically generating RAG evaluation data, including synthetic datasets.</li><li>End-to-End Technology Stack: Learn key packages for planning, building, testing, monitoring, and deploying enterprise-grade RAG systems.</li></ul><h3>Project Implementation</h3><h4>Part 1: Model exploration</h4><p>The first part of the project is exploring the capability of openAI knowledge base.</p><pre>from langchain.schema import (<br>    SystemMessage,<br>    HumanMessage,<br>    AIMessage<br>)<br><br>messages = [<br>    SystemMessage(content=&quot;You are a helpful assistant.&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>    HumanMessage(content=&quot;I&#39;d like to understand string theory.&quot;)<br>]<br>The format is very similar, we&#39;re just swapped the role of `&quot;user&quot;` for `HumanMessage`, and the role of `&quot;assistant&quot;` for `AIMessage`.<br><br>We generate the next response from the AI by passing these messages to the `ChatOpenAI` object.<br>res = chat(messages)<br>res<br>In response we get another AI message object. We can print it more clearly like so:<br>print(res.content)</pre><p>The result was sufficient enough</p><pre>sure, I can help you with that. String theory is a theoretical framework in physics that aims to describe the fundamental particles and forces of nature. It suggests that at the most fundamental level, everything in the universe is made up of tiny vibrating strings or loops of energy.<br><br>According to string theory, these strings are incredibly small, with a length scale of about the Planck length (about 10^(-35) meters). The different vibrational patterns of these strings give rise to different particles, such as electrons, quarks, and photons.<br><br>One of the key ideas in string theory is that it requires more than the usual four dimensions of space and time (three spatial dimensions and one time dimension) that we are familiar with. In fact, string theory suggests that there are additional hidden dimensions, usually referred to as &quot;extra dimensions,&quot; which are curled up or compactified at such small scales that we can&#39;t perceive them directly.<br><br>These extra dimensions can take various forms...</pre><h4>Hallucination of the model</h4><p>Model hallucination refers to a phenomenon where a language model generates outputs that may include inaccurate or fictitious information, leading to the creation of content that deviates from factual or contextually appropriate details. In other words, the model produces content that is not grounded in real-world data but is instead a product of its training on diverse and sometimes noisy information. Model hallucination can pose challenges in applications where accuracy and reliability are crucial, as the generated content may be misleading or incorrect.</p><p>The model asked about the llama2 released by meta</p><pre># add latest AI response to messages<br>messages.append(res)<br><br># now create a new user prompt<br>prompt = HumanMessage(<br>    content=&quot;What is so special about Llama 2?&quot;<br>)<br># add to messages<br>messages.append(prompt)<br><br># send to OpenAI<br>res = chat(messages)</pre><pre>I&#39;m sorry, but I&#39;m not aware of any specific significance or special meaning associated with &quot;Llama 2.&quot; It&#39;s possible that you may be referring to something specific, <br>like a book, a movie, a game, or a particular reference in a context that I&#39;m not aware of. Could you please provide more information or context so that I can better understand and assist you?</pre><h4>Part 2: RAG implementation</h4><p>The first phase of this procedure commenced with incorporating the company’s dataset into the Retrieval-Augmented Generation (RAG) framework. Utilizing the Pinecone Vector database, Pinecone executed low-latency vector searches to retrieve pertinent data for various applications, including search, RAG, recommendation, detection, and more. We streamlined the process by ensuring the effortless upload of the dataset into our designated data repository.</p><pre>import time<br>index_name = &quot;langchain&quot;<br>import os<br>import pinecone<br>from langchain.embeddings.openai import OpenAIEmbeddings<br><br># get API key from app.pinecone.io and environment from console<br>pinecone.init(<br>    api_key=os.environ.get(&#39;PINECONE_API_KEY&#39;) or &#39;PINECONE_API_KEY&#39;,<br>    environment=os.environ.get(&#39;PINECONE_ENVIRONMENT&#39;) or &#39;gcp-starter&#39;<br>)<br><br>if index_name not in pinecone.list_indexes():<br>    pinecone.create_index(<br>        index_name,<br>        dimension=1536,<br>        metric=&#39;cosine&#39;<br>    )<br>    # wait for index to finish initialization<br>    while not pinecone.describe_index(index_name).status[&#39;ready&#39;]:<br>        time.sleep(1)<br>#Intialise the index<br>index = pinecone.Index(index_name)<br>index.describe_index_stats()<br><br><br><br>embed_model = OpenAIEmbeddings(model=&quot;text-embedding-ada-002&quot;)<br># Using this model we can create embeddings like so:<br>texts = [<br>    &#39;this is the first chunk of text&#39;,<br>    &#39;then another second chunk of text is here&#39;<br>]<br><br>res = embed_model.embed_documents(texts)<br>len(res), len(res[0])<br>From this we get two (aligning to our two chunks of text) 1536-dimensional embeddings.<br><br><br>data = dataset.to_pandas()  # this makes it easier to iterate over the dataset<br><br>batch_size = 100<br><br>for i in tqdm(range(0, len(data), batch_size)):<br>    i_end = min(len(data), i+batch_size)<br>    # get batch of data<br>    batch = data.iloc[i:i_end]<br>    # generate unique ids for each chunk<br>    ids = [f&quot;{x[&#39;id&#39;]}&quot; for _, x in batch.iterrows()]<br><br>    # get text to embed<br>    texts = [x[&#39;text&#39;] for _, x in batch.iterrows()]<br>    # embed text<br>    embeds = embed_model.embed_documents(texts)<br>    # get metadata to store in Pinecone<br>    metadata = [<br>        {&#39;text&#39;: x[&#39;text&#39;],<br>         &#39;source&#39;: x[&#39;source&#39;]<br>         } for i, x in batch.iterrows()<br>    ]<br>    # add to Pinecone<br>    index.upsert(vectors=zip(ids, embeds, metadata))</pre><p>The will initializes Pinecone with an API key, sets up a “langchain” index, and employs the OpenAI text-embedding-ada-002 model to generate 1536-dimensional embeddings for chunks of text. The dataset is processed in batches, and unique IDs are assigned to each chunk. Texts are embedded using the model, and metadata, including text and source information, is extracted. The resulting embeddings, along with IDs and metadata, are then integrated into the Pinecone index in a batch-wise manner. This process facilitates the seamless incorporation of text data into the Retrieval-Augmented Generation (RAG) framework.</p><h4>Part 3: Automatic Prompt Generation</h4><h4>Context Generation</h4><p>the first step in prompt generation is accepting user input and automatically generating context from the vector data created that will be the knowledge base or context for the prompt generation</p><pre>def retrieve_context(query, k=3):<br><br>    env_file_path = find_dotenv(raise_error_if_not_found=True)<br>    load_dotenv(env_file_path)<br><br>    OPENAI_API_KEY = os.environ.get(&quot;OPENAI_API_KEY&quot;)<br><br>    chat = ChatOpenAI(<br>        openai_api_key=OPENAI_API_KEY,<br>        model=&#39;gpt-3.5-turbo&#39;<br>    )<br><br>    # Initialize Pinecone and setup the vector store<br>    pinecone.init(<br>        api_key=os.environ.get(&#39;PINECONE_API_KEY&#39;) or &#39;PINECONE_API_KEY&#39;,<br>        environment=os.environ.get(&#39;PINECONE_ENVIRONMENT&#39;) or &#39;gcp-starter&#39;<br>    )<br>    index_name = &quot;langchain&quot;<br>    embed_model = OpenAIEmbeddings(model=&quot;text-embedding-ada-002&quot;)<br>    index = pinecone.Index(index_name)<br>    text_field = &quot;text&quot;  # the metadata field that contains our text<br>    vectorstore = Pinecone(<br>        index,<br>        embed_model.embed_query,<br>        text_field<br>    )<br><br>    # Perform similarity search to retrieve context<br>    context = vectorstore.similarity_search(query, k=k)<br>    <br>    source_knowledge = &quot;\n&quot;.join([x.page_content for x in context])<br>    <br>    <br>    # Ensure the directory exists before writing the file<br>    folder_path = &quot;prompts&quot;<br>    print(folder_path)<br>    os.makedirs(folder_path, exist_ok=True)<br><br>    file_path = os.path.join(folder_path, &#39;context.txt&#39;)<br>    with open(file_path, &#39;w&#39;) as file:<br>        file.write(source_knowledge)<br>    return context<br><br>if __name__ == &quot;__main__&quot;:<br>    query = str(input(&quot;inputText: &quot;))<br></pre><p>This function, retrieve_context, that retrieves context based on vector similarity from the Pinecone vector store. The function uses OpenAI&#39;s GPT-3.5-turbo model and Pinecone for similarity search. It takes a user query and retrieves the most similar context (defaulting to three neighbors) from the Pinecone vector store. The context is then written to a file named &#39;context.txt&#39; in the &#39;prompts&#39; directory.</p><p>In the __main__ block, the user is prompted to input text, and the retrieve_context function is called with the input text. The retrieved context is then printed.</p><h4>Automatic Prompt generation</h4><p>Here we define functions for generating test data based on a given prompt, context, and the number of desired test outputs. The generate_test_data function makes an API call to obtain completions, and the resulting data is saved in JSON format using the save_json function. The main function, will retrieve context information from the input text which is user query. Based on that context the function generates prompts of fixed number.</p><pre>def generate_test_data(prompt, context, num_test_output):<br>    API_RESPONSE = get_completion([<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt.replace(&quot;{context}&quot;, context).replace(&quot;{num_test_output}&quot;, num_test_output)}<br>    ], logprobs=True, top_logprobs=1)<br><br>    return API_RESPONSE.choices[0].message.content<br><br>def save_json(test_data):<br>    file_path = &quot;test-dataset/test-data.json&quot;<br>    json_object = json.loads(test_data)<br>    with open(file_path, &#39;w&#39;) as json_file:<br>        json.dump(json_object, json_file, indent=4)<br><br>    print(f&quot;JSON data has been saved to {file_path}&quot;)<br><br>def main(num_test_output, inputText: str):<br>    context_message=context=retrieve_context(inputText)<br>if __name__ == &quot;__main__&quot;:<br>    user_input = str(input(&quot;inputText: &quot;))<br>    main(&quot;5&quot;, user_input)  # n number of test data to generate</pre><p>The resulting prompts with ground truth for user query of “what is langchain?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wCILFqL_zuWJ-boLU2U_w.png" /></figure><h4>Part 3: Prompt generation evaluation</h4><p>here we defines an evaluate function that assesses the adequacy of context for answering user questions using the GPT-3.5-turbo model. It replaces placeholders in a prompt with provided context and user messages, logs system responses, log probabilities, and calculates accuracy.</p><pre>def evaluate(prompt: str, user_message: str, context: str) -&gt; str:<br>    num_test_output = str(10)<br>    API_RESPONSE = get_completion(<br>        [<br>            {<br>                &quot;role&quot;: &quot;system&quot;, <br>                &quot;content&quot;: prompt.replace(&quot;{Context}&quot;, context).replace(&quot;{Question}&quot;, user_message)<br>            }<br>        ],<br>        model=&quot;gpt-3.5-turbo&quot;,<br>        logprobs=True,<br>        top_logprobs=1,<br>    )<br><br>    system_msg = str(API_RESPONSE.choices[0].message.content)<br><br>    for logprob in API_RESPONSE.choices[0].logprobs.content[0].top_logprobs:<br>        output = f&#39;\nhas_sufficient_context_for_answer: {system_msg}, \nlogprobs: {logprob.logprob}, \naccuracy: {np.round(np.exp(logprob.logprob)*100, 2)}%\n&#39;<br>        print(output)<br>        if system_msg == &#39;true&#39; and np.round(np.exp(logprob.logprob)*100, 2) &gt;= 95.00:<br>            classification = &#39;true&#39;<br>        elif system_msg == &#39;false&#39; and np.round(np.exp(logprob.logprob)*100, 2) &gt;= 95.00:<br>            classification = &#39;false&#39;<br>        else:<br>            classification = &#39;false&#39;<br>    return classification<br><br>if __name__ == &quot;__main__&quot;:<br>   <br>    context_message = file_reader(&quot;prompts/context.txt&quot;)<br>    prompt_message = file_reader(&quot;prompts/generic-evaluation-prompt.txt&quot;)<br>    context = str(context_message)<br>    prompt = str(prompt_message)<br>  <br>    # Read the generated prompts file<br>    with open(file_path, &#39;r&#39;) as f:<br>        prompts = json.load(f)<br><br>    # Extract the questions from the prompts<br>    questions = [prompt[&#39;prompt&#39;] for prompt in prompts]<br>    <br>    # Evaluate each question<br>    for question in questions:<br>        print(evaluate(prompt, question, context))</pre><p>The __main__ block reads context and prompt messages from files, extracts questions from a JSON file, and evaluates each question using the evaluate function.</p><p>The result for the above user query “what is langchain?” it generates 5 prompts and the evaluation result shows it has sufficient context to answer the prompts generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGYdi-xA_mrwvgVx1cfa6g.png" /><figcaption>Evaluation results</figcaption></figure><h4>Part 4: User Interface</h4><p>Simple user interface to accept user query with expected output and present the generated prompt with their score developed with react. At the backend Fast API has been used for this project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mr5GReF_VcYKka8LG6QquA.png" /></figure><h4>Part 5: System Integration and Testing</h4><h4>Monte Carlo Matchmaking and ELO Rating System</h4><p>The Monte Carlo Matchmaking method is used to select and match different prompt candidates against each other. It simulates various matchups to test the effectiveness of each prompt in different scenarios, optimizing the information gained from each battle. On the other hand, the ELO Rating System rates prompt candidates based on their performance in these battles, assigning a rating reflecting their success in previous matchups, taking into account not just the number of wins but also other factors. This system is commonly used in chess and other competitive games.</p><pre>file_path = &#39;../test-dataset/test-data.json&#39;<br># Open the file in read mode<br>with open(file_path, &#39;r&#39;) as file:<br>    # Read the contents of the file<br>    file_contents = file.read()<br>file_contents <br>file_path = &#39;../prompts/context.txt&#39;<br># Open the file in read mode<br>with open(file_path, &#39;r&#39;) as file:<br>    # Read the contents of the file<br>    context = file.read()<br>context<br>import json<br><br># file_contents = file_contents<br><br># Load the JSON data<br>data = json.loads(file_contents)<br><br># Separate prompts and ground truths<br>questions = [item[&#39;prompt&#39;] for item in data]<br>ground_truths = [item[&#39;ground_truth&#39;] for item in data]<br><br><br>print(&quot;\nGround Truths:&quot;)<br>for ground_truth in ground_truths:<br>    print(ground_truth)<br><br>print(&quot;\nquestions:&quot;)<br>for question in questions:<br>    print(question)<br><br>main_prompt = &quot;what is special about lama2?&quot;<br>test_cases = questions<br># result = evaluate_prompt(main_prompt, test_cases)<br># print(result)<br>test_cases<br>result = evaluate_prompt(main_prompt, test_cases)<br>print(result)<br></pre><pre>{&#39;main_prompt&#39;: {&#39;Monte Carlo Evaluation&#39;: 2.08, &#39;Elo Rating Evaluation&#39;: 1519.2019499940866},<br> &#39;test_case_1&#39;: {&#39;Monte Carlo Evaluation&#39;: 2.05, &#39;Elo Rating Evaluation&#39;: 1504.2019499940866},<br> &#39;test_case_2&#39;: {&#39;Monte Carlo Evaluation&#39;: 2.05, &#39;Elo Rating Evaluation&#39;: 1519.2019499940866}, <br>&#39;test_case_3&#39;: {&#39;Monte Carlo Evaluation&#39;: 1.97, &#39;Elo Rating Evaluation&#39;: 1519.2019499940866}, <br>&#39;test_case_4&#39;: {&#39;Monte Carlo Evaluation&#39;: 2.1, &#39;Elo Rating Evaluation&#39;: 1489.2019499940866}, <br>&#39;test_case_5&#39;: {&#39;Monte Carlo Evaluation&#39;: 1.99, &#39;Elo Rating Evaluation&#39;: 1489.2019499940866}<br>}<br></pre><h4><strong>RAGAS Evaluation</strong></h4><p>RAGAs, which stands for Retrieval-Augmented Generation Assessment, is a framework that assists in evaluating RAG pipelines at a component level. It was initially developed for “reference-free” evaluation, leveraging LLMs to conduct evaluations without relying on human-annotated ground truth labels. To evaluate the RAG pipeline, RAGAs requires information such as the user query, the generated answer, retrieved contexts, and the ground truth answer. Leveraging LLMs for reference-free evaluation is an active research area, aiming to minimize the use of human-annotated data for a more cost-effective and efficient evaluation method, despite some discussions about potential biases.</p><p>RAGAs provides metrics to evaluate retrieval and generation components of a RAG pipeline. For retrieval, it includes context precision and context recall.</p><ul><li>Context precision measures the signal-to-noise ratio of the retrieved context</li><li>Context recall assesses if all relevant information required to answer the question was retrieved</li><li>For generation, it includes faithfulness and answer relevancy</li><li>Faithfulness measures the factual accuracy of the generated answer</li><li>Answer relevancy measures how relevant the generated answer is to the question</li></ul><p>All metrics are scaled from 0 to 1, with higher values indicating better performance.</p><pre>from datasets import Dataset<br>data = {<br>    &quot;question&quot;: questions_list, # list <br>    &quot;answer&quot;: Answer, # list<br>    &quot;contexts&quot;: context_lists, # list list<br>    &quot;ground_truths&quot;: ground_truths_lists # list Lists<br>}<br><br># Convert dict to dataset<br>dataset = Dataset.from_dict(data)<br>from ragas import evaluate<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>    metrics=[<br>        context_precision,<br>        context_recall,<br>        faithfulness,<br>        answer_relevancy,<br>    ],<br>)<br><br>df = result.to_pandas()<br>evaluating with [context_precision]<br>100%|██████████| 1/1 [00:06&lt;00:00,  6.86s/it]<br>evaluating with [context_recall]<br>100%|██████████| 1/1 [00:01&lt;00:00,  1.78s/it]<br>evaluating with [faithfulness]<br>100%|██████████| 1/1 [00:04&lt;00:00,  4.33s/it]<br>evaluating with [answer_relevancy]<br>100%|██████████| 1/1 [00:04&lt;00:00,  4.30s/it]<br>df<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T91npj_5v13JL5MN4jRvEg.png" /></figure><p>The the RAGAs pipeline for query “what is llama2?” shows not low result for context precision. suggesting for better context retrieval. that implemented with other data from hugging face on “Langchain” but for this project time.</p><h3>Conclusion</h3><p>In conclusion, the project embarked on a multifaceted journey to revolutionize prompt engineering, particularly focusing on Retrieval-Augmented Generation (RAG) systems. The comprehensive exploration covered the end-to-end technology stack, evaluation techniques, and key packages vital for planning, building and testing such systems.</p><p>the project contributed to the design and development of the Prompt Generation System, introducing sophisticated algorithms to automate prompt generation based on user input. The incorporation of evaluation data generation added a crucial layer to the process, ensuring that the generated prompts align with the input descriptions and providing a diverse range of alternatives for consideration.</p><p>The project also incorporate Prompt Testing and Ranking, emphasizing a comprehensive evaluation approach that allows users to customize their preferred evaluation methods. The incorporation of innovative methods such as Monte Carlo Matchmaking and the ELO rating system showcased a commitment to dynamic and adaptive ranking methodologies.</p><p>User Interface Developed, aiming to create a user-friendly interaction platform. The design and implementation of an intuitive interface allowed users to input data seamlessly, receive prompts, and access evaluation results with ease.</p><p>In essence, the project stands as a testament to the commitment to advancing prompt engineering in the AI landscape, with a focus on practical applications such as RAG systems. The multifaceted approach encompassing automated prompt generation, evaluation data generation, dynamic ranking methodologies, user-friendly interfaces, and comprehensive testing positions the project at the forefront of reshaping how businesses harness the power of Language Models for optimal accessibility and effectiveness.</p><h3>Future Work</h3><ul><li>User-Centric Customization: Enhance user control over prompt customization, allowing for a more tailored prompt generation experience based on individual preferences.</li><li>Continuous Model Training: Implement a mechanism for ongoing Language Model (LLM) training to stay updated with evolving user needs and industry trends.</li><li>Advanced Evaluation Metrics: Research and integrate advanced evaluation metrics, leveraging state-of-the-art natural language processing and machine learning techniques for nuanced assessments.</li><li>Semantic Understanding: Improve the system’s ability to comprehend semantic nuances in user input, advancing Natural Language Processing (NLP) capabilities.</li><li>Integration with External Knowledge Bases: Link the prompt engineering system with external knowledge bases to enhance prompt depth and accuracy through access to domain-specific information.</li><li>Real-time User Feedback Mechanism: Introduce a real-time feedback loop in the user interface to gather immediate insights, facilitating rapid system improvements based on user preferences and interactions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52151c17b80a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End Web3 dApps]]></title>
            <link>https://medium.com/@elias.assamnew/end-to-end-web3-dapps-7b18a1faa5f5?source=rss-bd07403bb0c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b18a1faa5f5</guid>
            <dc:creator><![CDATA[Elias Assamnew]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 19:58:22 GMT</pubDate>
            <atom:updated>2024-01-19T00:47:55.467Z</atom:updated>
            <content:encoded><![CDATA[<h4>Certificate generation, distribution, and value transfer with Algorand NFTs and smart contracts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/0*cxl6foMNLR5BmYjf.png" /></figure><h3>The objective of the project</h3><p>The primary objective of this project is to revolutionize the certificate issuance and management process for 10 Academy by leveraging cutting-edge Web3 technologies, specifically the Algorand Blockchain. The current practice of distributing simple PDF certificates lacks both security and the ability to execute smart contract actions. By implementing Non-Fungible Tokens (NFTs) on the Algorand Blockchain, the project aims to establish a secure, tamper-proof system for generating certificates upon the successful completion of weekly challenges. This not only enhances the authenticity and verifiability of certificates but also opens avenues for trainees to engage with smart contracts, enabling predefined actions related to their achievements.</p><p>The project further seeks to enhance user experience through the development of an intuitive decentralized application (dapp) interface, ensuring easy navigation for trainees in generating, managing, and interacting with their NFT certificates. The decentralized nature of the Algorand Blockchain, coupled with robust security measures and privacy features, ensures a trustworthy and transparent system. Ultimately, the project strives to empower trainees with a secure, user-friendly, and future-proofed platform, fostering increased trust, engagement, and satisfaction within the 10 Academy community.</p><h3>Web3 Technology</h3><p>Web2, characterized by statelessness and the absence of a native state transfer mechanism, has prompted the evolution toward Web3 solutions.</p><p>Web3 introduces decentralized state management, utilizing blockchain and decentralized applications (DApps). This shift provides users with control over their digital state, a departure from Web2’s reliance on centralized service providers.</p><p>Additionally, Web3 focuses on efficient state transfer mechanisms, facilitating seamless and secure transactions of value. In contrast to Web2’s advertising-centric business model, Web3 promotes decentralization, aligning incentives with users and offering a user-centric approach.</p><p>The direction of Web3 signifies a move towards a decentralized and user-controlled internet, emphasizing transparent value transfer and efficient state management.</p><p>Web3 technology stack aims to address the statelessness of the current internet, introducing layers for holding and transferring state. Key layers include:</p><ol><li>User Control Layer: Manages private keys and facilitates user interaction with Web3 applications.</li><li>Scalability / Transfer Layer: Addresses blockchain scalability issues and Proposes solutions like payment channels, state channels, and side chains for efficient state transfer.</li><li>Protocol Layer: Standardizes functions for components and forms markets for digital components on the State Layer.</li><li>Component Layer: Builds on the Computation Layer and Introduces diverse digital components like native currency, crypto assets, crypto goods, identity, and stablecoins.</li><li>Computation Layer: Allows users to instruct the State Layer and the choices (e.g., Bitcoin’s Script or Ethereum’s EVM) determine blockchain compatibility.</li><li>State Layer: Preserves the state of underlying layers and Provided by blockchain infrastructure, it can be public or private/permission.</li></ol><figure><img alt="The Web 3 Stack — A modular framework" src="https://cdn-images-1.medium.com/max/1024/0*k6BzvbDEndExRBN9.png" /></figure><p><em>The Web 3 Stack — A modular framework</em></p><h3>Algorand blockchain</h3><p>he Algorand blockchain is a decentralized, public blockchain platform that supports a wide range of applications, including decentralized finance (DeFi), smart contracts, and non-fungible tokens (NFTs). It was founded in 2017 by Silvio Micali, a Turing Award-winning computer scientist and professor at the Massachusetts Institute of Technology (MIT).</p><p>The Algorand blockchain is designed to be scalable, secure, and efficient. It uses a unique consensus mechanism called Pure Proof-of-Stake (PPoS), which allows for fast and secure transactions without the need for energy-intensive mining. PPoS also ensures that the network is decentralized and resistant to censorship.</p><p>As of January 2023, the Algorand blockchain has a market capitalization of over $1.5 billion and over 10 million accounts. It is one of the most popular blockchain platforms for DeFi and NFT applications, and it is supported by a growing ecosystem of developers and businesses.</p><p>Here are some of the key features of the Algorand blockchain:</p><ul><li><strong>Scalability:</strong> The Algorand blockchain can process up to 1,000 transactions per second (TPS) and can scale to handle even more transactions as the network grows.</li><li><strong>Security:</strong> The Algorand blockchain uses a unique consensus mechanism called Pure Proof-of-Stake (PPoS), which provides strong security and resistance to censorship.</li><li><strong>Efficiency:</strong> The Algorand blockchain is very efficient, with low transaction fees and fast confirmation times.</li><li><strong>Decentralization:</strong> The Algorand blockchain is decentralized and not controlled by any single entity.</li><li><strong>Open source:</strong> The Algorand blockchain is open source and free to use.</li></ul><p>The Algorand blockchain is a promising platform for a wide range of applications, and it is likely to continue to grow in popularity in the years to come.</p><h3>Frontend and backend technologies</h3><p>IN this Project full-stack template provided by Algokit for both a baseline React web app and a production-ready baseline for developing and deploying <a href="https://github.com/algorand-devrel/beaker">Beaker</a> smart contracts. It&#39;s suitable for developing and integrating with any <a href="https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0032.md">ARC32</a> compliant Algorand smart contracts.</p><p>To use this template, <a href="https://github.com/algorandfoundation/algokit-cli#readme">install AlgoKit</a> and then either pass in -t fullstack to algokit init or select the relevant template interactively during algokit init.</p><p>This is one of the official templates used by AlgoKit to initialize both a frontend React web app and Algorand smart contract project. It&#39;s created based on the <a href="https://copier.readthedocs.io/en/stable/">Copier templates</a>.</p><h4>Features</h4><p>This template supports a multitude of features for both frontend and backend:</p><h4>Frontend</h4><ul><li>React web app with <a href="https://tailwindcss.com/">Tailwind CSS</a> and <a href="https://www.typescriptlang.org/">TypeScript</a></li><li>Styled framework agnostic CSS components using <a href="https://daisyui.com/">DaisyUI</a>.</li><li>Starter Jest unit tests for TypeScript functions. Can be disabled if not needed.</li><li>Starter <a href="https://playwright.dev/">playwright</a> tests for end-to-end testing. Can be disabled if not needed.</li><li>Integration with <a href="https://github.com/txnlab/use-wallet">use-wallet</a> for connecting to Algorand wallets such as Pera, Defly, and Exodus.</li><li>Example of performing a transaction with HelloWorld smart contract.</li><li>dotenv support for environment variables, as well as a local-only KMD provider that can be used for connecting the frontend component to an algokit localnet instance (Docker required).</li><li>CI/CD pipelines using GitHub Actions to deploy to Vercel or Netlify</li></ul><h4>Backend</h4><ul><li>Compilation of multiple Beaker contracts to a predictable folder location and file layout where they can be deployed.</li><li>Deploy-time immutability and permanence control.</li><li><a href="https://python-poetry.org/">Poetry</a> for Python dependency management and virtual environment management.</li><li><a href="https://flake8.pycqa.org/en/latest/">Flake8</a>.</li><li>Formatting via <a href="https://github.com/psf/black">Black</a>.</li><li>Type checking via <a href="https://mypy-lang.org/">mypy</a>.</li><li>Testing via pytest (not yet used).</li></ul><h3>Implementation</h3><h4>Generate Certeficate using OpenAI dele-e</h4><p>Generate Simple certificate Background using specific and descriptive prompt.</p><pre>ef generate_certificate_background(output_folder):<br>    # Step 1: Generate Beautiful Certificate Background (Using OpenAI API)<br>    <br>    response = client.images.generate(<br>        model=&quot;dall-e-3&quot;,<br>        prompt=&quot;&quot;&quot;<br>                Create a minimalist and sophisticated certificate background, <br>                ideal for highlighting achievements without overshadowing the main content. <br>                The design should feature very light and unobtrusive bold Red patterns, <br>                ensuring they are not too eye-catching. Include thin, elegant borders that frame the certificate tastefully. <br>                The color palette should be restricted to soft, neutral tones, providing a clean and professional look. <br>                Overall, the background must support and enhance the legibility and prominence of the certificate&#39;s text, <br>                blending seamlessly with the overall layout, without drawing attention away from the central message of the certificate, <br>                put no wrting oon the background, use bold red color for the boarders<br>        &quot;&quot;&quot;,<br>        size=&quot;1024x1024&quot;,<br>        quality=&quot;standard&quot;,<br>        n=1,<br>    )<br><br>    image_url = response.data[0].url<br><br>    background_path = os.path.join(output_folder, &#39;certificate_background.png&#39;)<br><br>    # Use requests to download the image<br>    with open(background_path, &#39;wb&#39;) as f:<br>        f.write(requests.get(image_url).content)<br><br>    return background_path</pre><p>The Certificate Generated has the following look</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wqdr1N1Rzq7sl4QSh0gUOA.png" /></figure><h4>Set Up Algorand Development Environment</h4><p>To set up an Algorand development environment using algokit, begin by installing the SDK with pip install algokit. Create a configuration file (algokit_config.yaml) specifying your Algorand node&#39;s address and token. Initialize AlgoKit with this configuration and test the connection. You can then interact with the Algorand blockchain, fetching account information or executing transactions. In the provided code snippet, an example demonstrates minting an NFT using AssetTransferTransaction. Ensure you replace placeholder values such as private keys and addresses with your actual data. This concise script covers the essential steps to connect to the Algorand blockchain, fetch information, and perform a basic transaction.</p><h4>Define Smart Contract Logic</h4><p>Create a simple smart contract logic using Algorand’s Smart Contracts in TEAL.</p><h4>Generate NFTs</h4><pre>def create_asset(sender_address, sender_private_key, asset_url):<br>    sp = algod_client.suggested_params()<br>    txn = transaction.AssetConfigTxn(<br>        sender=sender_address,<br>        sp=sp,<br>        default_frozen=False,<br>        unit_name=&quot;Certificate&quot;,<br>        asset_name=&quot;Certificate&quot;,<br>        manager=sender_address,<br>        reserve=sender_address,<br>        freeze=sender_address,<br>        clawback=sender_address,<br>        url=asset_url,<br>        total=1,<br>        decimals=0,<br>    )<br><br>    # Sign with secret key of creator<br>    stxn = txn.sign(sender_private_key)<br>    # Send the transaction to the network and retrieve the txid.<br>    txid = algod_client.send_transaction(stxn)<br>    print(f&quot;Sent asset create transaction with txid: {txid}&quot;)<br>    # Wait for the transaction to be confirmed<br>    results = transaction.wait_for_confirmation(algod_client, txid, 4)<br>    print(f&quot;Result confirmed in round: {results[&#39;confirmed-round&#39;]}&quot;)<br>    return results</pre><pre>create_asset(<br>    sender_address=user_account, <br>    sender_private_key=sender_private_key, <br>    asset_url=&quot;https://ipfs.io/ipfs/QmRkePdXa4F15Pr234imUR1knjDccWDSN4WgPjoivfd3vJ&quot;)</pre><h4>Upload to Pinata</h4><p>Pinata is a cloud service for keeping your NFT. This plugin makes NFT file storage easy for everyone. You can upload and pin images or videos, 3D files, or even an app on Pinata. All of Pinata’s content is available on the public IPFS network. This means that anybody running an IPFS node can access content stored on Pinata through their own IPFS node.</p><p>To upload your NFT to pinata:</p><pre>const axios = require(&#39;axios&#39;)<br>const FormData = require(&#39;form-data&#39;)<br>const fs = require(&#39;fs&#39;)<br>const JWT = &#39;Bearer PASTE_YOUR_PINATA_JWT&#39;</pre><pre>const pinFileToIPFS = async () =&gt; {<br>    const formData = new FormData();<br>    const src = &quot;path/to/file.png&quot;;<br>    <br>    const file = fs.createReadStream(src)<br>    formData.append(&#39;file&#39;, file)<br>    <br>    const pinataMetadata = JSON.stringify({<br>      name: &#39;File name&#39;,<br>    });<br>    formData.append(&#39;pinataMetadata&#39;, pinataMetadata);<br>    <br>    const pinataOptions = JSON.stringify({<br>      cidVersion: 0,<br>    })<br>    formData.append(&#39;pinataOptions&#39;, pinataOptions);<br>    try{<br>      const res = await axios.post(&quot;https://api.pinata.cloud/pinning/pinFileToIPFS&quot;, formData, {<br>        maxBodyLength: &quot;Infinity&quot;,<br>        headers: {<br>          &#39;Content-Type&#39;: `multipart/form-data; boundary=${formData._boundary}`,<br>          Authorization: JWT<br>        }<br>      });<br>      console.log(res.data);<br>    } catch (error) {<br>      console.log(error);<br>    }<br>}</pre><p>The Asset created store on Pinata</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgKGSQ0jZnJJvu1APNn1PA.png" /></figure><h4>Generate variations or edits on certificate background</h4><p>utilizes the Pillow library to dynamically edit a certificate by adding personalized information such as the recipient’s name, logo, and date. Below is a summarized explanation of the script:</p><figure><img alt="Edits on certificate background" src="https://cdn-images-1.medium.com/max/1024/1*-IArkvfoPfnA7Iwqe5CZGA.png" /><figcaption>Edits on certificate background</figcaption></figure><h4>Build Web3 dApps</h4><h4>BackEnd</h4><p>Dappflow Explorer explore on-chain data by connecting to any public node. All networks are supported including your localhost sandbox environment.</p><p>Easy way to manage your assets. Just connect your wallet to Create, Opt-in, Send, Modify, Freeze, UnFreeze assets. Mint ARC3, ARC69 NFT’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5izhw4tkKHdmRFo3oMpO6Q.png" /></figure><p>KMD Accounts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bO2Av_dqOtFo4fgR5DHPmQ.png" /></figure><p>Front End</p><h3>Lesson Learned</h3><ul><li>Integrating diverse technologies, such as REST, GraphQL, and blockchain nodes, requires careful consideration of interoperability. Standardizing communication protocols enhances seamless connectivity.</li><li>Building both frontend and backend systems demands comprehensive full-stack expertise.</li><li>Connecting with blockchain nodes involves intricate processes. Understanding blockchain dynamics and transaction handling is essential to mitigate integration complexities.</li><li>Connecting with distributed file systems demands a nuanced understanding of decentralized storage. Addressing data availability and redundancy is critical for robust file system integration.</li><li>Extensive unit testing is imperative for reliable APIs and dApps. Implementing advanced CI/CD pipelines ensures continuous testing and deployment, enhancing overall project stability and agility</li></ul><h3>Future Work</h3><ul><li>Explore the possibility of incorporating up gradable smart contracts to facilitate seamless enhancements and feature additions. This ensures adaptability to future requirements without disrupting existing functionalities.</li><li>Develop dedicated mobile applications to extend the accessibility of the certificate distribution system. This enables trainees to interact with NFTs and smart contracts conveniently from mobile devices.<br>Advanced Certificate Verification</li><li>Implement advanced mechanisms for certificate verification, possibly leveraging decentralized identity solutions. This enhances the overall security and authenticity of the certificates issued on the Algorand Blockchain.</li><li>Enhance NFT attributes to accommodate dynamic information related to trainees’ achievements and participation. This allows for more detailed and customizable representations within the NFTs, reflecting a broader range of accomplishments.</li><li>Introduce features that promote community engagement, such as forums, discussion boards, or collaborative spaces within the dApp. This fosters a sense of community among certificate holders, facilitating knowledge exchange and collaboration.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b18a1faa5f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redash chatbot add-on: LLM based chatbot for Advanced Data Analytics, Visualisation, and Automated…]]></title>
            <link>https://medium.com/@elias.assamnew/redash-chatbot-add-on-llm-based-chatbot-for-advanced-data-analytics-visualisation-and-automated-d598f0b4e546?source=rss-bd07403bb0c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d598f0b4e546</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[sql-generation]]></category>
            <category><![CDATA[redash]]></category>
            <dc:creator><![CDATA[Elias Assamnew]]></dc:creator>
            <pubDate>Sat, 06 Jan 2024 19:56:05 GMT</pubDate>
            <atom:updated>2024-01-10T00:24:36.608Z</atom:updated>
            <content:encoded><![CDATA[<h3>Redash chatbot add-on: LLM based chatbot for Advanced Data Analytics, Visualisation, and Automated Insight Extraction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ff3bjkR_JOYsDbb8.png" /></figure><h3>The business objective of the project</h3><p>The primary business goal centers on the development of a Redash chat add-on that goes beyond facilitating natural language queries, aspiring to transform into an expansive Business Intelligence (BI) platform. This strategic evolution aims to democratize data analytics, ensuring accessibility for team members regardless of their technical expertise. The envisioned BI platform extends its utility by incorporating advanced analytics features, such as predictive modeling and anomaly detection, fostering a collaborative environment through shared dashboards and automated report generation. Emphasizing data governance, compliance, and user support, the platform seeks to empower users with a comprehensive suite of tools for insightful data exploration, ensuring that the organization’s data-driven decision-making processes are both sophisticated and user-friendly.</p><p>These features aim to enhance the analytical capabilities of team members and elevate the overall reliability of insights derived from the platform. Scalability and performance optimization form the bedrock, positioning the BI platform to accommodate evolving data landscapes and increasing user demands. By combining these strategic objectives, the project aspires to create a resilient, versatile, and impactful BI platform that aligns with the organization’s long-term data analysis and business intelligence goals.</p><h3>The project design</h3><ol><li>Frontend Development: Redash Chat Add-On</li></ol><ul><li>Design and implement a user-friendly chat interface within Redash for natural language queries.</li><li>Enable seamless conversation in a question-and-answer format.</li><li>Integrate the chat add-on with Redash dashboards.</li></ul><p>2. Backend Development: Intelligence Backend</p><ul><li>Implement Natural Language Processing (NLP) to interpret user queries.</li><li>Develop logic to translate queries into one of the following:</li><li>Summary of visualizations in the current dashboard.</li><li>Insights about data returned by existing SQL queries.</li><li>Auto-generate SQL queries and visualizations.</li><li>Auto-generate new Redash dashboards from SQL queries and associated visualizations.</li><li>Create an API that facilitates communication between the frontend and backend.</li></ul><p>3. Democratizing Data Analytics:</p><ul><li>Focus on making data analytics accessible to team members with non-technical backgrounds.</li><li>Use language models (LLMs) to automatically generate complex SQL queries from natural language input.</li></ul><p>4. Enhancing BI Dashboards:</p><ul><li>Transform data from multiple systems (YouTube, Slack, Gmeet) into actionable insights.</li><li>Drive strategic decisions by providing monitoring capabilities and understanding digital content consumption trends.</li></ul><p>5. Streamlining Analytical Processes:</p><ul><li>Streamline data exploration by integrating the chat add-on with Redash, making the process more accessible and efficient.</li></ul><h3>Expected Impact:</h3><ul><li>Enable team members with varying technical backgrounds to extract and visualize data effortlessly.</li><li>Streamline data exploration and make it more accessible, leading to increased efficiency in decision-making processes.</li><li>Strategic Decision-Making:</li><li>Provide actionable insights from BI dashboards to drive strategic decisions and gain a competitive edge.</li></ul><p>By addressing these key areas, the project aims to revolutionize data analytics within the organization and empower team members to gain valuable insights from diverse data sources through a user-friendly and efficient Redash chat add-on.</p><h3>The tech-stack used</h3><h4>Redash</h4><p>Redash stands out as a versatile open-source business intelligence and data visualization platform, providing a comprehensive solution for users to connect with various data sources seamlessly. Supporting a broad spectrum of databases, including relational, NoSQL, and cloud-based warehouses, Redash ensures a unified analytics experience. Users can craft SQL queries or utilize a query builder to extract insights from diverse sources. The platform’s strength lies in its visualization options, offering charts, graphs, tables, and geospatial visualizations to cater to different data representation needs.</p><p>Creating interactive dashboards is a highlight of Redash, facilitating the organization and presentation of visualizations for a holistic view of data. Dashboards can be shared and embedded, fostering collaboration and knowledge dissemination within teams. Redash goes beyond static reporting with features like scheduled reports and alerting. Users can schedule automatic report generation at intervals and set up alerts based on specific data conditions, ensuring stakeholders stay informed in real-time.</p><p>Robust user authentication and authorization mechanisms in Redash help administrators control access to data sources, dashboards, and features based on user roles, prioritizing data security and compliance. The platform exposes a RESTful API, enabling programmatic interactions for automation, integration, and custom application development. Redash’s extensibility allows users to create custom visualizations and integrate additional functionalities through plugins, enhancing adaptability to specific business needs.</p><p>Redash has cultivated an active and supportive community, offering a collaborative space for users and contributors. Deployment options include on-premises, cloud, and a managed service called Redash Cloud. Its user-friendly interface, integration capabilities, and community-driven development contribute to Redash’s popularity in the business intelligence and data analytics domain, empowering organizations to explore, visualize, and share insights derived from their data effectively.</p><h4>Chatbot Framework</h4><h4>React for Frontend</h4><p>React is a powerful JavaScript library widely used for building user interfaces (UI). Its key feature is its component-based architecture, breaking down UIs into reusable and modular components. React employs a virtual DOM, optimizing rendering by selectively updating the necessary parts rather than the entire DOM, resulting in enhanced performance. With a declarative syntax and JSX, React provides a readable and maintainable code structure. The one-way data binding ensures a clear and predictable flow of data in applications, simplifying debugging and state management. React benefits from a vast ecosystem and an active community, offering additional tools like React Router, Redux for state management, and Jest for testing.</p><h4>Flask for Backend</h4><p>Flask, a web framework built in Python, serves as an excellent choice for backend development. Known for its micro-framework design, Flask provides the essential components needed to get a web application up and running, allowing developers the flexibility to choose additional components based on project requirements. Leveraging the Jinja2 templating engine, Flask supports the dynamic generation of HTML and other markup languages, facilitating the integration of Python code into HTML templates. Its reliance on Werkzeug, a WSGI toolkit, contributes to functionalities like request and response handling, routing, and more. Flask is adept at building RESTful APIs, accommodating various HTTP methods for scalable and clean API design. Its extensibility allows developers to integrate preferred tools for tasks such as database integration and authentication. With a supportive community and comprehensive documentation, Flask provides a flexible and efficient solution for backend development. In combination with React on the frontend, this duo creates a well-rounded and adaptable full-stack development environment.</p><h4>Language Model: GPT-3.5 Turbo</h4><p>GPT-3.5 Turbo, developed by OpenAI, is a powerful language model renowned for its natural language processing capabilities. With a focus on natural language understanding (NLU), the model demonstrates a remarkable ability to comprehend context and generate coherent, contextually relevant responses that closely mimic human fluency. Beyond general text generation, GPT-3.5 Turbo serves as a versatile tool for various applications. It excels in building conversational agents and chatbots, providing dynamic interactions with users. Additionally, the model proves adept at code generation, assisting developers by generating code snippets in multiple programming languages. Specifically in the realm of SQL generation, GPT-3.5 Turbo can interpret natural language prompts describing desired data or querying conditions, and seamlessly generate corresponding SQL queries. This functionality streamlines database interactions for developers and data analysts, offering a more intuitive and efficient way to work with structured data. Its capabilities extend to content summarization, language translation, creative writing assistance, and even custom task automation, making GPT-3.5 Turbo a versatile and invaluable tool in natural language understanding and generation tasks across diverse domains.</p><h4>Redash’s API Integration</h4><p>API integration between your backend server and Redash facilitates seamless communication and enhances the capabilities of your data analytics and visualization system. By leveraging Redash’s API, you empower your backend to programmatically interact with the Redash platform, enabling a range of automated actions and dynamic data manipulations. This integration empowers your application to execute queries on Redash, retrieve results, and further process or present the data as needed. For example, your backend server can initiate queries to Redash, dynamically adjust parameters based on user inputs or system conditions, and retrieve real-time insights. This not only streamlines the flow of information but also allows your application to stay synchronized with the latest data available in your Redash dashboards. The API integration ensures a cohesive connection between your backend logic and the analytical capabilities of Redash, fostering a more responsive, dynamic, and data-driven user experience within your application. Moreover, this integration lays the foundation for automating routine tasks, enhancing the efficiency of the data analytics workflow, and promoting a more robust and integrated analytics solution for your users.</p><h4>Containerization: Docker</h4><p>Leveraging Docker for containerization in your data analytics and visualization system provides a powerful and flexible infrastructure solution. Docker allows you to encapsulate your application and its dependencies into lightweight, portable containers, ensuring consistency across various environments. By encapsulating your Redash application and its dependencies within Docker containers, you create a standardized environment that is easily reproducible, reducing potential deployment issues related to dependencies and configurations. This portability ensures a smoother deployment process and facilitates scalability as your system evolves.</p><p>Furthermore, Docker enables efficient resource utilization by isolating applications into containers, preventing conflicts between different components of your system. This isolation enhances security and simplifies maintenance, as updates or modifications to one container do not impact others. Additionally, Docker simplifies version control and collaboration, as developers can work with the same containerized environment regardless of their local setup.</p><p>For orchestration, Docker can be paired with a tool like Kubernetes, providing a robust solution for automating the deployment, scaling, and management of containerized applications. Kubernetes orchestrates the deployment and scaling of Docker containers, ensuring high availability, fault tolerance, and efficient resource utilization. With Kubernetes, you can easily scale your Redash application based on demand, distribute workloads across multiple containers, and handle automatic load balancing.</p><p>In summary, using Docker for containerization offers a streamlined and consistent environment for deploying your Redash application, while optional orchestration with Kubernetes adds scalability and automation. Together, these technologies contribute to a more reliable, scalable, and maintainable infrastructure for your data analytics and visualization system.</p><h4>LangChain</h4><p>LangChain is a comprehensive framework designed for developing context-aware applications powered by language models, emphasizing the integration of reasoning capabilities within applications. The central concept within LangChain is the use of agents, where a language model serves as a reasoning engine to dynamically determine a sequence of actions and their order, as opposed to the traditional hardcoded approach in chains. Agents, unlike chains, leverage language models to intelligently select actions, enhancing the adaptability and context-awareness of applications.</p><p>The framework provides key components for efficient agent development. The AgentAction and AgentFinish classes define the actions an agent should take and the final results, respectively. Intermediate Steps represent prior agent actions and outputs during the current run. The Agent itself is responsible for deciding the next step, powered by a language model, a prompt, and an output parser. Different agents may employ distinct prompting styles, input encoding, and output parsing methods. Agent Inputs and Outputs are structured as key-value mappings, with AgentExecutor serving as the runtime for an agent. AgentExecutor manages complexities like non-existent tools, tool errors, and agent-produced output parsing, while also handling logging and observability at different stages of the decision-making process and tool calls. This multifaceted framework empowers developers to create intelligent and dynamic applications that leverage language models for reasoning and decision-making.</p><h3>The methodologies followed</h3><h4>1. Environment Setup:</h4><p>Set up development, testing, and production environments, ensuring compatibility with Redash and other dependencies.</p><ul><li>Redash Local development <a href="https://github.com/getredash/redash/wiki/Local-development-setup">setup</a> can be used to setup the environment</li></ul><h4>2. Frontend Development:</h4><p>Design and implement the Redash chat add-on in the frontend, focusing on a user-friendly interface for natural language queries.</p><p>The frontend development of the Redash chat add-on is accomplished using React, a popular JavaScript library for building user interfaces. The primary goal is to create an intuitive and interactive chat interface within Redash, enabling users to seamlessly interact with the data visualization assistant using natural language queries. The following codes can be used to install dependencies for react.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*QfCWcNCqcPwAoMnX31-g_Q.png" /></figure><h4>3. Backend Development:</h4><ul><li>Implement the intelligence backend, integrating OpenAI for natural language processing and creating connectors to fetch data from connected databases.</li></ul><h4>4. Natural Language Processing (NLP):</h4><ul><li>Implement NLP algorithms to interpret user queries and translate them into actionable commands for the backend.</li></ul><h4>5. SQL Query Generation:</h4><ul><li>Develop logic to generate SQL queries based on user input, considering both existing queries and auto-generated ones.</li></ul><h4>6. Dashboard Integration:</h4><ul><li>Integrate the chat add-on seamlessly with Redash dashboards, allowing users to interact with visualizations and data.</li></ul><h3>The challenges faced</h3><ul><li>NLP Accuracy: Achieving precise natural language understanding poses challenges due to ambiguities and context nuances.</li><li>Security, Scalability, Local Deployment, and OpenAI API Integration: Ensuring robust security measures for handling sensitive data, scalability to accommodate a growing user base, addressing local deployment challenges, and integrating the OpenAI API seamlessly contribute to the overall complexity of the project.</li><li>Integration Complexity: Seamless integration with Redash and BI platforms requires addressing differences in data formats, authentication, and query workflows.</li><li>User Experience Design: Balancing simplicity and functionality is crucial for designing an intuitive chat interface that caters to users with varying technical backgrounds.</li><li>Autonomous Knowledge Discovery: Developing algorithms for autonomously identifying meaningful insights involves careful consideration of data structures and patterns.</li></ul><h3>Result Obtained</h3><h4>Redash Local development setup</h4><p>For a detailed, step-by-step guide, refer to the comprehensive instructions provided in this <a href="https://github.com/getredash/redash/wiki/Local-development-setup">link</a>. Setting up the Redash development requires the establishment of a robust local environment as the first crucial step. Regardless of whether one is working on Linux or Windows WSL2, this involves the installation of essential packages like Docker, NodeJS, and Yarn. Following the cloning of the Redash source code, installation of dependencies, and configuration of local environment variables, developers can seamlessly compile the front end and create a local Redash Docker image. The process of starting Redash locally becomes effortless, and developers can access the web interface at <a href="http://localhost:5001/">http://localhost:5001</a>, serving as the gateway to further configuration. The subsequent Python setup for backend development ensures compatibility with a diverse range of data sources. This comprehensive overview sets the stage for a streamlined and effective Redash development journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OA2QOhNKwZ5HAPMwh4_gRQ.png" /></figure><h3>The Dataset</h3><p>Our YouTube channel has a lot of valuable information. We have details about each video, like its title and when it was uploaded. We also keep track of how many people are watching our videos over time, and we pay attention to the comments people leave.</p><p>We transcribe the spoken words in our videos to help us understand what our content is about and improve our search engine ranking. We regularly check our data to see how well our channel is doing and to find ways to make our audience even happier.</p><p>In different folders, we organize our data into groups. Each group has three CSV files that help us learn more about our YouTube community. We look at things like where our viewers are from, their age, and whether they are new or returning viewers. This information helps us understand our audience and make better videos.</p><p>We also study technical details, like what devices and operating systems our viewers use. We look at gender, language preferences, and even how people find our channel. By understanding all these aspects, we paint a detailed picture of how our YouTube channel is doing and what our viewers like.</p><p>Schema prepared for each file as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BlAUrMM8FUCCAwAn" /><figcaption>Schema to load the data to postgres DB</figcaption></figure><h3>Chat-bot Integration into Redash</h3><p>Integrating a chatbot into a Redash dashboard involves a systematic approach combining React for the frontend, Flask for the backend, Less for CSS styling, and OpenAI’s language model (LLM) for natural language processing. The process begins with establishing a Flask backend server to handle communication and incorporating the OpenAI model for natural language understanding. On the frontend, a React component is developed within the Redash dashboard, providing users with a chat interface. Real-time communication is established between the React frontend and Flask backend, ensuring swift query processing through the OpenAI LLM. The integration is styled using Less for a visually appealing and cohesive look within the Redash environment. User input and responses are managed seamlessly, capturing queries, processing through the OpenAI model, and displaying results in the chat interface. Thorough testing and iteration precede the final deployment of the integrated solution to the production environment, enhancing user interactivity and leveraging OpenAI’s language capabilities within the Redash analytics platform.</p><p>In summary, the integration process encompasses backend setup, OpenAI LLM integration, React frontend development, real-time communication, styling with Less, and user input handling. The result is a cohesive and visually appealing chatbot interface seamlessly embedded within the Redash dashboard, offering users a dynamic and interactive experience enriched by natural language processing capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9obM3RQAgWjPa_GW" /></figure><h3>SQL Generation</h3><p>Practical implementation of leveraging OpenAI’s GPT-3.5 Turbo model for generating SQL queries based on user questions within the context of a PostgreSQL database. By integrating natural language processing capabilities, users can madeto interact with the database using conversational queries. The systematic approach involves establishing a connection to the database, extracting schema information, and constructing prompts for the language model. The OpenAI chat model then generates suggested SQL queries, which are further processed to extract the relevant information for user interaction.</p><p>This script belowexemplifies the potential of combining advanced language models with database interactions, offering a glimpse into the possibilities of creating intelligent assistants capable of understanding and responding to natural language queries in the domain of data retrieval. As natural language processing technologies continue to advance, such integrations contribute to the development of user-friendly interfaces, making data exploration and query generation more accessible for a broader audience.</p><pre>import os<br>import psycopg2<br>from dotenv import load_dotenv<br>from openai import OpenAI<br>def generate_sql_query(question):<br>load_dotenv()<br>client = OpenAI(api_key=os.getenv(&#39;OPENAI_API_KEY&#39;))<br>conn = psycopg2.connect(<br>host=&quot;redash-postgres-1&quot;,<br>database=&quot;youtube_data&quot;,<br>user=&quot;postgres&quot;,<br>password=&quot;postgres&quot;,<br>port=&quot;5432&quot;<br>)<br>cursor = conn.cursor()<br>try:<br>cursor.execute(&quot;SELECT table_name FROM information_schema.tables WHERE table_schema = &#39;public&#39;&quot;)<br>table_names = [row[0] for row in cursor.fetchall()]<br>schemas = {}<br>for table_name in table_names:<br>cursor.execute(f&quot;SELECT column_name, data_type FROM information_schema.columns WHERE table_name = &#39;{table_name}&#39;&quot;)<br>schema_rows = cursor.fetchall()<br>schemas[table_name] = {row[0]: row[1] for row in schema_rows}<br>schemas_str = &#39;, &#39;.join(f&quot;{table_name}: {&#39;, &#39;.join(f&#39;{col_name} ({col_type})&#39; for col_name, col_type in schema.items())}&quot; for table_name, schema in schemas.items())<br>if question.lower() in [&#39;hi&#39;, &#39;hello&#39;, &#39;hey&#39;]:<br>return &quot;Hello! I&#39;m an AI assistant. I can help you generate SQL queries based on your questions.&quot;<br>elif question.lower() == &#39;what is your name?&#39;:<br>return &quot;My name is Query Generator.&quot;<br>elif question.lower() == &#39;what can you do?&#39;:<br>return &quot;I can help you generate SQL queries based on your questions.&quot;<br>prompt = f&quot;Retrieve data based on the question: {question}.&quot;<br>chat_completion = client.chat.completions.create(<br>model=&quot;gpt-3.5-turbo&quot;,<br>messages=[<br>{<br>&quot;role&quot;: &quot;system&quot;,<br>&quot;content&quot;: f&quot;You are a helpful assistant. The database has the following schemas: {schemas_str}.&quot;<br>},<br>{<br>&quot;role&quot;: &quot;user&quot;,<br>&quot;content&quot;: prompt<br>}<br>]<br>)<br>suggested_query = chat_completion.choices[0].message.content.strip()<br>try:<br>start_index = suggested_query.index(&quot;SELECT&quot;)<br>end_index = suggested_query.index(&quot;;&quot;) + 1<br>except ValueError:<br>sql_query = suggested_query<br>else:<br>sql_query = suggested_query[start_index:end_index]<br>answer = []<br>answer.append(suggested_query)<br>answer.append(sql_query)<br>return answer<br>finally:<br>cursor.close()<br>conn.close()<br>question = &quot;how can I get the operatig system that has a maximum view ?&quot;<br>sql_query = generate_sql_query(question)[1]<br>print(sql_query)</pre><p>and at the back end of the chat bot</p><pre>from flask import request, jsonify<br>from scripts.query_generator import generate_sql_query<br>from redash.handlers.base import (<br>    BaseResource<br>)<br># import os<br># from openai import OpenAI<br># VARIABLE_KEY = os.environ.get(&quot;OPENAI_API_KEY&quot;)<br># client = OpenAI(<br>#   api_key=VARIABLE_KEY<br># )<br><br>class ChatResource(BaseResource):<br>    def post(self):<br>        try:<br>            value = request.get_json()<br>            question = value.get(&#39;question&#39;)<br>            # completion = client.chat.completions.create(<br>            #     model=&quot;gpt-3.5-turbo&quot;,<br>            #     messages=[<br>            #         {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a redash visualization assistant, skilled in SQL queries and data visualization. You are only required to give answers for query and data visualization questions. If asked about a topic outside these two, make sure to respond that you have no information regarding that question. I am only here to help you with your query and data visualization questions. When asked to write queries, only provide the code without descriptions.&quot;},<br>            #         {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: question}<br>            #     ]<br>            # )<br>            # answer = completion.choices[0].message.content<br>            result = generate_sql_query(question)[0]<br>            answer = result[0] if isinstance(result, list) else result<br>            response_data = {&quot;answer&quot;: answer}<br>            return jsonify(response_data), 200<br>        except Exception as error:<br>            print(error)<br>            return jsonify({&quot;error&quot;: &quot;An error occurred&quot;}), 500</pre><p>And the result obtained is like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_qm2Jcm3A6hnrt31" /></figure><h3>Conclution</h3><p>The overarching project involving the integration of a Redash chat add-on, OpenAI’s language model, and data analytics capabilities presents a holistic solution to democratize data analytics within an organization. The initiative starts with the development of a Redash chat add-on, leveraging React for the frontend, Flask for the backend, and Less for CSS styling. This facilitates natural language queries and autonomous knowledge discovery, fostering a user-friendly and inclusive environment for team members with diverse technical backgrounds.</p><p>The integration of OpenAI’s language model enhances the chatbot’s capabilities, allowing for context-aware reasoning and dynamic responses to user queries. The backend API, adaptable for various data analysis and BI projects, provides long-term value by serving as a versatile tool within the organization.</p><p>The emphasis on comprehensive data analytics, as exemplified in the Python script for generating SQL queries, extends the project’s impact. The integration of natural language processing with database interactions showcases a practical application of advanced language models in data retrieval, contributing to the development of intelligent assistants capable of understanding and responding to nuanced user queries.</p><p>In conclusion, the project not only addresses immediate goals of enhancing Redash’s capabilities but also lays the foundation for a more inclusive and dynamic data analytics environment. The combined efforts of integrating user-friendly interfaces, advanced language models, and robust data analytics contribute to a comprehensive solution that empowers teams to extract meaningful insights and fosters a culture of data-driven decision-making within the organization.</p><h3>Lessons learned</h3><ul><li>Collaborative Teamwork and Communication: Working as a team introduces the challenge of collaborative teamwork and effective communication. Overcoming this challenge involves establishing clear roles, fostering open communication channels, and leveraging diverse skills to navigate the complexities of integrating multiple technologies seamlessly.</li><li>Balancing Flexibility and Complexity: Integrating multiple technologies, including Redash, React, Flask, and OpenAI’s language model, requires a careful balance between flexibility and complexity to ensure a seamless and effective system.</li><li>Adapting to Diverse Data Sources: Handling diverse data sources and schemas is a critical technical consideration. The project’s Python script showcases the importance of creating solutions that can dynamically adapt to different database structures.</li><li>Continuous Testing and Iteration: The project highlights the significance of continuous testing and iteration. Adapting to evolving technologies and user requirements ensures the reliability, performance, and long-term success of the integrated components.</li><li>Maintaining Flexibility for Emerging Challenges: The ability to iterate on the integration, address emerging challenges, and refine the user experience underscores the importance of maintaining flexibility in the technical approach. This adaptability contributes to the project’s resilience in the face of changing conditions.</li></ul><h3>Limitations:</h3><ol><li><strong>Scope of Natural Language Processing (NLP)</strong>: The current implementation of the chatbot’s natural language processing capabilities may have limitations in handling highly complex queries or nuanced language structures. Addressing this would require continuous improvement and refinement of the underlying NLP model.</li><li><strong>Data Source Compatibility:</strong> The Python script for SQL query generation assumes a specific structure in the PostgreSQL database. Adapting to diverse database structures or supporting multiple database types may pose challenges that need further consideration.</li></ol><h4>Future WOrk</h4><ol><li><strong>Intuitive Data Visualization</strong>: Integrate enhanced data visualization features within Redash to provide users with more intuitive and interactive ways to explore and interpret data. This could include additional chart types, real-time dashboards, and customizable visualization options.</li><li><strong>Enhanced User Training: </strong>Provide additional user training resources and documentation to empower team members with non-technical backgrounds to leverage the full potential of the Redash chat add-on and data analytics capabilities.</li><li>Predictive Analytics: Explore the integration of machine learning models within Redash to enable predictive analytics. This could involve forecasting trends, predicting user behavior, or anticipating future data patterns, providing valuable insights for decision-making.</li><li>Recommendation Systems: Implement machine learning algorithms to create personalized recommendation systems within the Redash dashboard. This can assist users in discovering relevant datasets, queries, or visualizations based on their historical interactions and preferences.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d598f0b4e546" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data warehouse tech stack with MySQL/PostgreSQL, DBT, Airflow]]></title>
            <link>https://medium.com/@elias.assamnew/data-warehouse-tech-stack-with-mysql-postgresql-dbt-airflow-730d1b0dcc9f?source=rss-bd07403bb0c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/730d1b0dcc9f</guid>
            <dc:creator><![CDATA[Elias Assamnew]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 18:37:38 GMT</pubDate>
            <atom:updated>2023-12-26T05:28:17.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QPdwKWF8fwIDUPQ-QbQ7w.png" /><figcaption>Data Warehouse pipeline with PostgreSQL, DBT, Airflow, and Redash</figcaption></figure><h3>Objective</h3><p>The primary objective of the project is to create a scalable data warehouse that hosts vehicle trajectory data extracted from swarm drones and static roadside cameras. This data will be utilized to improve traffic flow in the city and support various undisclosed projects initiated by the city traffic department. The scalable data warehouse aims to organize the data to facilitate efficient querying for downstream projects, ensuring that the collected data can be effectively harnessed for ongoing and future traffic management initiatives.</p><h3>Introduction</h3><p>Creating a scalable data warehouse for hosting vehicle trajectory data extracted from swarm drones and static roadside cameras is a crucial task for startup. Using the Extract Load Transform (ELT) framework with DBT will be instrumental in achieving this. The ELT framework allows for setting up transformation workflows on an as-needed basis, providing flexibility and adaptability to the city traffic department’s analytic engineers.</p><p>To ensure the scalability and efficiency of the data warehouse, it’s essential to design it with future needs in mind. The organization of the data should facilitate efficient querying for downstream projects. This involves structuring the data in a way that supports quick and effective retrieval, analysis, and utilization by various projects aimed at improving traffic flow and other undisclosed initiatives.</p><h3>Data Description</h3><p>The pNEUMA dataset provides naturalistic trajectories for approximately half a million vehicles. These trajectories were collected through a unique experiment that utilized a swarm of drones in the congested downtown area of Athens, Greece. Each file represents a specific combination of area, date, and time and is approximately 87MB in size. The trajectories were extracted from video frames recorded during the experiment. Resources such as <em>“</em><a href="https://github.com/JoachimLandtmeters/pNEUMA_mastersproject"><em>JoachimLandtmeters/pNEUMA_mastersproject</em></a><em>”</em> on GitHub offer tools for visualizing and analyzing the dataset, making it easier to explore this valuable resource. The dataset can access and download from <a href="https://zenodo.org/records/7426506">https://zenodo.org/records/7426506.</a></p><h3><strong>Methodology</strong></h3><p>Project Flow</p><ol><li>Data Extraction and Ingestion**</li></ol><ul><li>Apache Airflow schedules and triggers the extraction of vehicle trajectory data from swarm drones and static roadside cameras.</li><li>Extracted data is ingested into the data pipeline and stored in PostgreSQL.</li></ul><p>2. Data Transformation with dbt</p><ul><li>dbt processes and transforms the ingested data within PostgreSQL, applying business logic and structuring the data for downstream analytics.</li><li>Transformed data is stored back into PostgreSQL, ready for querying and analysis.</li></ul><p>3. Data Quality Checks**</p><ul><li>Apache Airflow triggers data quality checks to ensure the accuracy and completeness of the transformed data in PostgreSQL.</li><li>Any discrepancies or issues are logged for further investigation.</li></ul><p>4. Orchestration and Scheduling</p><ul><li>Apache Airflow orchestrates the entire data pipeline, scheduling tasks and workflows to ensure timely execution of data extraction, transformation, and quality checks.</li></ul><p>5. Visualization and Reporting</p><ul><li>Redash connects to PostgreSQL to create visualizations and dashboards based on the transformed data, providing insights into traffic flow patterns, congestion points, and other relevant metrics.</li></ul><p>Data Preparation</p><p>Each row in the dataset represents the data for a single vehicle. The first 10 columns of the dataset contain information such as the unique track ID, vehicle type, distance traveled, average speed, latitude, longitude, speed, longitudinal acceleration, lateral acceleration, and time. The first 4 columns provide details about the vehicle, while the subsequent 6 columns are repeated at regular time intervals (approximately every 4 seconds) to describe the vehicle’s trajectory. For instance, the latitude and longitude of the vehicle at specific times are captured in these repeating sets of 6 columns. Additionally, the speed is measured in kilometers per hour, longitudinal and lateral acceleration in meters per second squared, and time in seconds.</p><h3>Air flow</h3><ol><li>Fetch the docker-compose docker-compose.yaml It creates an <strong>airflow</strong> container</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*XRW3Ai8j2OO1hg-MP56-_Q.png" /></figure><p>2. Run docker-compose airflow-init and then docker-compose up in order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*hwsgi_UZ5Q_Z0ZB--5xmIg.png" /></figure><p>This will create and run around 7 images in airflow containers. A folder with the name ‘dags’ will be created and the scripts and the dags file are put in there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLkNLPnhBt9FndMA9gIGkw.png" /></figure><p>To access the airflow-webserver on a browser, you can use <strong><em>localhost:8080</em></strong></p><h3>dbt</h3><p>Install dbt-Postgres using pip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*TaO-5hVONw9bFCVHVLrmCA.png" /></figure><p>We will have folders like models, analysis, etc, and a file named <strong><em>dbt_project</em></strong>.<strong><em>yml</em></strong>.</p><h3><strong>Redash</strong></h3><p>Redash is installed using the docker-compose file downloaded from <a href="https://github.com/getredash/redash/blob/master/docker-compose.yml">https://github.com/getredash/redash/blob/master/docker-compose.yml</a>.</p><h3>Challenges Faced</h3><p>Resource Constraints: The Dockerized environment may face resource limitations, especially in terms of memory and CPU, which could impact the performance of Airflow, dbt, and PostgreSQL.</p><p>Container Orchestration Complexity: Managing multiple containers and services using Docker Compose requires careful orchestration and monitoring to ensure seamless operation and resource allocation.</p><p>Network Configuration: Configuring network connectivity and communication between containers and external services may introduce complexities, especially in distributed environments.</p><h3>What Can Be Improved with More Time?</h3><p>Advanced Analytics: Incorporating advanced analytics capabilities for predictive modeling and real-time insights to further improve traffic flow management.</p><p>Robust Monitoring: Developing comprehensive monitoring and alerting systems to track the performance and health of the tech stack components.</p><p>Continuous Optimization: Establishing processes for continuous optimization of the tech stack based on evolving business needs and technological advancements.</p><h3>Conclusion</h3><p>Emphasis on the continuous evolution and improvement of the tech stack to meet future challenges and opportunities.<br>This blog will provide insights into work flow in building scalable data warehouse, the challenges faced during the tech stack implementation, as well as valuable suggestions for future improvements that can enhance the effectiveness of the data-driven AI startup’s operations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=730d1b0dcc9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>