<?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 Yohanes Teshome Kebede on Medium]]></title>
        <description><![CDATA[Stories by Yohanes Teshome Kebede on Medium]]></description>
        <link>https://medium.com/@Yohanes213?source=rss-b0e5a4e1d5de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Nje7l-UxO-NKypbz6Ucarg.jpeg</url>
            <title>Stories by Yohanes Teshome Kebede on Medium</title>
            <link>https://medium.com/@Yohanes213?source=rss-b0e5a4e1d5de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:49:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Yohanes213/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[LangGraph + FastAPI + RAG + Airflow = Scalable Microservice AI Research Assistant]]></title>
            <link>https://medium.com/@Yohanes213/building-an-ai-powered-academic-research-assistant-a-deep-dive-into-architecture-and-209db178911e?source=rss-b0e5a4e1d5de------2</link>
            <guid isPermaLink="false">https://medium.com/p/209db178911e</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[pinecone]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[rag-pipeline]]></category>
            <dc:creator><![CDATA[Yohanes Teshome Kebede]]></dc:creator>
            <pubDate>Tue, 06 May 2025 09:24:29 GMT</pubDate>
            <atom:updated>2025-05-07T16:08:58.583Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an AI-Powered Academic Research Assistant: A Deep Dive into Architecture and Implementation</h3><h3>Introduction</h3><p>In this post, I’ll walk you through building a sophisticated AI-powered system that helps researchers explore and analyze academic papers. The system automatically scrapes papers from PubMed, processes them using state-of-the-art AI models, and provides intelligent responses through a modern web interface.</p><h3>System Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XinJJPWnqnSLZPtT0uEicQ.png" /><figcaption>System architecture</figcaption></figure><p>The system follows a microservices architecture with five main components:</p><ol><li>Frontend Service (Streamlit)</li><li>Paper Ingestion Service (FastAPI)</li><li>Vector Database Service (FastAPI + Pinecone)</li><li>Research Assistant Service (FastAPI + Gemini)</li><li>Airflow (Task Orchestration)</li></ol><p>Let’s dive deep into each component.</p><h3>1. Frontend Service (Port 8501)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LytxcQVOO-Q0Z6UM3iXFwA.png" /></figure><p>The frontend is built using Streamlit, providing a clean and intuitive interface for researchers. Key features include:</p><ul><li>Chat-based research assistant interface</li><li>Paper search functionality</li><li>System status monitoring</li></ul><p>The frontend communicates with other services through REST APIs, making it easy to maintain and scale.</p><h3>2. Paper Ingestion Service (Port 8000)</h3><p>This service is responsible for keeping our research database up-to-date. Here’s how it works:</p><pre>async def scrape_articles():<br>    logger.info(&quot;Starting article scraping&quot;)<br>    base_url = &#39;https://pubmed.ncbi.nlm.nih.gov/trending/?sort=date&amp;page=&#39;<br>    <br>    success_count = 0<br>    error_count = 0<br><br>    for page_number in range(1, 100):<br>        logger.info(f&quot;Processing page {page_number}&quot;)<br>        url = base_url + str(page_number)<br>        soup = extract_articles(url)<br>        articles = [parse_article_info(article) for article in soup]<br><br>        # Fetch additional details and send to vector DB<br>        for article in articles:<br>            if article and article[&quot;article_url&quot;]:<br>                details = fetch_article_details(article[&quot;article_url&quot;])<br>                article.update(details)<br>                <br>                if await check_article_exists(article[&quot;pmid&quot;]):<br>                    logger.info(f&quot;Article {article[&#39;pmid&#39;]} already exists in vector DB, skipping...&quot;)<br>                    break<br>                # Send to vector DB<br>                if await send_to_vector_db(article):<br>                    success_count += 1<br>                else:<br>                    error_count += 1<br><br>    return {    <br>        &quot;success_count&quot;: success_count,<br>        &quot;error_count&quot;: error_count<br>    }</pre><p>Key features:</p><ul><li>Automatic scraping of trending PubMed papers</li><li>Duplicate detection</li><li>Robust error handling</li><li>Integration with vector database</li></ul><h3>3. Vector Database Service (Port 5000)</h3><p>The vector database service uses Pinecone to store and retrieve paper embeddings efficiently. Here’s how it handles queries:</p><pre>@router.get(&quot;/query&quot;)<br>async def query_data(query: str, top_k: int = 5):<br>    results = index.search(<br>        namespace=index_name,<br>        query={&quot;inputs&quot;: {&quot;text&quot;: query}, &quot;top_k&quot;: top_k},<br>    )<br>    hits = results.result[&quot;hits&quot;]<br>    return [<br>        {<br>          &quot;id&quot;:    hit[&quot;_id&quot;],<br>          &quot;score&quot;: hit[&quot;_score&quot;],<br>          **hit[&quot;fields&quot;]<br>        }<br>        for hit in hits<br>    ]</pre><p>Key features:</p><ul><li>Semantic search capabilities</li><li>Efficient vector storage</li><li>Document deduplication</li><li>RESTful API interface</li></ul><h3>4. Research Assistant Service (Port 5001)</h3><p>The Research Assistant service is built using a sophisticated orchestration of components using LangGraph, which creates a directed graph for processing research queries. Here’s a detailed breakdown:</p><h4>State Management (state.py)</h4><pre>class State(BaseModel):<br>    messages: Annotated[List[AnyMessage], add_messages]<br>    query: str<br>    context: str<br>    search_results: str<br>    needs_search: bool<br>    top_k: int<br>    response: str</pre><p>The State class manages the entire flow’s state, including:</p><ul><li>Chat message history</li><li>Current query</li><li>Retrieved document context</li><li>Web search results</li><li>Search flags and parameters</li><li>Final response</li></ul><h4>Graph Architecture (graph.py)</h4><pre>def build_graph():<br>    graph = StateGraph(State)<br><br>    # Add all nodes<br>    graph.add_node(&quot;conversation_node&quot;, conversation_node)<br>    graph.add_node(&quot;retrieve_node&quot;, retrieve_node)<br>    graph.add_node(&quot;evaluate_node&quot;, evaluate_context_node)<br>    graph.add_node(&quot;web_search_node&quot;, web_search_node)<br>    graph.add_node(&quot;response_node&quot;, response_node)<br><br>    # Add edges with conditional routing<br>    graph.add_edge(START, &quot;conversation_node&quot;)<br>    graph.add_conditional_edges(<br>        &quot;conversation_node&quot;,<br>        lambda state: END if state.response else &quot;retrieve_node&quot;<br>    )<br>    graph.add_edge(&quot;retrieve_node&quot;, &quot;evaluate_node&quot;)<br>    graph.add_edge(&quot;evaluate_node&quot;, &quot;web_search_node&quot;)<br>    graph.add_edge(&quot;web_search_node&quot;, &quot;response_node&quot;)<br>    graph.add_edge(&quot;response_node&quot;, END)<br><br>    return graph.compile(checkpointer=memory)</pre><p>The graph defines the processing flow:</p><ol><li>Conversation analysis</li><li>Document retrieval</li><li>Context evaluation</li><li>Web search (if needed)</li><li>Response generation</li></ol><h4>Processing Nodes</h4><p><strong>Conversation Node (conversation.py)</strong></p><pre>def conversation_node(state: State) -&gt; dict:<br>    # Check if query is conversational or needs research<br>    prompt = f&quot;&quot;&quot;<br>    You are an AI assistant. Determine if the following query requires research/document retrieval or is just a conversational exchange.<br>    Respond with EXACTLY:<br>    - CONVERSATIONAL: for greetings, personal questions, or general chat<br>    - RESEARCH: for questions that need information from documents or research<br><br>    Query: {state.query}<br><br>    Decision:<br>    &quot;&quot;&quot;<br>    <br>    decision = llm.invoke([prompt])<br>    needs_retrieval = decision.content.strip() == &quot;RESEARCH&quot;<br>    <br>    if not needs_retrieval:<br>        # Handle conversational exchange directly<br>        chat_prompt = f&quot;&quot;&quot;<br>        You are a helpful and friendly AI assistant. Respond naturally to the user&#39;s message.<br>        Previous messages: {state.messages}<br>        Current message: {state.query}<br>        &quot;&quot;&quot;<br>        response = llm.invoke([chat_prompt])<br><br>        return {<br>            &quot;messages&quot;: [AIMessage(content=response.content)],<br>            &quot;response&quot;: response.content,<br>        }<br>    <br>    return {&quot;response&quot;: &quot;&quot;}</pre><p>This node acts as the initial gateway, determining whether the query needs research or is just conversational.</p><p><strong>Retrieve Node (retrieve.py)</strong></p><pre>def retrieve_node(state: State) -&gt; dict:<br>    docs = requests.get(<br>        &quot;http://vector-db:5000/query&quot;,<br>        params={&quot;query&quot;: state.query, &quot;top_k&quot;: state.top_k},<br>    ).json()<br>    <br>    # Convert documents to a formatted string<br>    context = &quot;&quot;<br>    if docs:<br>        context = &quot;\n\n&quot;.join([<br>            f&quot;Document {i+1}:\n&quot; +<br>            f&quot;Title: {doc.get(&#39;title&#39;, &#39;N/A&#39;)}\n&quot; +<br>            f&quot;Abstract: {doc.get(&#39;abstract&#39;, &#39;N/A&#39;)}\n&quot; +<br>            f&quot;URL: {doc.get(&#39;article_url&#39;, &#39;N/A&#39;)}&quot;<br>            for i, doc in enumerate(docs)<br>        ])<br><br>    return {<br>        &quot;context&quot;: context,<br>        &quot;messages&quot;: state.messages<br>    }</pre><p>Handles document retrieval from the vector database, formatting the results for context.</p><p><strong>Evaluate Node (evaluate.py)</strong></p><pre>def evaluate_context_node(state: State) -&gt; dict:<br>    if state.needs_search:<br>        return {&quot;needs_search&quot;: True}<br><br>    prompt = f&quot;&quot;&quot;<br>        You are an assistant. Given the context and the user question, decide whether we need live web information to answer.<br>        Respond with EXACTLY NEED_MORE_INFO or SUFFICIENT.<br><br>        Context:<br>        {state.context}<br><br>        Question:<br>        {state.query}<br><br>        Decision:<br>        &quot;&quot;&quot;<br>    resp = llm.invoke([prompt])<br>    decision = resp.content.strip()<br>    return {&quot;needs_search&quot;: decision == &quot;NEED_MORE_INFO&quot;}</pre><p>Determines if additional web search is needed based on the retrieved context.</p><p><strong>Web Search Node (web_search.py)</strong></p><pre>def web_search_node(state: State) -&gt; dict:<br>    if state.needs_search:<br>        search_results = search_tool.invoke(state.query)<br>        additional_context = &quot;\n&quot;.join([f&quot;Source: {result[&#39;url&#39;]}\nContent: {result[&#39;content&#39;]}\n&quot; for result in search_results[&quot;results&quot;]])<br>        return {&quot;search_results&quot;: additional_context}<br>    return {&quot;search_results&quot;: &quot;&quot;}</pre><p>Performs web searches using Tavily when additional information is needed.</p><p><strong>Response Node (response.py)</strong></p><pre>def response_node(state: State) -&gt; dict:<br>    answer_prompt = f&quot;&quot;&quot;<br>    You are a helpful assistant. Answer the question using ALL the information provided in the context below.<br>    You must consider and synthesize information from BOTH retrieved documents and web search results when available.<br><br>    Retrived_context:<br>    {state.context}<br><br>    Web_search_results:<br>    {state.search_results}<br><br>    Question:<br>    {state.query}<br><br>    Instructions:<br>    1. Analyze ALL provided information from both retrieved documents and web search results<br>    2. Synthesize a comprehensive answer that combines relevant information from all sources<br>    3. If there are source URLs in the context, include relevant ones in your response<br>    4. Clearly indicate when you&#39;re drawing information from retrieved documents vs web search results<br>    <br>    Answer:<br>    &quot;&quot;&quot;<br>    gen = llm.invoke([answer_prompt])<br>    msg = gen[0] if isinstance(gen, list) else gen<br><br>    return {<br>        &quot;messages&quot;: [AIMessage(content=msg.content)],<br>        &quot;response&quot;: msg.content<br>    }</pre><p>Generates the final response by synthesizing information from all sources.</p><h4>Configuration (config.py)</h4><pre>llm = ChatGoogleGenerativeAI(<br>    model=&quot;gemini-2.0-flash-001&quot;,<br>    temperature=0,<br>    max_retries=2,<br>)<br><br>search_tool = TavilySearch(<br>    max_results=2,<br>)</pre><p>Configures:</p><ul><li>Google’s Gemini model for LLM operations</li><li>Tavily for web searches</li><li>Environment variables and API keys</li></ul><h4>FastAPI Integration (main.py)</h4><pre>@app.post(&quot;/response&quot;)<br>def get_response(query: str, top_k: int = 1, needs_search: bool = False):<br>    result = graph.invoke(<br>        {<br>            &quot;messages&quot;: [HumanMessage(content=query)],<br>            &quot;query&quot;: query,<br>            &quot;top_k&quot;: top_k,<br>            &quot;search_results&quot;: &quot;&quot;,<br>        },<br>        config=config<br>    )</pre><p>Exposes the research assistant through a REST API, managing:</p><ul><li>Request handling</li><li>Graph execution</li><li>Response delivery</li></ul><h4>Memory Management</h4><pre>memory = InMemorySaver()<br>graph = graph.compile(checkpointer=memory)</pre><p>Uses LangGraph’s InMemorySaver for:</p><ul><li>Maintaining conversation state</li><li>Checkpointing graph execution</li><li>Managing thread-specific configurations</li></ul><h3>Flow Example</h3><ol><li>User sends query: “What is the latest research regarding hyperbaric oxygen treatments (HBOTs)?”</li><li>conversation_node identifies it as a research query</li><li>retrieve_node fetches relevant papers from vector DB</li><li>evaluate_node determines if web search is needed</li><li>web_search_node gets latest information (if needed)</li><li>response_node synthesizes information and generates response</li></ol><p>This architecture provides:</p><ul><li>Modular and maintainable code</li><li>Clear separation of concerns</li><li>Flexible processing pipeline</li><li>Efficient state management</li><li>Scalable deployment options</li></ul><p>The use of LangGraph allows for complex orchestration of AI components while maintaining clean, maintainable code and providing robust error handling and state management.</p><h3>5. Airflow Integration (Port 8080)</h3><p>Airflow orchestrates the entire data pipeline:</p><ul><li>Schedules weekly paper ingestion</li><li>Monitors task execution</li><li>Provides a dashboard for pipeline management</li></ul><h3>Deployment and Infrastructure</h3><p>The entire system is containerized using Docker, making it easy to deploy and scale. Here’s a snippet from the docker-compose.yml:</p><pre>services:<br>  postgres:<br>    container_name: postgres<br>    image: postgres:13<br>    environment:<br>      POSTGRES_USER: airflow<br>      POSTGRES_PASSWORD: airflow<br>      POSTGRES_DB: airflow<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;pg_isready&quot;, &quot;-U&quot;, &quot;airflow&quot;]<br>      interval: 5s<br>      retries: 5<br>    restart: always<br><br>  airflow-init:<br>    &lt;&lt;: *airflow-common<br>    container_name: airflow-init<br>    entrypoint: /bin/bash<br>    command: -c &quot;airflow db init &amp;&amp; airflow users create --username admin --password admin --firstname Anonymous --lastname Admin --role Admin --email admin@example.com&quot;<br>  airflow-webserver:<br>    &lt;&lt;: *airflow-common<br>    container_name: airflow-webserver<br>    command: webserver<br>    ports:<br>      - &quot;8080:8080&quot;<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;http://localhost:8080/health&quot;]<br>      interval: 10s<br>      timeout: 10s<br>      retries: 5<br>    depends_on:<br>      airflow-init:<br>        condition: service_completed_successfully<br>    restart: always<br><br>  airflow-scheduler:<br>    &lt;&lt;: *airflow-common<br>    container_name: airflow-scheduler<br>    command: scheduler<br>    depends_on:<br>      airflow-init:<br>        condition: service_completed_successfully<br>    restart: always<br><br>  paper-ingestion:<br>    container_name: paper-ingestion<br>    build:<br>      context: ./paper_ingestion<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;8000:8000&quot;<br>    volumes:<br>      - ./paper_ingestion:/app<br>    environment:<br>      - VECTOR_DB_URL=http://vector-db:5000<br>    depends_on:<br>      - airflow-webserver<br>      - vector-db<br>    restart: always<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;http://localhost:8000/health&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 3<br><br>  vector-db:<br>    container_name: vector-db<br>    build:<br>      context: ./vector_db<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;5000:5000&quot;<br>    volumes:<br>      - ./vector_db:/app<br>    env_file:<br>      - ./vector_db/.env<br>    environment:<br>      - PINECONE_API_KEY<br>    restart: always<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;http://localhost:5000/health&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 3<br><br>  research-assistant:<br>    container_name: research-assistant<br>    build:<br>      context: ./research_assistant<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;5001:5001&quot;<br>    volumes:<br>      - ./research_assistant:/app<br>    environment:<br>      - VECTOR_DB_URL=http://vector-db:5000<br>    depends_on:<br>      - paper-ingestion<br>      - vector-db<br>    restart: always<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;http://localhost:5001/health&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 3<br><br>  frontend:<br>    container_name: frontend<br>    build:<br>      context: ./frontend<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;8501:8501&quot;<br>    volumes:<br>      - ./frontend:/app<br>    environment:<br>      - RESEARCH_ASSISTANT_URL=http://research-assistant:5001<br>      - PAPER_INGESTION_URL=http://paper-ingestion:8000<br>      - VECTOR_DB_URL=http://vector-db:5000<br>    depends_on:<br>      - research-assistant<br>      - paper-ingestion<br>      - vector-db<br>    restart: always<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;http://localhost:8501/_stcore/health&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 3</pre><h3>Security and API Management</h3><p>The system uses environment variables for sensitive information:</p><ul><li>Pinecone API key</li><li>Google API key (Gemini)</li><li>Tavily API key</li><li>LangSmith API key</li></ul><h3>Monitoring and Debugging</h3><p>The system includes comprehensive monitoring:</p><ul><li>Health check endpoints for all services</li><li>LangSmith integration for LLM monitoring</li><li>Airflow dashboard for pipeline monitoring</li><li>Docker health checks</li></ul><h3>Future Improvements</h3><p>Potential enhancements include:</p><ol><li>Enhanced research agent capabilities</li><li>Support for additional academic databases</li><li>Advanced visualization features</li><li>User authentication and personalization</li><li>Citation management</li></ol><h3>Conclusion</h3><p>This AI-powered academic research assistant demonstrates how modern AI technologies can be combined to create powerful tools for researchers. The microservices architecture ensures scalability and maintainability, while the use of cutting-edge AI models provides intelligent research assistance.</p><p>The complete code is available on GitHub, and you can deploy it using Docker Compose. The system is designed to be easily extensible, allowing for future enhancements and customizations.</p><h4><strong>Project Link</strong>: <a href="https://github.com/Yohanes213/Academic-Research-Assistant">Academic-Research-Assistant</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=209db178911e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic Image and Text Alignment: Automated Storyboard Synthesis for Digital Advertising]]></title>
            <link>https://medium.com/@Yohanes213/semantic-image-and-text-alignment-automated-storyboard-synthesis-for-digital-advertising-7ce452067d71?source=rss-b0e5a4e1d5de------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ce452067d71</guid>
            <category><![CDATA[autogen]]></category>
            <category><![CDATA[storyboard]]></category>
            <category><![CDATA[image-compositing]]></category>
            <dc:creator><![CDATA[Yohanes Teshome Kebede]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 17:01:27 GMT</pubDate>
            <atom:updated>2024-07-26T14:32:36.334Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUMv1WwV7MFJyynq0WykzQ.png" /><figcaption>Coca Cola Storyboard</figcaption></figure><h4>Introduction</h4><p>Recent advancements in machine learning, natural language processing, and computer vision, powered by Large Language Models (LLMs), are revolutionizing digital capabilities. These technologies enable the intricate processing and interpretation of data, translating complex ideas into dynamic visual content. This fusion bridges the gap between textual concepts and compelling storytelling, simplifying the creation of detailed, engaging visuals.</p><h4>Business Objective</h4><p>At Adludio, a leader in mobile advertising, leverages these cutting-edge technologies to transform textual ad descriptions into detailed storyboards. This innovation streamlines campaign ideation, enhancing creativity and efficiency while ensuring maximum engagement through interactive, targeted ads. The goal is to automate the end-to-end advertising process, reducing turnaround times from weeks to days using advanced machine learning algorithms. This automation will expedite ideation and execution, allowing clients to swiftly launch impactful campaigns with minimal time and resources.</p><h4>Project Overview</h4><p>In this project, I utilized two agents: one for image composition and one for critique. The goal was to create an automated system capable of generating and evaluating digital advertisements. Despite being a relatively new and challenging area, I experimented with various methods to achieve this. This blog chronicles my experience in building and refining these agents, highlighting the challenges and learning moments throughout the process.</p><h4>Exploratory Data Analysis (EDA)</h4><p>The project commenced with a thorough exploratory data analysis (EDA) of the provided datasets, emphasizing the images, concept descriptions, and associated metadata. Key steps included:</p><ul><li><strong>Distribution Analysis:</strong> I analyzed the distributions of Engagement Rate (ER) and Click-Through Rate (CTR) to understand the overall performance metrics of the advertisements.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*2lvK9GrJVYLldjRA5mvdCA.png" /><figcaption>Distribution of ER and CTR</figcaption></figure><ul><li><strong>Boxplot Analysis:</strong> Boxplots were utilized to identify and visualize outliers in the data, providing a clearer understanding of variability and extreme values.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*fZjR0D6ITluKL07h5rFkNA.png" /><figcaption>Boxplot of ER and CTR</figcaption></figure><ul><li><strong>Creative Assets Composition:</strong> To gain insights into the composition of creative assets, I visualized the top 10 categories of assets based on the concepts file. This helped in understanding the prevalent themes and elements in the ads.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*HImNlxoUU1oWO5b2UVV-3g.png" /><figcaption>Top 10 Category</figcaption></figure><ul><li><strong>Scatterplot Analysis:</strong> A scatterplot was created to examine the relationship between ER and CTR, highlighting any potential correlations or trends between these two important metrics.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*eQnj-DC0YdBp_b2mtbUICg.png" /><figcaption>The relationship between CTR and ER</figcaption></figure><p>These analyses provided a solid foundation for subsequent steps, offering valuable insights into the dataset’s structure and characteristics.</p><h4>Autogen Agents</h4><p>In this project, I utilized AutoGen with two specialized agents to streamline the process of composing and evaluating advertisement images:</p><p><strong>Image Composition Agent</strong></p><p>This agent is responsible for generating the advertisement images by combining various components provided by the user. The agent calls the combine_images_grid function, which overlays multiple images onto a base image according to a specified 3x3 grid system. Here&#39;s a breakdown of the function:</p><pre>import cv2<br>import matplotlib.pyplot as plt<br><br>def resize_to_fit(image, max_height, max_width):<br>    &quot;&quot;&quot;<br>    Resize an image to fit within the given dimensions while maintaining aspect ratio.<br><br>    Parameters:<br>    image (np.ndarray): The image to resize.<br>    max_height (int): The maximum height of the resized image.<br>    max_width (int): The maximum width of the resized image.<br><br>    Returns:<br>    np.ndarray: The resized image.<br>    &quot;&quot;&quot;<br>    h, w = image.shape[:2]<br>    if h &gt; max_height or w &gt; max_width:<br>        scaling_factor = min(max_height / h, max_width / w)<br>        new_size = (int(w * scaling_factor), int(h * scaling_factor))<br>        return cv2.resize(image, new_size, interpolation=cv2.INTER_AREA)<br>    return image<br><br>def combine_images_grid(base_image, overlays):<br>    &quot;&quot;&quot;<br>    Combine multiple overlay images into the base image using a 3x3 grid system.<br><br>    Parameters:<br>    base_image (np.ndarray): The base image where overlay images will be placed.<br>    overlays (list of tuples): List of overlay images and their grid positions. Each tuple should be in the format<br>                               (overlay_image, (grid_row, grid_col)), where (grid_row, grid_col) specifies the grid cell.<br><br>    Returns:<br>    np.ndarray: The combined image with overlays.<br>    &quot;&quot;&quot;<br>    # Make a copy of the base image to modify<br>    combined_image = base_image.copy()<br><br>    # Get the dimensions of the base image<br>    base_h, base_w = combined_image.shape[:2]<br><br>    # Calculate the size of each grid cell<br>    cell_h, cell_w = base_h // 3, base_w // 3<br><br>    # Iterate through the overlay images and their grid positions<br>    for overlay, (grid_row, grid_col) in overlays:<br>        # Resize the overlay to fit within the grid cell<br>        overlay = resize_to_fit(overlay, cell_h, cell_w)<br><br>        # Get the dimensions of the overlay image<br>        overlay_h, overlay_w = overlay.shape[:2]<br><br>        # Calculate the top-left corner of the grid cell<br>        x = grid_col * cell_w<br>        y = grid_row * cell_h<br><br>        # Place the overlay image in the center of the grid cell<br>        center_x = x + (cell_w - overlay_w) // 2<br>        center_y = y + (cell_h - overlay_h) // 2<br><br>        # Ensure the region is within the bounds of the base image<br>        if center_y + overlay_h &gt; base_h or center_x + overlay_w &gt; base_w:<br>            raise ValueError(&quot;Overlay image exceeds the bounds of the base image at the specified location.&quot;)<br><br>        # Place the overlay image on the base image<br>        combined_image[center_y:center_y+overlay_h, center_x:center_x+overlay_w] = overlay<br><br>    return combined_image</pre><p>The Image Composition Agent uses this function to create a composite image by placing the user-provided components onto a base image. The function ensures that each component is resized appropriately and positioned correctly within the grid.</p><p>The agent configuration is as follows:</p><pre>image_assistant = autogen.AssistantAgent(<br>    name=&quot;image_compose&quot;,<br>    system_message=&quot;&quot;&quot;<br>    You first get an input from the message. You then take that and pass that to combine_images_grid function defined before.<br>    You then return the combined image. You will pass that to our critic agent.<br>    &quot;&quot;&quot;,<br>    llm_config={<br>        &quot;temperature&quot;: 0,<br>        &quot;timeout&quot;: 600,<br>        &quot;cache_seed&quot;: 42,<br>        &quot;config_list&quot;: [config.copy() for config in gpt4_llm_config],<br>        &quot;functions&quot;: [<br>            {<br>                &quot;name&quot;: &quot;combine_images_grid&quot;,<br>                &quot;description&quot;: &quot;Ask the function to compose images based on the inputs.&quot;,<br>                &quot;parameters&quot;: {<br>                    &quot;type&quot;: &quot;object&quot;,<br>                    &quot;properties&quot;: {<br>                        &quot;base_image&quot;: {<br>                            &quot;type&quot;: &quot;array&quot;,<br>                            &quot;description&quot;: &quot;The background image in which the composition of the other images will be upon.&quot;<br>                        },<br>                        &quot;overlays&quot;: {<br>                            &quot;type&quot;: &quot;array&quot;,<br>                            &quot;items&quot;: {<br>                                &quot;type&quot;: &quot;object&quot;,<br>                                &quot;properties&quot;: {<br>                                    &quot;overlay_image&quot;: {<br>                                        &quot;type&quot;: &quot;array&quot;,<br>                                        &quot;description&quot;: &quot;The overlay image to place on the base image.&quot;<br>                                    },<br>                                    &quot;grid_position&quot;: {<br>                                        &quot;type&quot;: &quot;array&quot;,<br>                                        &quot;items&quot;: {&quot;type&quot;: &quot;integer&quot;},<br>                                        &quot;description&quot;: &quot;The grid position (row, col) where the overlay image will be placed.&quot;<br>                                    }<br>                                }<br>                            },<br>                            &quot;description&quot;: &quot;A list with the image and their respective region in the background image.&quot;<br>                        }<br>                    },<br>                    &quot;required&quot;: [&quot;base_image&quot;, &quot;overlays&quot;]<br>                }<br>            }<br>        ],<br>    },<br>)</pre><p><strong>Critic Agent</strong></p><p>After the Image Composition Agent generates an image, the Critic Agent evaluates it based on predefined criteria related to the positioning of each component. The Critic Agent provides feedback to ensure that the composed images meet the desired standards for layout and design. This feedback loop helps in refining the image composition, ensuring that each component is placed accurately according to the guidelines.</p><p>By leveraging these AutoGen agents, I automated the complex task of creating and refining advertisement images, ensuring both efficiency and consistency in producing high-quality visual content.</p><pre>critic = autogen.AssistantAgent(<br>    name=&quot;Critic&quot;,<br>    system_message=&quot;&quot;&quot; You are an expert in advertisement design and know what constitutes the best ads. Based on the recommended positions for each component, please analyze the provided image and offer feedback on where each component should be placed according to the guidelines below:<br><br>    VERTICAL_POSITIONING = {&#39;Logo&#39;: [1], &#39;CTA Button&#39;: [1, 2, 3], &#39;Icon&#39;: [1, 2, 3], &#39;Product Image&#39;: [2],<br>               &#39;Text Elements&#39;: [1,3], &#39;Infographic&#39;: [2], &#39;Banner&#39;: [1], &#39;Illustration&#39;: [2], &#39;Photograph&#39;: [2],<br>               &#39;Mascot&#39;: [2], &#39;Testimonial Quotes&#39;: [2], &#39;Social Proof&#39;: [2, 1, 3], &#39;Seal or Badge&#39;: [3, 1, 2],<br>               &#39;Graphs and Charts&#39;: [2], &#39;Decorative Elements&#39;: [3], &#39;Interactive Elements&#39;: [2],<br>               &#39;Animation&#39;: [2], &#39;Coupon or Offer Code&#39;: [3], &#39;Legal Disclaimers or Terms&#39;: [3],<br>               &#39;Contact Information&#39;: [3, 1, 2], &#39;Map or Location Image&#39;: [3], &#39;QR Code&#39;: [3, 1, 2]}<br><br>    HORIZONTAL_POSITIONING = {&#39;Logo&#39;: [1], &#39;CTA Button&#39;: [2, 1, 3], &#39;Icon&#39;: [1], &#39;Product Image&#39;: [1],<br>                          &#39;Text Elements&#39;: [1], &#39;Infographic&#39;: [1], &#39;Banner&#39;: [2], &#39;Illustration&#39;: [2],<br>                          &#39;Photograph&#39;: [2], &#39;Mascot&#39;: [1], &#39;Testimonial Quotes&#39;: [2], &#39;Social Proof&#39;: [3, 1, 2],<br>                          &#39;Seal or Badge&#39;: [3, 1, 2], &#39;Graphs and Charts&#39;: [1], &#39;Decorative Elements&#39;: [3],<br>                          &#39;Interactive Elements&#39;: [2], &#39;Animation&#39;: [2], &#39;Coupon or Offer Code&#39;: [3],<br>                          &#39;Legal Disclaimers or Terms&#39;: [3], &#39;Contact Information&#39;: [3, 1, 2],<br>                          &#39;Map or Location Image&#39;: [3], &#39;QR Code&#39;: [3, 1, 2]}<br><br><br>    Instructions:<br><br>    1. Identify each component in the provided image.<br>    2. Provide feedback on where each component should be placed based on the vertical and horizontal positioning guidelines. For example, &quot;Move the logo to the top right if it&#39;s not there.&quot;<br>    3. Instead of providing the feedback in text, can you provide the region where each component should be. Only givr feedback to identified one.<br>    &quot;&quot;&quot;,<br>    llm_config={&quot;config_list&quot;: [config.copy() for config in gpt4_llm_config]},<br>)</pre><p><strong>Group Chat Setup</strong></p><p>The agents interact within a group chat setup, managed by a GroupChatManager. This setup allows for seamless communication between the agents and ensures that the image composition and evaluation process is streamlined.</p><pre>user_proxy = autogen.UserProxyAgent(<br>    name=&quot;User_proxy&quot;,<br>    system_message=&quot;A human admin.&quot;,<br>    human_input_mode=&quot;NEVER&quot;,<br>    #is_termination_msg=lambda x: x.get(&quot;content&quot;, &quot;&quot;) and x.get(&quot;content&quot;, &quot;&quot;).rstrip().endswith(&quot;TERMINATE&quot;),<br>    code_execution_config={<br>        &quot;last_n_messages&quot;: 1,<br>        &quot;work_dir&quot;: &quot;groupchat&quot;,<br>        &quot;use_docker&quot;: False,<br>    },<br>)<br><br>groupchat_1 = autogen.GroupChat(agents=[user_proxy, image_assistant, critic], messages=[], max_round=10)<br><br>manager_1 = autogen.GroupChatManager(<br>    groupchat=groupchat_1,<br>    name=&quot;Research_manager&quot;,<br>    llm_config={&quot;config_list&quot;: [config.copy() for config in gpt4_llm_config]},<br>    code_execution_config={<br>        &quot;last_n_messages&quot;: 1,<br>        &quot;work_dir&quot;: &quot;groupchat&quot;,<br>        &quot;use_docker&quot;: False,<br>    },<br>)<br><br>user = autogen.UserProxyAgent(<br>    name=&quot;User&quot;,<br>    human_input_mode=&quot;NEVER&quot;,<br>    is_termination_msg=lambda x: x.get(&quot;content&quot;, &quot;&quot;).find(&quot;TERMINATE&quot;) &gt;= 0,<br>    code_execution_config={<br>        &quot;last_n_messages&quot;: 1,<br>        &quot;work_dir&quot;: &quot;tasks&quot;,<br>        &quot;use_docker&quot;: False,<br>    },<br>)<br>user.initiate_chats(<br>    [<br>        {&quot;recipient&quot;: image_assistant, &quot;message&quot;: f&quot;The input for combine_images_grid is in {image_tasks}&quot;, &quot;summary_method&quot;: &quot;last_msg&quot;},<br>        {&quot;recipient&quot;: manager_1, &quot;message&quot;: &#39;Get the rest from research_assistant and give feedback&#39;, &quot;summary_method&quot;: &quot;reflection_with_llm&quot;},<br>    ]<br>)</pre><p>This collaborative approach ensures that the composition and evaluation of advertisements are handled efficiently, leveraging the strengths of each agent to</p><h4><strong>Tool I used</strong></h4><p>In my project, I explored different configurations with three models to find the best fit for image composition and critique. Here’s a summary of my experience with each:</p><ol><li><strong>LLaVA Model</strong></li></ol><pre>from autogen.agentchat.contrib.llava_agent import LLaVAAgent, llava_call<br><br>LLAVA_MODE = &quot;remote&quot; <br>assert LLAVA_MODE in [&quot;local&quot;, &quot;remote&quot;]<br><br>if LLAVA_MODE == &quot;remote&quot;:<br><br>    llava_config_list = [<br>        {<br>            &quot;api_key&quot;: os.environ[&quot;REPLICATE_API_TOKEN&quot;],<br>            &quot;base_url&quot;: &quot;yorickvp/llava-13b:2facb4a474a0462c15041b78b1ad70952ea46b5ec6ad29583c0b29dbd4249591&quot;,<br>        }<br>    ]</pre><p>The LLaVA model impressed me with its strong vision capabilities. I tested it on various images to evaluate its object detection and image description skills. While it excelled at describing images and identifying objects, it often hallucinated when providing knowledge-based responses. Unfortunately, it didn’t work for my specific use case, possibly due to an issue with the URL configuration. Further investigation is needed to pinpoint the exact cause.</p><p>2. <strong>GPT-4 Model</strong></p><pre>gpt4_llm_config =[{<br>        &quot;model&quot;: &quot;gpt-4&quot;,<br>        &quot;api_key&quot;: os.environ[&#39;OPENAI_API_KEY&#39;],<br>    }]</pre><p>GPT-4 provided excellent responses and facilitated effective communication between agents. However, due to its high cost, I couldn’t extensively experiment with it. Although the agents interacted well, the responses didn’t fully meet my requirements.</p><p>3. Gemini-Pro Model</p><pre>gpt4_llm_config = [{<br>        &quot;model&quot;: &quot;gemini-pro&quot;,<br>        &quot;api_key&quot;: os.envirn[&#39;GEMINI_API_KEY&#39;],<br>        &quot;api_type&quot;: &quot;google&quot;<br>    }]</pre><p>Gemini-Pro delivered similar results to GPT-4 but had the added advantage of offering free API keys. While it shows promise, further refinement is needed to achieve the desired response quality. I’m continuing to work on improving this model’s performance for my project needs.</p><p>In summary, while each model had its strengths and limitations, the search for the optimal configuration continues. The journey involved trial and error, but each step brought valuable insights into the capabilities and limitations of these advanced models.</p><h4>Project Implementation Challenges and Learnings</h4><p>My initial goal was to start with a simple image composition function and then test the AutoGen system with a static knowledge base focused solely on position verification. Unfortunately, AutoGen didn’t perform as expected, consuming a significant amount of my time.</p><p>If the project had succeeded, I planned to enhance the image composition function to include advanced features such as color composition, text extraction, and other sophisticated capabilities. The project also utilized a static knowledge base, while the ultimate objective was to dynamically build a knowledge base from our data.</p><p>Here’s how I envisioned the complete process:</p><ol><li><strong>Identifying Top-Performing Ads</strong>: Using performance metrics from a CSV file, such as Engagement Rate (ER) and Click-Through Rate (CTR), we would identify the best-performing ads.</li><li><strong>Analyzing Image Component Arrangement</strong>: The next step would involve analyzing the structure and arrangement of components within these top-performing ads. This analysis would enable the system to learn optimal component structures.</li><li><strong>Feedback Loop</strong>: The critic agent would use this dynamically built knowledge base to provide informed feedback to the composition agent, ensuring that each composed ad meets high-performance standards.</li></ol><p>Despite these well-laid plans, I encountered challenges in implementing this dynamic feedback system. Integrating the performance analysis with the image composition and critique agents proved to be a complex task, one that I have yet to fully resolve.</p><p>The journey, though fraught with obstacles, offered valuable insights and learning experiences. Each step brought me closer to understanding the intricacies of automated storyboard synthesis and the potential for future advancements in this exciting field.</p><h4>Challenge Faced</h4><ul><li><strong>Understanding and Implementing AutoGen Agents</strong></li></ul><p>Working with AutoGen agents was a new experience for me, involving a significant learning curve. The challenge was not only understanding the underlying concepts but also adapting them to fit my project’s specific needs. This required studying the documentation, experimenting with configurations, and refining the agents to ensure they performed well for image composition and critique.</p><ul><li><strong>Debugging Complexities</strong></li></ul><p>Debugging was another significant challenge. As with any new technology, troubleshooting unexpected issues and ensuring smooth integration of different components required careful attention. Overcoming these hurdles involved thorough testing, collaboration with peers, and using online resources to quickly identify and resolve problems.</p><ul><li><strong>Time Constraints and Knowledge Base Development</strong></li></ul><p>Building a robust knowledge base was also challenging, primarily in terms of sourcing and curating relevant information. Developing a comprehensive repository that the AutoGen agents could use required extensive research and validation.</p><h4>Conclusion</h4><p>Despite these challenges, the journey of implementing AutoGen agents for automated storyboard synthesis has been immensely rewarding. Each obstacle presented an opportunity to deepen my understanding and refine my technical skills in machine learning and digital advertising. Moving forward, I am excited to continue exploring new advancements in AI-driven creative processes, contributing to innovative solutions that redefine the landscape of digital advertising.</p><h4><strong>References</strong></h4><ul><li>Autogen notebooks: <a href="https://github.com/microsoft/autogen/tree/main/notebook">https://github.com/microsoft/autogen/tree/main/notebook</a></li><li>Autogen Documentaion: <a href="https://microsoft.github.io/autogen/">https://microsoft.github.io/autogen/</a></li><li><a href="https://github.com/birehan/Automated-Storyboard-Synthesis-for-Digital-Advertising">https://github.com/birehan/Automated-Storyboard-Synthesis-for-Digital-Advertising</a></li></ul><p>Project Link: <a href="https://github.com/Yohanes213/Automated-Storyboard-Synthesis-for-Digital-Advertising">Automated-Storyboard-Synthesis-for-Digital-Advertising</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ce452067d71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Contract Advisor RAG: Towards Building A High-Precision Legal Expert LLM APP]]></title>
            <link>https://medium.com/@Yohanes213/contract-advisor-rag-towards-building-a-high-precision-legal-expert-llm-app-5cf9f941c03f?source=rss-b0e5a4e1d5de------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cf9f941c03f</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Yohanes Teshome Kebede]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 16:20:58 GMT</pubDate>
            <atom:updated>2024-07-26T14:29:37.140Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*8feP6JEGMrFW-llXarw-mw.png" /><figcaption>Source: <a href="https://blog.griddynamics.com/retrieval-augmented-generation-llm/">https://blog.griddynamics.com/retrieval-augmented-generation-llm/</a></figcaption></figure><h4>Business objective</h4><p>Lizzy AI is an early-stage Israeli startup, developing the next-generation contract AI. We leverage Hybrid LLM technology (edge, private cloud and LLM services), to build the first, fully autonomous, artificial contract lawyer. The first step in our journey is a powerful contract assistant, with the ultimate goal of developing a fully autonomous contract bot, capable of drafting, reviewing, and negotiating contracts, independently, end-to-end, without human assistance.</p><p>Our task is as follows: <strong>build, evaluate and improve</strong> a RAG system for Contract Q&amp;A (chatting with a contract and asking questions about the contract).</p><h4><strong>What is RAG</strong></h4><p>Retrieval Augmented Generation, commonly known as RAG, is a hybrid AI model that marries the expertise of powerful language models with the richness of external data sources. At its core, RAG leverages a large language model for generating responses, but with a twist — it first retrieves relevant information from a vast pool of external data. This retrieval phase empowers the model to augment its generated responses with information that goes beyond its initial training data, offering more accurate, informed, and context-rich outputs.</p><h4><strong>Why is RAG Exciting</strong></h4><p>Building a basic RAG system can be surprisingly straightforward, making it an enticing entry point for AI enthusiasts and students. However, crafting a high-quality, robust RAG system that performs exceptionally well is a complex and challenging endeavor. This complexity provides a rich learning ground for those aspiring to push the boundaries in AI.</p><p>In this blog post, I am going to explain different method I used to build, then evaluate my RAG System.</p><h4>Project Implementation</h4><p><strong>Data</strong></p><p>The dataset used in this project is an Advisory Services Agreement. This agreement outlines the terms and conditions between Cloud Investments Ltd. and an advisor, detailing the services to be provided, compensation, confidentiality, non-competition, and other legal aspects. The agreement serves as a typical example of a contractual document used for building, evaluating, and improving a RAG system for contract Q&amp;A.</p><p><strong>Database</strong></p><p>I utilized Pinecone as the vector database for storing and retrieving document embeddings.</p><p><strong>Chunking</strong></p><p>I experimented with two methods for chunking the text and compared their results:</p><ol><li><strong>Custom Chunking Method:</strong></li></ol><pre>def chunk_text(text, max_tokens=300):<br>    &quot;&quot;&quot;<br>    Chunk input text into segments of approximately max_tokens tokens.<br><br>    Args:<br>    - text (str): The input text to be chunked.<br>    - max_tokens (int): Maximum number of tokens per chunk (default: 300).<br><br>    Returns:<br>    - list: List of chunked text segments.<br>    &quot;&quot;&quot;<br>    chunks = []<br>    current_chunk = &quot;&quot;<br>    tokens_count = 0<br>    sentences = text.split(&quot;. &quot;)<br><br>    for sentence in sentences:<br>        if tokens_count + len(sentence.split()) &gt; max_tokens:<br>            chunks.append(current_chunk.strip())<br>            current_chunk = &quot;&quot;<br>            tokens_count = 0<br>        current_chunk += sentence + &quot;. &quot;<br>        tokens_count += len(sentence.split())<br><br>    if current_chunk:<br>        chunks.append(current_chunk.strip())<br><br>    return chunks</pre><p>2. <strong>Using</strong><strong>RecursiveCharacterTextSplitter from LangChain:</strong></p><pre>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>text_splitter = RecursiveCharacterTextSplitter(<br>    chunk_size = 1000,<br>    chunk_overlap=100<br>)</pre><p>By switching between these two methods, I evaluated their effectiveness in chunking the text.</p><p><strong>Embedding</strong></p><p>For embedding, I used OpenAI’s embedding model:</p><pre>from langchain.embeddings.openai import OpenAIEmbeddings<br>def embed_text(chunked_text, model=&quot;text-embedding-ada-002&quot;):<br>    &quot;&quot;&quot;<br>    Embed chunked text segments using OpenAI&#39;s text embedding model.<br><br>    Args:<br>    - chunked_text (list): List of text segments to embed.<br>    - model (str): Name of the OpenAI embedding model (default: &#39;text-embedding-ada-002&#39;).<br><br>    Returns:<br>    - list: List of embedded document representations.<br>    &quot;&quot;&quot;<br>    try:<br>        embed_model = OpenAIEmbeddings(model=model, openai_api_key=openapi_key)<br>        document_embeddings = embed_model.embed_documents(chunked_text)<br>        return document_embeddings<br>    except Exception as e:<br>        logger.error(f&quot;Error embedding text: {str(e)}&quot;)<br>        return []</pre><p><strong>Vectorization</strong></p><p>The vectorized text was stored in Pinecone:</p><pre>from pinecone import Pinecone as PineconeClient<br>def vectorize(chunked_text, document, namespace):<br>    &quot;&quot;&quot;<br>    Vectorize embedded text chunks and upsert into a Pinecone index.<br><br>    Args:<br>    - chunked_text (list): List of text chunks.<br>    - document (list): List of document embeddings corresponding to chunked_text.<br>    - namespace (str): Namespace for Pinecone index.<br><br>    Returns:<br>    - None<br>    &quot;&quot;&quot;<br>    try:<br>        upsert_data = [<br>            (str(i), embedding, {&quot;text&quot;: chunked_text[i]})<br>            for i, embedding in enumerate(document)<br>        ]<br><br>        pc = PineconeClient(pinecone_key)<br>        index_name = &quot;lawquestionandanswer&quot;<br>        index = pc.Index(index_name)<br><br>        index.upsert(upsert_data, namespace=namespace)<br>    except Exception as e:<br>        logger.error(f&quot;Error vectorizing text: {str(e)}&quot;)</pre><h4><strong>Different Method I Implemented</strong></h4><h4><strong>1. Basic RAG Implementation</strong></h4><p>I started by building a simple RAG system using LangChain and OpenAI. I utilized a prompt from LangChain Hub and employed LangSmith to log and track the process.</p><pre>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnablePassthrough<br>from langchain import hub<br>from langchain_openai import ChatOpenAI<br>from langsmith import traceable<br><br>openai_client = ChatOpenAI(api_key=os.getenv(&#39;OPENAI_API_KEYS&#39;), temperature=0)<br>LANGCHAIN_TRACING_V2 = &quot;true&quot;<br>LANGCHAIN_ENDPOINT = &quot;https://api.smith.langchain.com&quot;<br>LANGCHAIN_API_KEY = os.getenv(&#39;LANGCHAIN_API_KEY&#39;)<br>LANGCHAIN_PROJECT = &quot;Contract Question and Answer&quot;<br><br><br>async def generate_response(query):<br>    &quot;&quot;&quot;<br>    Generate a response to a given query using LangChain and OpenAI.<br><br>    Args:<br>        query (str): The query string for which response is generated.<br><br>    Returns:<br>        str: Response generated by the system.<br>    &quot;&quot;&quot;<br>    retriver = retrive()<br><br>    prompt = hub.pull(&quot;rlm/rag-prompt&quot;)<br><br>    chain = (<br>        {&quot;context&quot;: retriver, &quot;question&quot;: RunnablePassthrough()} <br>        | prompt<br>        | openai_client<br>        | StrOutputParser()<br>    )<br><br>    response = chain.invoke(query)<br>    return response</pre><p><strong>Explanation</strong></p><ul><li><strong>LangChain Components</strong>: The system uses various components from LangChain, including RunnablePassthrough for passing the question through the chain and StrOutputParser for parsing the output.</li><li><strong>Prompt from LangChain Hub</strong>: The prompt used in the system is pulled from the LangChain Hub (hub.pull(&quot;rlm/rag-prompt&quot;)).</li><li><strong>OpenAI Client</strong>: The OpenAI client is initialized with an API key and a specified temperature.</li><li><strong>LangSmith Tracking</strong>: LangSmith is configured to track and log the process.</li><li><strong>Async Function</strong>: The generate_response function is defined as an asynchronous function, which takes a query as input and generates a response using the RAG system.</li></ul><p><strong>Result:</strong></p><p>The system produced promising responses. Here is an example result from LangSmith(from one example question):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Szo4nBSw1hSUxtjGcASQRA.png" /></figure><h4><strong>2. RAG Implementation(With Custom Prompt)</strong></h4><pre><br>async def generate_response(query):<br>    &quot;&quot;&quot;<br>    Generate a response to a given query using LangChain and OpenAI.<br><br>    Args:<br>        query (str): The query string about the contract.<br><br>    Returns:<br>        str: Response generated by the system.<br>    &quot;&quot;&quot;<br><br>    retriver = retrive()<br><br>    # Combine system and user messages into a single list<br>    prompt_template = PromptTemplate(<br>        input_variables=[&#39;context&#39;, &#39;query&#39;],<br>        template=&quot;&quot;&quot;<br>            You are an AI expert specialized in contract analysis and advisory services.<br>            Your goal is to assist users by providing precise and helpful answers based on a contract document(context). <br>            The document in question is an Advisory Services Agreement. <br>            Given the user query, generate a well-structured and informative response by extracting relevant information from the document. <br>            Ensure the response is concise, accurate, and directly addresses the query.<br>            Don&#39;t make the response long. Make the response short and precise. <br>            If you know got the answer from a specific section, specify it like Under this section and write the section number.<br>            question: {query} context: {context}<br>        &quot;&quot;&quot;<br>    )<br><br>    <br>    prompt = ChatPromptTemplate(<br>        input_variables=[&#39;context&#39;, &#39;query&#39;],<br>        messages=[<br>            HumanMessagePromptTemplate(prompt=prompt_template)<br>        ]<br>    )   <br><br>    chain = (<br>        {&quot;context&quot;: retriver, &quot;query&quot;: RunnablePassthrough()}<br>        | prompt<br>        | chatopenai_client<br>        | StrOutputParser()<br>    )<br><br>    response = chain.invoke(query)<br>    return response</pre><p><strong>Result (RAGAS)</strong></p><p>I implemented RAGAS evaluation to assess the results.</p><pre>async def runner(questions):<br>    result = await generate_response(questions)<br>    return result<br><br><br>if __name__ == &quot;__main__&quot;:<br><br>    retriver = retrive()<br><br>    questions, ground_truth = load_evaluation_dataset(&quot;data/Robinson Q&amp;A.docx&quot;)<br>    answers = []<br>    contexts = []<br><br>    loop = asyncio.get_event_loop()<br><br>    for question in questions:<br>        result = loop.run_until_complete(runner(question))<br>        answers.append(result)<br>        contexts.append(<br>            [docs.page_content for docs in retriver.get_relevant_documents(question)]<br>        )<br><br>    data = {<br>        &quot;question&quot;: questions,<br>        &quot;answer&quot;: answers,<br>        &quot;contexts&quot;: contexts,<br>        &quot;ground_truth&quot;: ground_truth,<br>    }<br><br>    dataset = Dataset.from_dict(data)<br><br>    result = evaluate(<br>        dataset=dataset,<br>        metrics=[<br>            context_precision,<br>            context_recall,<br>            faithfulness,<br>            answer_relevancy,<br>        ],<br>    )</pre><h4><strong>3. Query Expansion</strong></h4><p>I used two query expansion.</p><blockquote>- Hypothetical</blockquote><blockquote>- Multiple Query</blockquote><p>Hypothetical Query Expansion</p><pre>from openai import OpenAI<br>from dotenv import load_dotenv<br>import os<br><br>load_dotenv()<br>openai_key = os.getenv(&quot;OPENAI_API_KEYS&quot;)<br><br>client = OpenAI(api_key=openai_key)<br><br>def expand_query_hypothetical(query, model=&quot;gpt-3.5-turbo&quot;):<br>    messages = [<br>        {<br>            &quot;role&quot;: &quot;system&quot;,<br>            &quot;content&quot;:(<br>                &quot;You are a knowledgeable contract assistant. For the given question, provide a hypothetical example answer &quot;<br>                &quot;that one might find in an Advisory Services Agreement document. Ensure the example is clear, concise, and relevant to the query. &quot;<br>                &quot;Answer in one sentence and make it like you have the information.&quot;<br>            )<br>        },<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query}<br>    ] <br><br>    response = client.chat.completions.create(<br>        model=model,<br>        messages=messages,<br>        temperature=0<br>    )<br><br>    return response.choices[0].message.content</pre><p>Multiple Query Expansion</p><pre>def expand_query_multiple(query, model=&quot;gpt-3.5-turbo&quot;):<br>    messages = [<br>        {<br>            &quot;role&quot;: &quot;system&quot;,<br>            &quot;content&quot;: (<br>                &quot;You are a helpful expert in contract assistance. Users are asking questions about a contract document. &quot;<br>                &quot;For the provided question, suggest up to five additional related questions to help them find the information they need. &quot;<br>                &quot;Ensure the questions are short, cover different aspects of the topic, and are directly related to the original question. Output each question on a new line without numbering them.&quot;<br>            )<br>        },<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query}<br>    ] <br><br>    response = client.chat.completions.create(<br>        model=model,<br>        messages=messages,<br>        temperature=0.2<br>    )<br><br>    return response.choices[0].message.content.strip()</pre><p><strong>Results and Process Explanation</strong></p><p><strong>Time Consumption:</strong> The first observation was that the process took a significant amount of time, especially for the multiple query expansion method.</p><p><strong>Hypothetical Answer Expansion:</strong></p><ul><li>The system generates a hypothetical answer to the original query.</li><li>This hypothetical answer is then used to retrieve relevant documents from the database.</li><li>The retrieved documents are then used to generate the final response.</li></ul><p><strong>Multiple Query Expansion:</strong></p><ul><li>The system generates up to five additional related questions based on the original query.</li><li>For each of these six queries (including the original query), relevant documents are retrieved.</li><li>Using a Cohere reranking process, the top four most relevant documents are selected.</li><li>These top documents are then used in conjunction with the original query to generate the final response.</li></ul><pre>from dotenv import load_dotenv<br>import os<br>from langchain_cohere import CohereRerank<br>from langchain_community.llms import Cohere<br>from langchain.retrievers.contextual_compression import ContextualCompressionRetriever<br>from query_expansion import expand_query_hypothetical, expand_query_multiple<br>from response_generation import retrive, generate_response<br>import asyncio<br><br>load_dotenv()<br>cohere_api_key = os.getenv(&quot;COHERE_API_KEYS&quot;)<br>os.environ[&quot;COHERE_API_KEY&quot;] = cohere_api_key<br><br>def coherererank():<br>    &quot;&quot;&quot;<br>    Creates and configures the retrieval pipeline with ContextualCompressionRetriever<br>    for efficient retrieval and ranking.<br><br>    Returns:<br>        ContextualCompressionRetriever: The configured retriever instance.<br>    &quot;&quot;&quot;<br><br>    llm = Cohere(temperature=0)<br>    compressor = CohereRerank()<br>    retriever = retrive() <br><br>    compressed_retriever = ContextualCompressionRetriever(<br>        base_compressor=compressor, base_retriever=retriever<br>    )<br><br>    return compressed_retriever<br><br>if __name__ == &quot;__main__&quot;:<br>    compressed_retriever = coherererank()<br><br>    query = &quot;Can the Agreement or any of its obligations be assigned?&quot;<br>    joint_query = expand_query_multiple(query)<br><br>    list_queries = joint_query.strip().split(&#39;\n&#39;)<br>    list_queries.append(query)<br><br>    # Retrieve documents for all expanded and original queries<br>    all_docs = []<br>    for query1 in list_queries:<br>        docs = compressed_retriever.invoke(query1)<br>        all_docs.extend(docs)<br><br>    #print(all_docs)<br>    # Rank all retrieved documents using a suitable ranking algorithm (replace with your choice)<br>    ranked_docs = sorted(all_docs, key=lambda doc: vars(doc)[&#39;metadata&#39;][&#39;relevance_score&#39;], reverse=True)  # Example ranking by score<br><br>    query = &#39;&#39;<br>    # Print the top 3 ranked documents<br>    for doc in ranked_docs[:3]:<br>        print(doc)<br>        print(&quot;\n&quot;)  # Add newline for better formatting<br><br>        query+=vars(doc)[&#39;page_content&#39;]<br>        query+= &quot;\n&quot;<br><br>    <br>    response = asyncio.run(generate_response(query))<br>    <br>    print(response)</pre><p><strong>Insights About Multiple Query Expansion</strong></p><p>I evaluated the responses generated using multiple query expansion and observed mixed results. Here’s a summary of my findings:</p><p><strong>Evaluation Observations</strong></p><ol><li><strong>Good Responses:</strong></li></ol><ul><li>For some questions, the system generated very accurate and helpful responses.</li><li>These successful responses demonstrated the effectiveness of multiple query expansion in retrieving relevant information.</li></ul><p><strong>2. Poor Responses:</strong></p><ul><li>For other questions, the system did not generate the correct answer.</li><li>However, I noticed that the reranked retrieved documents often contained the correct answer.</li><li>This indicates that the retrieval process is functioning well, but the response generation is where the issue lies.</li></ul><h4>Modifications and Tests</h4><p>To address these issues, I made the following modifications and tests:</p><ol><li><strong>Reducing Multiple Queries:</strong></li></ol><ul><li>I reduced the number of additional queries from five to three.</li><li>This helped streamline the retrieval process, focusing on fewer but more relevant documents.</li></ul><p><strong>2. Adjusting Reranking:</strong></p><ul><li>I adjusted the reranking process to select only the top document.</li><li>This aimed to ensure that the most relevant document is used for generating the response.</li></ul><p><strong>3. Testing Multiple Prompts:</strong></p><ul><li>I experimented with different prompt structures to see if they could improve the quality of the generated responses.</li></ul><p><strong>Conclusion</strong></p><p>The primary reason for poor responses was identified as the prompt quality. A well-structured and well-written prompt is crucial for guiding the model to generate accurate and relevant answers. Improving the prompt design should lead to better results in response generation.</p><h4>4. RetrievalQA Implementation</h4><p>I improved the system by switching from using ChatOpenAI directly to employing RetrievalQA, which combines language model capabilities with a retrieval mechanism. This approach leverages the strengths of both the language model and the retriever, providing more contextually accurate responses.</p><p>Here is the updated implementation:</p><pre>from langchain.memory import ConversationBufferMemory<br>from langchain.chains import RetrievalQA<br><br>chatopenai_client = ChatOpenAI(api_key=os.getenv(&quot;OPENAI_API_KEYS&quot;), temperature=0)<br><br><br>retriever = retriever()<br><br>memory = ConversationBufferMemory()<br>qa = RetrievalQA.from_llm(llm=chatopenai_client, retriever = retriever,  memory = memory)<br><br><br>async def generate_response(query):<br>    &quot;&quot;&quot;<br>    Generate a response to a given query using LangChain and OpenAI.<br><br>    Args:<br>        query (str): The query string about the contract.<br><br>    Returns:<br>        str: Response generated by the system.<br>    &quot;&quot;&quot;<br><br>    response = await qa.arun(query)<br>    return response</pre><p><strong>Result (Ragas Evaluation)</strong></p><p>I evaluated the system using Ragas metrics and visualized the results using a radar chart. Here’s the script for generating and visualizing the results:</p><pre>import plotly.graph_objects as go<br><br>def visualize_result(result, name, title):<br>    data = {<br>        &#39;context_precision&#39;: result[&#39;context_precision&#39;],<br>        &#39;context_recall&#39;: result[&#39;context_recall&#39;],<br>        &#39;faithfulness&#39;: result[&#39;faithfulness&#39;],<br>        &#39;answer_relevancy&#39;: result[&#39;answer_relevancy&#39;],<br>        &#39;answer_similarity&#39;: result[&#39;answer_similarity&#39;]<br>    }<br><br>    # Create the radar chart<br>    fig = go.Figure()<br><br>    fig.add_trace(go.Scatterpolar(<br>        r=list(data.values()),<br>        theta=list(data.keys()),<br>        fill=&#39;toself&#39;,<br>        name=&#39;Ensemble Rag&#39;<br>    ))<br><br>    fig.update_layout(<br>        polar=dict(<br>            radialaxis=dict(<br>                visible=True,<br>                range=[0, 1]<br>            )<br>        ),<br>        showlegend=True,<br>        title=title,<br>        width=800<br>    )<br><br>    # Save the figure as an HTML file<br>    fig.write_html(name)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-asUl2untoGr_2RgnIwGjw.png" /></figure><h4><strong>5. RetrievalQA wth </strong>RecursiveCharacterTextSplitter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QjMEEwbA1pLOHj-45QiY0A.png" /></figure><p><strong>Insight:</strong></p><p>The is a slight decrease in context_recall and slight increase in faithfulness.</p><h4>6. RetrievalQA.from_chain_type</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*zSh_YAWvtxATp7RtsQChZA.png" /></figure><p><strong>Insight:</strong></p><p>Compare to RetrievalQA.from_lllm,thereis a slight i increase context_recall and slight decrease in faithfulness.</p><p><strong>7. Autogen Implementation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPYdqqKH8rvR25TS9LBsSg.png" /></figure><p>The system consists of two agents: a Retrieval-augmented User Proxy agent, called RetrieveUserProxyAgent, and a Retrieval-augmented Assistant agent, called RetrieveAssistantAgent, both of which are extended from built-in agents from AutoGen.</p><pre>__import__(&#39;pysqlite3&#39;)<br>import sys<br>sys.modules[&#39;sqlite3&#39;] = sys.modules.pop(&#39;pysqlite3&#39;)<br>import os<br>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.sqlite3&#39;,<br>        &#39;NAME&#39;: os.path.join(&#39;.&#39;, &#39;db.sqlite3&#39;),<br>    }<br>}<br>import json<br><br><br>import chromadb<br><br>import autogen<br>from autogen.agentchat.contrib.retrieve_assistant_agent import RetrieveAssistantAgent<br>from autogen.agentchat.contrib.retrieve_user_proxy_agent import RetrieveUserProxyAgent<br><br># Accepted file formats for that can be stored in<br># a vector database instance<br>from autogen.retrieve_utils import TEXT_FORMATS<br>import os<br><br>config_list = [<br>    {&quot;model&quot;: &quot;gpt-3.5-turbo-0125&quot;, &quot;api_key&quot;: os.getenv(&#39;OPENAI_API_KEYS&#39;), &quot;api_type&quot;: &quot;openai&quot;},<br>]<br><br>assert len(config_list) &gt; 0<br>print(&quot;models to use: &quot;, [config_list[i][&quot;model&quot;] for i in range(len(config_list))])</pre><pre>from langchain.text_splitter import RecursiveCharacterTextSplitter<br><br>recur_spliter = RecursiveCharacterTextSplitter(separators=[&quot;\n&quot;, &quot;\r&quot;, &quot;\t&quot;])</pre><pre>assistant = RetrieveAssistantAgent(<br>    name=&quot;assistant&quot;,<br>    system_message=&quot;&quot;&quot;<br>    You are an AI expert specialized in contract analysis and advisory services.<br>    Your goal is to assist users by providing precise and helpful answers based on a contract document.<br>    The document in question is an Advisory Services Agreement.<br>    Given the user query, generate a well-structured and informative response by extracting relevant information from the document.<br>    Ensure the response is concise, accurate, and directly addresses the query.<br>    &quot;&quot;&quot;,<br>    llm_config={<br>        &quot;timeout&quot;: 600,<br>        &quot;cache_seed&quot;: 42,<br>        &quot;config_list&quot;: config_list,<br>    },<br>)<br><br>ragproxyagent = RetrieveUserProxyAgent(<br>    name=&quot;ragproxyagent&quot;,<br>    human_input_mode=&quot;NEVER&quot;,<br>    max_consecutive_auto_reply=3,<br>    retrieve_config={<br>        &quot;task&quot;: &quot;qa&quot;,<br>        &quot;docs_path&quot;: [<br>            &#39;../data/Robinson Advisory.docx.pdf&#39;<br>        ],<br>        #&quot;custom_text_types&quot;: [&quot;non-existent-type&quot;],<br>        &quot;chunk_token_size&quot;: 1000,<br>        &quot;model&quot;: config_list[0][&quot;model&quot;],<br>        #&quot;client&quot;: chromadb.PersistentClient(path=&quot;/tmp/chromadb&quot;),  # deprecated, use &quot;vector_db&quot; instead<br>        &quot;vector_db&quot;: &quot;chroma&quot;,  # to use the deprecated `client` parameter, set to None and uncomment the line above<br>        &quot;overwrite&quot;: True,  # set to True if you want to overwrite an existing collection<br>        #&quot;chunk_mode&quot;: &quot;one_line&quot;,<br>        &quot;must_break_at_empty_line&quot;: False,<br>        #&quot;embedding_model&quot;: embed_model,<br>        &quot;update_context&quot;: True,<br>        &quot;custom_text_split_function&quot;: recur_spliter.split_text,<br>        #&quot;custom_text_split_function&quot;: autogen.retrieve_utils.split_text_to_chunks(max_tokens = 1000, chunk_mode = &quot;multi_lines&quot;, must_break_at_empty_line = True, overlap = 10)&#39;<br>        <br>    },<br>    code_execution_config=False,  # set to False if you don&#39;t want to execute the code<br>)</pre><pre>assistant.reset()<br><br>qa_problem = &quot;What is the termination notice?&quot;<br>chat_result = ragproxyagent.initiate_chat(assistant, <br>                                          message=ragproxyagent.message_generator,<br>                                          problem=qa_problem)</pre><p><strong>Output:</strong></p><pre>The termination notice clause is not explicitly mentioned in the provided context or throughout the document.</pre><p>The above you code you see is just one example I tried. I tried different things like:</p><ul><li>Different chunking length</li><li>Manipulating the parameters like changing this to False “update_context”.</li><li>Used custom chunking method (RecursiveCharacterTextSplitter).</li></ul><p>But the result wasn’t promising. The answer as you can see above isn’t good.</p><p><strong>Conclusions:</strong></p><p>From what I’ve noticed, the main reason for this bad response is the way it’s reding the docx file. It isn’t reading it well and for each space it will put it a new line. I think, that’s what causing.</p><h4>Frontend: Interactive Streamlit App</h4><p>To facilitate user interaction with the RAG system I developed, I built an intuitive Streamlit web application. This app allows users to pose contract-related queries and receive responses generated by the model in real-time. Below is a snapshot of the user interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4D6Tr84VltPbBbUvcuCKw.png" /></figure><h4>Limitations</h4><p>While this project has demonstrated promising results in implementing a RAG (Retrieval-Augmented Generation) system for contract analysis, several limitations were identified during its development:</p><ul><li><strong>Lack of Organized Analysis:</strong> The project currently lacks a well-structured analysis framework. Each method’s performance metrics, such as context precision, recall, faithfulness, and answer relevancy, should be systematically recorded and evaluated. This would provide clearer insights into the strengths and weaknesses of different approaches employed.</li><li><strong>Uniform Metrics and Measurements:</strong> There is a need for consistent metrics and measurements across all implemented methods. This consistency would facilitate a more accurate comparison and evaluation of different RAG configurations and variations.</li><li><strong>Incomplete Implementation:</strong> While initial implementations have been successful, there are several potential enhancements that have not yet been explored. These include experimenting with alternative chunking methods, refining the QA structure, and exploring different approaches to document retrieval and ranking.</li></ul><h4>Future Improvements</h4><p>To address the identified limitations and further enhance the effectiveness of the RAG system, several future improvements are planned:</p><ul><li><strong>Exploring Alternative Methods:</strong> Experiment with different chunking methods to optimize text segmentation and improve document relevance.</li><li><strong>Refining QA Structures:</strong> Implement alternative QA structures to enhance the system’s ability to extract accurate and relevant information from contract documents.</li><li><strong>Implementing a Well-Structured Recording System:</strong> Develop a comprehensive recording system that tracks the performance of each method over time. This system will include regular RAGAS (Retrieval-Augmented Generation Accuracy Score) evaluations, time-based performance metrics, and detailed logs of system interactions.</li><li><strong>Continuous Evaluation and Optimization:</strong> Continuously evaluate and optimize the RAG system based on feedback and performance metrics. This iterative process will ensure that the system evolves to meet the demands of real-world contract analysis scenarios.</li></ul><p>By addressing these areas, the project aims to not only overcome its current limitations but also establish a robust foundation for future enhancements and applications in contract analysis and advisory services.</p><h4>Conclusions</h4><p>In developing a RAG system for contract analysis, I’ve explored various AI technologies and strategies to enhance advisory services. Integrating LangChain for document retrieval and OpenAI models for response generation has been instrumental in extracting and delivering precise information from legal documents.</p><p>Throughout this project, I encountered challenges such as prompt formulation and document retrieval methods. These obstacles provided valuable insights into the importance of structured analysis and uniform metrics for evaluating system performance.</p><p>Looking forward, there are opportunities to further optimize the RAG system. Future efforts will focus on refining QA structures, exploring alternative chunking methods, and implementing a more robust evaluation framework.</p><p>Ultimately, my goal is to provide a reliable tool that simplifies contract analysis tasks, contributing to more informed decision-making in legal environments.</p><p>If you enjoyed reading this post, please drop a 👏</p><p>Project Link: <a href="https://github.com/Yohanes213/Contract-Advisor-RAG">Contract Advisory RAG</a></p><p>Follow me on GitHub: <a href="https://github.com/Yohanes213">Yohanes213</a></p><p>Follow me on Medium: <a href="https://medium.com/@Yohanes213">Yohanes Teshome Kebede</a></p><p>Let’s connect on LinkedIn: <a href="https://www.linkedin.com/in/yohanes-teshome/">Yohanes Teshome Kebede</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cf9f941c03f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crypto Trading Engineering: Scalable Backtesting Infrastructure]]></title>
            <link>https://medium.com/@Yohanes213/crypto-trading-engineering-scalable-backtesting-infrastructure-596ba497887b?source=rss-b0e5a4e1d5de------2</link>
            <guid isPermaLink="false">https://medium.com/p/596ba497887b</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[backtesting]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[Yohanes Teshome Kebede]]></dc:creator>
            <pubDate>Wed, 26 Jun 2024 18:39:28 GMT</pubDate>
            <atom:updated>2024-07-26T14:35:16.393Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7STepILTA_ZLCcdHPdH3Uw.png" /></figure><h4>Business Need</h4><p>Mela seeks to streamline cryptocurrency investments and offer a secure investment platform. The project’s goal is to create a scalable trading data pipeline capable of conducting reliable backtests and storing critical data artifacts effectively.</p><h4>Background</h4><p>With the rising prominence of cryptocurrencies, there is a critical need for robust infrastructure to support effective trading strategies. This project aims to address these demands by constructing a sophisticated data pipeline tailored specifically for cryptocurrency markets. The pipeline will facilitate rigorous backtesting of diverse trading strategies and ensure secure storage of essential market data. By integrating advanced data engineering practices and MLOps tools, the goal is to enhance decision-making capabilities and operational efficiency in cryptocurrency trading. Ultimately, this initiative aims to provide investors with a stable and transparent platform for exploring and optimizing their investment strategies in the dynamic world of digital currencies.</p><h4><strong>Data</strong></h4><p>For this project, data was sourced primarily from Yahoo Finance. The analysis focuses on several prominent cryptocurrencies:</p><ul><li>Bitcoin</li><li>Ethereum</li><li>Binance Coin</li><li>Cardano</li><li>Dogecoin</li><li>Gnosis</li><li>Solana</li></ul><p>These cryptocurrencies were selected based on their market prominence and varied characteristics within the crypto space. The dataset from Yahoo Finance provides a comprehensive foundation for conducting detailed analyses and backtesting various trading strategies. This approach ensures that the project leverages reliable and widely accessible data sources to support robust decision-making in cryptocurrency investments.</p><h4><strong>Technology Stack</strong></h4><p>Our project leverages a modern technology stack to support various aspects of cryptocurrency trading infrastructure:</p><ul><li><strong>Backtrader</strong>: Utilized for robust backtesting of trading strategies, ensuring thorough evaluation and optimization.</li><li><strong>FastAPI</strong>: Powers the backend with its high-performance framework, facilitating efficient data processing and management of requests.</li><li><strong>React</strong>: Drives the frontend development, offering a responsive and intuitive interface for users to interact with backtest results and configure trading parameters.</li><li><strong>MLflow</strong>: Integrated for saving and tracking backtest results, providing a centralized repository for metrics and insights.</li><li><strong>Apache Kafka</strong>: Employed for seamless data processing, enabling efficient handling and streaming of real-time market data and backtest requests.</li><li><strong>Airflow</strong>: Automates workflows and scheduling tasks, ensuring reliable execution of backtests and data pipeline operations.</li></ul><p>This technology stack ensures scalability, reliability, and efficiency in building a comprehensive cryptocurrency trading platform, from data processing and analysis to frontend user interaction and automated workflow management.</p><h4>Project Implementation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0U6zYOefVl4pLNcj-oll4g.jpeg" /></figure><p><strong>Data Exploration</strong></p><p>We performed several data exploration activities to gain insights into the trading data. Here are a couple of key analyses:</p><ol><li><strong>Analyzing Trading Volume Trends with Moving Averages</strong></li></ol><p>To understand the trading volume trends, we plotted the raw trading volume and overlaid it with a moving average. This helps in smoothing out short-term fluctuations and highlighting longer-term trends.</p><pre>plt.plot(df.index, df[&#39;Volume&#39;], label=&#39;Volume&#39;)<br>plt.plot(df.index, df[&#39;Volume&#39;].rolling(window=4).mean(), label=&#39;Moving Average Volume&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*E9REp4xfkYBnRaB656EY6g.png" /></figure><p><strong>2. Bitcoin Price Over Time</strong></p><p>We analyzed the price movement of Bitcoin over time using candlestick charts. These charts provide a clear visualization of the price changes within specific periods and are useful for identifying trends and patterns.</p><pre>df_indexed = df.set_index(&#39;Date&#39;)<br>mpf.plot(df_indexed, type=&#39;candle&#39;, style=&#39;yahoo&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*DOcz4taeqwMJxaHhKQPKBw.png" /></figure><pre>mpf.plot(df_indexed, type=&#39;candle&#39;, mav=(3,6,9), volume=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*BSNI7vofFsXd7eg2rTM8vQ.png" /></figure><p><strong>Back Testing</strong></p><p>We utilized backtrader to conduct thorough backtesting, providing users with a range of strategies to choose from. The implementation leverages Python functions to execute and assess the performance of selected strategies within specified date ranges.</p><pre>from strategy.sma import SmaStrategy<br>from strategy.ema import EmaStrategy<br>from strategy.rsi import RsiStrategy<br>from strategy.macd import MacdStrategy<br>from strategy.adx import AdxStrategy<br>from strategy.cci import CciStrategy<br>from backtest import run_backtest<br>import sys<br>import os<br>import json<br><br><br><br><br>sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), &#39;..&#39;)))<br>from kafka_scripts.kafka_consumer import consume_backtest_request<br>from kafka_scripts.kafka_producer import send_backtest_results<br><br><br>sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), &#39;../mlflow&#39;)))<br>from mlflow_track import track<br><br>with open(&#39;backtest/config.json&#39;, &#39;r&#39;) as f:<br>    data_config = json.load(f)<br><br>def main(name, strategy_name, start_date, end_date, params, start_cash, comm):<br>    strategy_map = {<br>        &#39;sma&#39;: SmaStrategy,<br>        &#39;ema&#39;: EmaStrategy,<br>        &#39;rsi&#39;: RsiStrategy,<br>        &#39;MACD&#39;: MacdStrategy,<br>        &#39;adx&#39;: AdxStrategy,<br>        &#39;cci&#39;: CciStrategy<br>    }<br>    data_path = f&#39;data/{data_config[name]}.csv&#39;<br><br>    if strategy_name in strategy_map:<br>        strategy = strategy_map[strategy_name]<br>        results = run_backtest( strategy, params, data_path, start_date, end_date, start_cash, comm)<br>        <br>        # Extract desired metrics<br>        num_trades = results[&#39;trade_analyzer&#39;].total.total<br>        winning_trades = results[&#39;trade_analyzer&#39;].won.total<br>        losing_trades = results[&#39;trade_analyzer&#39;].lost.total<br>        max_drawdown = results[&#39;drawdown&#39;].max.drawdown<br>        sharpe_ratio = results[&#39;sharperatio&#39;][&#39;sharperatio&#39;]<br><br>        metrics = {<br>            &#39;Number of trades&#39;: num_trades,<br>            &#39;Winning trades&#39;: winning_trades,<br>            &#39;Losing trades&#39;: losing_trades,<br>            &#39;Max drawdown&#39;: max_drawdown,<br>            &#39;Sharpe ratio&#39;: sharpe_ratio<br>        }<br><br>        track(name, strategy, start_date, end_date, start_cash, comm, params, metrics)<br><br>        # Return extracted metrics<br>        return metrics<br>    else:<br>        print(f&quot;Strategy {strategy_name} is not recognized.&quot;)<br>        return None<br><br>if __name__ == &#39;__main__&#39;:<br>    for inputs in consume_backtest_request():<br>        print(inputs)<br>        results = main(*inputs)<br>        send_backtest_results(results)<br>        print(results)</pre><p><strong>Integration with Kafka and MLflow</strong></p><p>kafka_producer.py</p><pre>import json<br>from kafka import KafkaProducer<br><br># Create Kafka producer<br>producer = KafkaProducer(bootstrap_servers=&#39;localhost:9092&#39;, value_serializer=lambda v: json.dumps(v).encode(&#39;utf-8&#39;))<br><br>def send_backend_request(name, start_date, end_date, strategy, params, start_cash, comm):<br>    message = {<br>        &#39;name&#39;: name,<br>        &#39;start_date&#39;: start_date,<br>        &#39;end_date&#39;: end_date,<br>        &#39;strategy&#39;: strategy,<br>        &#39;params&#39;: params,<br>        &#39;start_cash&#39;: start_cash,<br>        &#39;comm&#39;: comm<br>    }<br><br>    # Produce message to backend_requests topic<br>    producer.send(&#39;backend_requests&#39;, value=message)<br>    producer.flush()<br><br># Define function to send backtest results<br>def send_backtest_results(metrics):<br>    message = {<br>        &#39;metrics&#39;: metrics<br>    }<br>    producer.send(&#39;backtest_results&#39;, value=message)<br>    producer.flush()</pre><p>kafka_consumer.py</p><pre>from kafka import KafkaConsumer<br>import json<br>import sys<br>import os<br>import logging<br>def consume_backtest_request():<br>    consumer = KafkaConsumer(<br>        &#39;backend_requests&#39;,<br>        bootstrap_servers=&#39;localhost:9092&#39;,<br>        auto_offset_reset=&#39;latest&#39;,<br>        value_deserializer=lambda v: json.loads(v.decode(&#39;utf-8&#39;))<br>    )<br><br>    for message in consumer:<br>        name = message.value[&#39;name&#39;]<br>        start_date = message.value[&#39;start_date&#39;]<br>        end_date = message.value[&#39;end_date&#39;]<br>        strategy = message.value[&#39;strategy&#39;]<br>        params = message.value[&#39;params&#39;]<br>        start_cash = message.value[&#39;start_cash&#39;]<br>        comm = message.value[&#39;comm&#39;]<br><br>        yield name, strategy, start_date, end_date, params, start_cash, comm<br><br><br>def consume_backtest_results():<br>    consumer = KafkaConsumer(<br>        &#39;backtest_results&#39;,<br>        bootstrap_servers=&#39;localhost:9092&#39;,<br>        auto_offset_reset=&#39;latest&#39;,<br>        # consumer_timeout_ms=30000,<br>        value_deserializer=lambda v: json.loads(v.decode(&#39;utf-8&#39;)),<br>        <br>    )<br><br>    for message in consumer:<br>        metrics = message.value[&#39;metrics&#39;]<br><br>        return metrics</pre><p>The information for backtesting will be received from a Kafka producer on the backend_requests topic. Upon consuming this information, the chosen strategy is executed for backtesting. Subsequently, both the parameters and the resulting metrics are logged into MLflow for tracking and analysis purposes. Finally, the computed metrics are passed back to Kafka on the backtest_results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a7dpFJAxdn69IvjfUoqnkg.png" /></figure><p><strong>Backend</strong></p><p>We developed a comprehensive backend using FastAPI to handle user authentication, data processing, and integration with other services.</p><ul><li><strong>User Authentication</strong>: Implemented a secure database to manage user credentials and authentication processes, ensuring only authorized access to the system.</li><li><strong>Data Management</strong>: Created a database schema to store backtesting information, including user inputs and backtrader results. This allows for efficient retrieval and storage of historical backtesting data.</li><li><strong>User Input Handling</strong>: The backend receives user inputs from the frontend, processes these inputs, and initiates the appropriate backtesting procedures.</li><li><strong>Backtesting Integration</strong>: After processing the user’s input, the backtesting request is sent to Kafka. The results from the backtesting process are then consumed from Kafka and passed back to the frontend for display.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZh2tSt5YKSutBahK8QJAw.png" /></figure><p><strong>Database Schema — Entity Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*psvLlVxxC-gISLkg_qNOmg.png" /></figure><p><strong>Frontend</strong></p><p>Using React, we developed an interactive user interface (UI) that allows users to input their backtesting parameters and view results.</p><ul><li><strong>User Inputs</strong>: The UI provides fields for users to input the following details:</li><li>Cryptocurrency</li><li>Strategy</li><li>Parameters for the strategy</li><li>Start date of analysis</li><li>End date of analysis</li><li>Commission</li><li><strong>Real-Time Feedback</strong>: Once the user submits their inputs, the frontend sends these details to the backend. It then waits for the processed backtesting results, which are fetched from Kafka and displayed to the user.</li><li><strong>User-Friendly Design</strong>: The React interface is designed to be intuitive, ensuring users can easily navigate and input their desired backtesting configurations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRfMPZYbmFJdATIA2_13Uw.png" /></figure><p><strong>Docker</strong></p><p>To streamline the deployment process, we containerized Kafka and MLflow using Docker. This setup ensures that all components are consistently configured and easily deployable across different environments.</p><p>Below is the Docker Compose configuration:</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  zookeeper:<br>    image: confluentinc/cp-zookeeper:latest<br>    environment:<br>      ZOOKEEPER_CLIENT_PORT: 2181<br>      ZOOKEEPER_TICK_TIME: 2000<br>    ports:<br>      - &quot;2181:2181&quot;<br>    networks:<br>      - backend-tier<br><br>  kafka:<br>    image: confluentinc/cp-kafka:latest<br>    depends_on:<br>      - zookeeper<br>    ports:<br>      - &quot;9092:9092&quot;<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>    networks:<br>      - backend-tier<br><br>  mlflow:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.mlflow<br>    command: mlflow server --host 0.0.0.0<br>    ports:<br>      - &quot;5000:5000&quot;<br><br>networks:<br>  backend-tier:<br>    driver: bridge</pre><h4><strong>Limitations and Future Improvements</strong></h4><p><strong>Limitations</strong></p><ul><li><strong>Static Data</strong>: The current implementation relies on real-time data limited to specific dates. This restricts the backtesting to predefined time frames rather than continuously updated data.</li><li><strong>Complex Setup</strong>: The need to manually run multiple scripts and before starting the frontend makes the deployment process cumbersome and less efficient.</li></ul><p><strong>Future Improvements</strong></p><ul><li><strong>API Integration</strong>: Incorporate real-time data from APIs to allow for continuous and up-to-date backtesting, enhancing the relevance and accuracy of the results.</li><li><strong>Complete Dockerization</strong>: While we have already dockerized Kafka and MLflow, further containerizing all components (including the backend and frontend) will simplify the deployment process. This will make the system more efficient and ensure consistency across different environments.</li><li><strong>Frontend Model Training Results</strong>: Develop a feature to display model training results on the frontend. This will allow users to view and analyze the performance metrics of different models directly through the user interface, enhancing transparency and usability.</li></ul><h4>Conclusions</h4><p>In this project, we successfully developed a backtesting system for users to evaluate cryptocurrency trading strategies. By leveraging a combination of backtrader, FastAPI, React, Kafka, and MLflow, we built a comprehensive platform that allows users to input their trading parameters and receive detailed performance metrics. While there are limitations regarding data and setup complexity, future improvements such as real-time API integration and Dockerization will further enhance the system&#39;s functionality and ease of use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=596ba497887b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic optimization: Delivery drivers location optimisation with Causal Inference]]></title>
            <link>https://medium.com/@Yohanes213/logistic-optimization-delivery-drivers-location-optimisation-with-causal-inference-3c7c45d5b56d?source=rss-b0e5a4e1d5de------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c7c45d5b56d</guid>
            <category><![CDATA[causal-inference]]></category>
            <dc:creator><![CDATA[Yohanes Teshome Kebede]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 16:00:32 GMT</pubDate>
            <atom:updated>2024-07-26T14:37:59.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*o4lpcf-fCgXN9efqRXJnEg.png" /><figcaption><strong>Causal Inference</strong></figcaption></figure><h4><strong>The Objective of the Project</strong></h4><p><a href="https://www.gokada.ng/">Gokada</a> is the largest last mile delivery service in Nigeria. Gokada Works is partnered with motorbike owners and drivers to deliver parcels across Lagos, Nigeria. Gokada has completed more than a million deliveries in less than a year, with a fleet of over 1200 riders.</p><p>One key issue Gokada has faced as it expands its service is the sub-optimal placement of pilots (Gokada calls their motor drivers pilots) and clients who want to use Gokada to send their parcel. This has led to a high number of unfulfilled delivery requests.</p><p>We are asked to work on its data to help it understand the primary causes of unfulfilled requests as well as come up with solutions that recommend drivers locations that increase the fraction of complete orders. Since drivers are paid based on the number of requests they accept, your solution will help Gokada business grow both in terms of client satisfaction and increased business.</p><h4>What is Causal Inference</h4><p>Causal inference is the process of determining the cause-and-effect relationship between variables or events. In other words, it’s about understanding how changes in one variable affect another. This concept is crucial in various fields, including statistics, economics, epidemiology, and machine learning.</p><p>At its core, causal inference seeks to answer questions like:</p><ol><li><strong>What is the effect of X on Y?</strong></li><li><strong>Does X cause Y, or is it the other way around?</strong></li><li><strong>What would have happened if X had been different?</strong></li></ol><p><strong>Why is Causal Inference Important?</strong></p><p>In many situations, especially in scientific research or business decision-making, we need to understand not just the correlation between variables, but whether changes in one variable actually cause changes in another. For example:</p><ul><li>Does a new drug treatment cause an improvement in patient outcomes?</li><li>Does advertising spending lead to increased sales?</li><li>Does education level affect earning potential?</li></ul><h4>Data Overview</h4><p>In this project, we have access to two main datasets:</p><p><strong>1. Completed Orders Dataset:</strong></p><p>This dataset contains information about completed orders.</p><p>Columns include:</p><ul><li>Trip ID: Unique identifier for each trip (536020 entries)</li><li>Trip Origin: Address where the trip started</li><li>Trip Destination: Address where the trip ended</li><li>Trip Start Time: Timestamp indicating when the trip started</li><li>Trip End Time: Timestamp indicating when the trip ended</li></ul><p><strong>2. Delivery Requests Dataset:</strong></p><p>This dataset includes delivery requests made by clients, both completed and unfulfilled.</p><p>Columns include:</p><ul><li>ID: Unique identifier for each delivery request (1557740 entries)</li><li>Order ID: Unique identifier for the order</li><li>Driver ID: Unique identifier for the driver assigned to the delivery</li><li>Driver Action: Indicates whether the driver accepted or rejected the delivery request</li><li>Latitude (Lat) and Longitude (Lng): Coordinates of the delivery location</li><li>Created At: Timestamp indicating when the delivery request was created</li><li>Updated At: Timestamp indicating when the delivery request was last updated</li></ul><p><strong>Important Note:</strong> The created_atand updated_at columns seem to have missing values (0 non-null entries).</p><h4>Project Implementation</h4><h4>1. Data Exploration</h4><p><strong>Dropping Columns</strong></p><p>During the initial data exploration phase, column created_atand updated_at from the delivery request table are dropped, since all of the data point is null.. The focus was on enhancing efficiency and preparing the data for further analysis.</p><pre>    def remove_columns(df, columns):<br>        try:<br>            df.drop(columns=columns, inplace=True)<br><br>            logger.info(f&#39;Successfully drop {columns}&#39;)<br>            return df<br>        except Exception as e:<br>            logger.error(f&quot;Error dropping {columns} columns&quot;)</pre><p><strong>Converting data columns</strong></p><p>To ensure consistency and enable proper analysis, certain columns such as Trip Start Timeand Trip End Time were converted to datetime format.</p><pre>    def change_datetime(self, df, date_columns):<br>        &quot;&quot;&quot;<br>        Changes specified columns to datetime format in the DataFrame.<br><br>        Params:<br>            df (pd.DataFrame): The DataFrame containing the data.<br>            date_columns (list): A list of column names to be converted to datetime.<br><br>        Returns:<br>            pd.DataFrame: The DataFrame with specified columns converted to datetime format.<br>        &quot;&quot;&quot;<br>        try:<br>            for column in date_columns:<br>                df[column] = pd.to_datetime(df[column])<br>            logger.info(f&quot;Converted columns {date_columns} to datetime format&quot;)<br>            return df<br>        except Exception as e:<br>            logger.error(f&quot;Error converting columns to datetime: {e}&quot;)<br>            return df</pre><p><strong>Distance</strong></p><p>Using geographical coordinates from Trip Originand Trip Destination, distances in kilometers were calculated to understand travel distances.</p><pre>def calculate_distance(self, origin_str, destination_str):<br>        &quot;&quot;&quot;<br>        Calculate the distance from the lat and lon.<br><br>        params:<br>            df (pd.DataFrmae): The dataframe containing the data.<br>            origin_str (str): The data containing the origin lat and lon.<br>            destination_str: The data containing the destination lat and lon.<br>        <br>        Returns:<br>            distance (float): The calculated distance in km. <br>        &quot;&quot;&quot;<br>        try: <br>            origin_lat, origin_lon = map(float, origin_str.split(&quot;,&quot;))<br>            dest_lat, dest_lon = map(float, destination_str.split(&quot;,&quot;))<br><br>            origin = (origin_lat, origin_lon)<br>            destination = (dest_lat, dest_lon)<br><br>            distance = geodesic(origin, destination).km<br><br>            return distance<br>        except Exception as e:<br>            logger.error(f&quot;Error converting {origin_str, destination_str}: {e}&quot;)</pre><p><strong>Duration</strong></p><p>Duration between Trip Start Timeand Trip End Time was calculated to understand the duration of each trip.</p><pre>    def calculate_duration(self, df,start_time, end_time):<br>        &quot;&quot;&quot;<br>        Calculate the duration in hours.<br><br>        params:<br>            df (pd.DataFrmae): The dataframe containing the data.<br>            start_time (pd.DataFrame): The data containing the start time.<br>            end_time (pd.DataFrame): The data containing the end time.<br>        <br>        Returns:<br>            duration (float): The duration time <br>        &quot;&quot;&quot;<br><br>        try:<br>            return (df[end_time] - df[start_time])/ pd.Timedelta(hours=1)<br>        except Exception as e:<br>            logger.error(f&quot;Error Calucation the duration for {start_time} {end_time}: {e}&quot;)</pre><h4>Impute</h4><p>We have null elements on columns, meaning the calculated duration have null elements.</p><pre>#   Column            Non-Null Count   Dtype <br>---  ------            --------------   ----- <br> 0   Trip ID           536020 non-null  int64 <br> 1   Trip Origin       536020 non-null  address<br> 2   Trip Destination  536020 non-null  address<br> 3   Trip Start Time   534369 non-null  timestamp<br> 4   Trip End Time     536019 non-null  timestamp</pre><p>For columns like Trip Start Timeand Trip End Time which represent the start and end of each trip respectively, it’s crucial to handle missing values effectively. Since these timestamps are essential for our analysis, a thoughtful imputation strategy is necessary.</p><p>Given that these timestamps are interrelated with the duration of each trip, a reasonable approach is to impute missing durations based on the nearest known data. Here’s how I handled it:</p><pre>    def impute_elements(df, distance, column):<br>        try:<br>            for i, row in df.iterrows():<br>                if pd.null(row[column]):<br>                    closest_index = np.argmin(distances[i])<br>                    closest_duration = df[column][closest_index]<br>                    df.at[i, column] = closest_duration<br>            logger.info(f&#39;Succesfully imputed {column}&#39;)<br>            return df<br>        <br>        except Exception as e:<br>            logger.error(f&#39;Error imputing {column}&#39;)</pre><p><strong>Explanation:</strong></p><p>Since the trip start and end times are crucial timestamps, we can’t afford to drop them. Instead, I developed a method to impute missing durations based on the closest known data point. Here’s the approach:</p><ol><li><strong>Find Closest Duration:</strong> From the calculated distances, we identify the closest known trip distance to the missing duration.</li><li><strong>Impute Missing Duration:</strong> We then use the duration corresponding to the closest distance to fill in the missing duration data.</li></ol><p>This approach ensures that our imputation is based on relevant information, maintaining the integrity of the dataset for further analysis.</p><p><strong>Speed</strong></p><p>Using the duration and distance we can calculate the speed.</p><pre>def apply_distance_duration(pipeline, df, origin_cols, destination_cols, start_time_col, end_time_col):<br>    &quot;&quot;&quot;<br>    Applies distance and duration calculations to the DataFrame and adds new columns for distance, duration, and speed.<br><br>    Params:<br>        df (pd.DataFrame): The DataFrame containing the data.<br>        origin_cols (list): A list of column names containing origin latitudes and longitudes.<br>        destination_cols (list): A list of column names containing destination latitudes and longitudes.<br>        start_time_col (str): The column name containing the start time.<br>        end_time_col (str): The column name containing the end time.<br><br>    Returns:<br>        pd.DataFrame: The original DataFrame with additional columns for distance, duration, and speed.<br>    &quot;&quot;&quot;<br>    try:<br>        for origin_col, destination_col in zip(origin_cols, destination_cols):<br>            df[f&#39;Distance (km)&#39;] = df.apply(<br>                lambda row: pipeline.calculate_distance(row[origin_col], row[destination_col]), axis=1)<br>            logger.info(f&quot;Applied distance calculation to DataFrame for {origin_col} and {destination_col}&quot;)<br><br>        df[&#39;Duration (hr)&#39;] = pipeline.calculate_duration(df, start_time_col, end_time_col)<br>        logger.info(f&quot;Applied duration calculation to DataFrame using {start_time_col} and {end_time_col}&quot;)<br>        <br>        df = pipeline.impute_elements(df, df[&#39;Distance (km)&#39;], &#39;Duration (hr)&#39;)<br><br>        df[&#39;Speed (km/hr)&#39;] = df[&#39;Distance (km)&#39;] / df[&#39;Duration (hr)&#39;]<br>        logger.info(&quot;Calculated speed&quot;)<br><br>        logger.info(f&quot;Distance, duration, and speed calculations applied to {len(df)} rows.&quot;)<br>        return df<br>    except Exception as e:<br>        logger.error(f&quot;Error applying distance, duration, and speed calculations: {e}&quot;)<br>        return df</pre><p><strong>Remove Outliers</strong></p><p>After calculating the speed, we can see that there are outliers. So, using this column we will remove the outliers</p><pre>    def remove_outliers(df, column, lower_quantile = 0.25, upper_quantile = 0.75):<br>        try:<br>            Q1 = df[column].quantile(lower_quantile)<br>            Q3 = df[column].quantile(upper_quantile)<br><br>            IQR = Q3 - Q1<br><br>            lower_bound = Q1 - 1.5 * IQR<br>            upper_bound = Q3 + 1.5 * IQR<br><br>            df_no_outliers = df[df[column] &gt;= lower_bound &amp; df[column] &lt;= upper_bound]<br><br>            logger.info(f&#39;Succesfully removed outliers using column {column}&#39;)<br>            return df_no_outliers<br>        <br>        except Exception as e:<br>            logger.error(&#39;Error Removing outliers&#39;)</pre><p><strong>Additional Features</strong></p><p>We added other features, for analysis.</p><pre>    def is_weekend(self, date):<br>        &quot;&quot;&quot;<br>        Checks if a given date is a weekend.<br><br>        Params:<br>            date (datetime): The date to check.<br><br>        Returns:<br>            bool: True if the date is a weekend (Saturday or Sunday), False otherwise.<br>        &quot;&quot;&quot;<br>        try:<br>            return date.weekday() &gt;= 5<br>        except Exception as e:<br>            logger.error(f&quot;Error checking if date is weekend: {e}&quot;)<br>            return False<br><br>    def is_holiday(self, date):<br>        &quot;&quot;&quot;<br>        Checks if a given date is a holiday.<br><br>        Params:<br>            date (datetime): The date to check.<br><br>        Returns:<br>            bool: True if the date is a holiday, False otherwise.<br>        &quot;&quot;&quot;<br>        try:<br>            return date in self.holidays<br>        except Exception as e:<br>            logger.error(f&quot;Error checking if {date} column is holiday: {e}&quot;)<br>            return False</pre><p>We noticed that is_holiday wasn’t helpful, since in our final cleaned dataset, there is only a data for non-holidays days.</p><p>From the delivery table, I calculated the distance from the driver location to the trip origin location to understand if that have effect on driver acceptance and rejection of an order</p><pre>     def calculate_driver_to_Trip_origin(df_driver, df_completed):<br>        try:<br>            for index, row in df_driver.iterows():<br>                order_id = row[&#39;order_id&#39;]<br>                if order_id in df_completed[&#39;Trip ID&#39;].unique():<br>                    origin_lat = df_completed[df_completed[&#39;Trip ID&#39;] == order_id][&#39;Origin Lat&#39;].iloc[0]<br>                    origin_lon = df_completed[df_completed[&#39;Trip ID&#39;] == order_id][&#39;Origin Lon&#39;].iloc[0]<br><br>                    origin = (origin_lat, origin_lon)<br><br>                    driver_loc = (row[&#39;lat&#39;], row[&#39;lng&#39;])<br><br>                    df_driver.at[index, &#39;Distance From Trip Origin&#39;] = geodesic(origin, driver_loc).km<br><br>            logger.info(&#39;Sucessfuly Complted calculating the distance from the driver location to trip origin&#39;)<br>            return df_driver<br><br>        except Exception as e:<br>            logger.error(&quot;Error Calculating the distance from the driver location to trip origin&quot;)</pre><p>So, after cleaning our data and adding some features, this is what our last data looks like.</p><pre>Data columns (total 10 columns):<br> #   Column                          Non-Null Count    Dtype  <br>---  ------                          --------------    -----  <br> 0   id                              1440254 non-null  int64  <br> 1   order_id                        1440254 non-null  int64  <br> 2   driver_id                       1440254 non-null  int64  <br> 3   driver_action                   1440254 non-null  object <br> 4   lat                             1440254 non-null  float64<br> 5   lng                             1440254 non-null  float64<br> 6   Distance From Trip Origin       1440254 non-null  float64<br> 7   Distance (Trip to Destination)  1440254 non-null  float64<br> 8   is_weekend                      1440254 non-null  bool   <br> 9   is_holiday                      1440254 non-null  bool  </pre><h4>2. Visualization</h4><p>To enhance the user experience and provide a clear understanding of order tracking, I created an interactive web page. This page allows users to input their order details and visualize the locations where drivers have accepted or rejected the order, as well as the trip origin and destination. Here’s a detailed walkthrough of the visualization:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Gokada Order Tracking&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://unpkg.com/leaflet/dist/leaflet.css&quot; /&gt;<br>    &lt;script src=&quot;https://unpkg.com/leaflet/dist/leaflet.js&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Track Your Order&lt;/h1&gt;<br>    &lt;input type=&quot;text&quot; id=&quot;order_id&quot; placeholder=&quot;Enter Order ID&quot; /&gt;<br>    &lt;button onclick=&quot;trackOrder()&quot;&gt;Track&lt;/button&gt;<br>    &lt;div id=&quot;map&quot; style=&quot;height: 500px;&quot;&gt;&lt;/div&gt;<br><br>    &lt;script&gt;<br>        // Initialize the map<br>        const map = L.map(&#39;map&#39;).setView([6.5244, 3.3792], 12); // Centered on Lagos<br>        L.tileLayer(&#39;https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png&#39;, {<br>            maxZoom: 18<br>        }).addTo(map);<br><br>        let originMarker, destMarker, acceptedDriversMarkers = [], rejectedDriversMarkers = [];<br><br>        function trackOrder() {<br>            const orderId = document.getElementById(&#39;order_id&#39;).value;<br>            console.log(&#39;Tracking order:&#39;, orderId); // Debugging<br><br>            // Clear existing markers<br>            if (originMarker) map.removeLayer(originMarker);<br>            if (destMarker) map.removeLayer(destMarker);<br>            acceptedDriversMarkers.forEach(marker =&gt; map.removeLayer(marker));<br>            rejectedDriversMarkers.forEach(marker =&gt; map.removeLayer(marker));<br><br>            fetch(`http://127.0.0.1:5000/order/${orderId}`)<br>                .then(response =&gt; {<br>                    console.log(&#39;Order response:&#39;, response);<br>                    if (!response.ok) {<br>                        throw new Error(&#39;Order not found&#39;);<br>                    }<br>                    return response.json();<br>                })<br>                .then(order =&gt; {<br>                    if (order.error) {<br>                        alert(order.error);<br>                        return;<br>                    }<br>                    console.log(&#39;Order details:&#39;, order); // Debugging<br>                    const origin = [order[0].origin_lat, order[0].origin_lon];<br>                    const dest = [order[0].dest_lat, order[0].dest_lon];<br>                    originMarker = L.marker(origin, {icon: greenIcon}).addTo(map).bindPopup(&#39;Origin&#39;).openPopup();<br>                    destMarker = L.marker(dest, {icon: redIcon}).addTo(map).bindPopup(&#39;Destination&#39;).openPopup();<br>                })<br>                .catch(error =&gt; {<br>                    console.error(&#39;Error fetching order:&#39;, error); // Debugging<br>                    alert(&#39;Order not found&#39;);<br>                });<br><br>            fetch(`http://127.0.0.1:5000/driver/${orderId}`)<br>                .then(response =&gt; {<br>                    console.log(&#39;Driver response:&#39;, response);<br>                    if (!response.ok) {<br>                        throw new Error(&#39;Driver data not found&#39;);<br>                    }<br>                    return response.json();<br>                })<br>                .then(data =&gt; {<br>                    if (data.error) {<br>                        alert(data.error);<br>                        return;<br>                    }<br>                    console.log(&#39;Driver details:&#39;, data); // Debugging<br>                    data.accepted_driver.forEach(coord =&gt; {<br>                        const marker = L.marker(coord, {icon: orangeIcon}).addTo(map).bindPopup(&#39;Accepted Driver&#39;).openPopup();<br>                        acceptedDriversMarkers.push(marker);<br>                    });<br>                    data.rejected_drivers.forEach(coord =&gt; {<br>                        const marker = L.marker(coord).addTo(map).bindPopup(&#39;Rejected Driver&#39;).openPopup();<br>                        rejectedDriversMarkers.push(marker);<br>                    });<br>                })<br>                .catch(error =&gt; {<br>                    console.error(&#39;Error fetching driver data:&#39;, error); // Debugging<br>                    alert(&#39;Driver data not found&#39;);<br>                });<br>        }<br><br>        // Define custom icons<br>        const greenIcon = new L.Icon({<br>            iconUrl: &#39;https://leafletjs.com/examples/custom-icons/leaf-green.png&#39;,<br>            iconSize: [38, 95],<br>            iconAnchor: [22, 94],<br>            popupAnchor: [-3, -76],<br>        });<br><br>        const redIcon = new L.Icon({<br>            iconUrl: &#39;https://leafletjs.com/examples/custom-icons/leaf-red.png&#39;,<br>            iconSize: [38, 95],<br>            iconAnchor: [22, 94],<br>            popupAnchor: [-3, -76],<br>        });<br><br>        const orangeIcon = new L.Icon({<br>            iconUrl: &#39;https://leafletjs.com/examples/custom-icons/leaf-orange.png&#39;,<br>            iconSize: [38, 95],<br>            iconAnchor: [22, 94],<br>            popupAnchor: [-3, -76],<br>        });<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>The web-page looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qyAYTGw9nBlEXEquUgo7Gg.png" /></figure><h4>3. Causal learning</h4><p>For this project, I utilized causalnex library to perform causal learning. Causalnex expects certain column names and data types, so I prepared the data accordingly:</p><pre># Renaming columns to meet causalnex requirements<br>df.rename(columns={<br>    &#39;Distance (Trip to Destination)&#39;: &#39;Distance_Trip_to_Destination&#39;,<br>    &#39;Distance From Trip Origin&#39;: &#39;Distance_From_Trip_Origin&#39;,<br>    &#39;lat&#39;: &#39;latitude&#39;,<br>    &#39;lng&#39;: &#39;longitude&#39; <br>}, inplace=True)<br><br># Encoding non-numeric data using LabelEncoder<br>le = LabelEncoder()<br><br>non_numeric_columns = list(df.select_dtypes(exclude=&#39;number&#39;).columns)<br><br>for col in non_numeric_columns:<br>    df[col] = le.fit_transform(df[col])</pre><p>Causalnex operates with discrete data, so I discretized continuous variables:</p><pre># Discretize the continuous variables<br>discretizer_distance_origin = KBinsDiscretizer(n_bins=10, encode=&#39;ordinal&#39;, strategy=&#39;uniform&#39;)<br>discretizer_distance_destination = KBinsDiscretizer(n_bins=10, encode=&#39;ordinal&#39;, strategy=&#39;uniform&#39;)<br>discretizer_latitude = KBinsDiscretizer(n_bins=10, encode=&#39;ordinal&#39;, strategy=&#39;uniform&#39;)<br>discretizer_longitude = KBinsDiscretizer(n_bins=10, encode=&#39;ordinal&#39;, strategy=&#39;uniform&#39;)<br><br><br>df[&#39;Distance_From_Trip_Origin&#39;] = discretizer_distance_origin.fit_transform(df[[&#39;Distance_From_Trip_Origin&#39;]]).astype(int)<br>df[&#39;Distance_Trip_to_Destination&#39;] = discretizer_distance_destination.fit_transform(df[[&#39;Distance_Trip_to_Destination&#39;]]).astype(int)<br>df[&#39;latitude&#39;] = discretizer_latitude.fit_transform(df[[&#39;latitude&#39;]]).astype(int)<br>df[&#39;longitude&#39;] = discretizer_longitude.fit_transform(df[[&#39;longitude&#39;]]).astype(int)</pre><p>Next, defining the columns we’ll use and building our structure model:</p><pre>cols = [&#39;is_weekend&#39;, &#39;latitude&#39;, &#39;longitude&#39;, &#39;driver_action&#39;, &#39;Distance_From_Trip_Origin&#39;, &#39;Distance_Trip_to_Destination&#39;]<br><br># Structure model<br>sm = StructureModel()<br><br># Adding edges to the structure model<br>driver_action_relations = [(col, &#39;driver_action&#39;) for col in cols if col != &#39;driver_action&#39;]<br>structure_model.add_edges_from(driver_action_relations)<br><br># Visualizing the causal structure<br>viz = plot_structure(sm, all_node_attributes=NODE_STYLE.WEAK, all_edge_attributes=EDGE_STYLE.WEAK)<br>viz.show(&quot;causal_structure.html&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EijOSgK2HLBIXGZ5x1_HOw.jpeg" /></figure><p>Splitting the data into training and testing sets:</p><pre>from sklearn.model_selection import train_test_split<br><br>train, test = train_test_split(df[cols], test_size=0.2, random_state=42)<br><br># Create the Bayesian Network<br>bn = BayesianNetwork(sm)<br><br># Fit CPDs<br>bn = bn.fit_node_states_and_cpds(train)</pre><p>To better understand the conditional probability distributions (CPDs), we visualized them using kernel density estimation and correlation heatmap:</p><pre>sns.kdeplot(data=df_cpd, x=&#39;prob_driver_action_0&#39;, label=&#39;Driver Action 0&#39;, shade=True)<br>sns.kdeplot(data=df_cpd, x=&#39;prob_driver_action_1&#39;, label=&#39;Driver Action 1&#39;, shade=True)<br>plt.xlabel(&#39;Probability&#39;)<br>plt.ylabel(&#39;Density&#39;)<br>plt.title(&#39;Kernel Density Estimation of Driver Actions&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*iKJmprHMBUP2d398lOIquw.png" /></figure><pre>plt.figure(figsize=(10, 6))<br>sns.heatmap(df_cpd.corr(), annot=True, cmap=&#39;coolwarm&#39;, fmt=&quot;.2f&quot;)<br>plt.title(&#39;Correlation Heatmap&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*qgvxTTDitxgB8Cnq93Fp7A.png" /></figure><p><strong>Inference</strong></p><pre>ie = InferenceEngine(bn)<br><br>marginals = ie.query({})<br><br>print(marginals)</pre><pre>{&#39;is_weekend&#39;: {0: 0.8726667563497693, 1: 0.12733324365021595},<br> &#39;driver_action&#39;: {0: 0.9259156128562702, 1: 0.07408438714372964},<br> &#39;latitude&#39;: {0: 0.10491289370975616,<br>  1: 0.10088412472346694,<br>  2: 0.0807663166445787,<br>  3: 0.15736152950886648,<br>  4: 0.2387987290544357,<br>  5: 0.21276534807366443,<br>  6: 0.08487232829346668,<br>  7: 0.0180044835460111,<br>  8: 0.0015266274551667088,<br>  9: 0.00010761899058594099},<br> &#39;longitude&#39;: {0: 1.7357901707410013e-05,<br>  1: 0.0004495696542219168,<br>  2: 0.00959978753928311,<br>  3: 0.22976828069115598,<br>  4: 0.593003203400762,<br>  5: 0.09221819229604196,<br>  6: 0.06357678658373027,<br>  7: 0.010654280068008243,<br>  8: 0.0006648076353938016,<br>  9: 4.773422969537757e-05},<br> &#39;Distance_From_Trip_Origin&#39;: {0: 0.9129362366159726,<br>  1: 0.08687976962592878,<br>  2: 7.550687242723403e-05,<br>  3: 4.339475426852492e-05,<br>  4: 3.124422307333787e-05,<br>  5: 1.1282636109816501e-05,<br>  6: 9.54684593907553e-06,<br>  7: 3.471580341481998e-06,<br>  8: 3.471580341481998e-06,<br>  9: 6.0752655975934945e-06},<br> &#39;Distance_Trip_to_Destination&#39;: {0: 0.5483959996979748,<br>  1: 0.32408851488396606,<br>  2: 0.09434453525520001,<br>  3: 0.0264187263986781,<br>  4: 0.005141410485734805,<br>  5: 0.0009564203840782931,<br>  6: 0.00030549907005041635,<br>  7: 6.596002648815856e-05,<br>  8: 3.7319488670931445e-05,<br>  9: 0.00024561430915985094}}</pre><h4>Insights from Causal Inference on Driver Actions</h4><p>In our analysis, we utilized a Bayesian Network to model and predict driver actions based on various factors. By performing interventions on these factors, we can observe how changes in each variable influence the likelihood of a particular driver action. Here are the insights derived from our interventions:</p><p><strong>1. Distance From Trip Origin</strong></p><ul><li><strong>Initial Insight</strong>: At a distance of 0 units from the trip origin, the likelihood of a certain driver action (denoted as action 0) is approximately 92.6%.</li><li><strong>Trend</strong>: As the distance increases, the probability of action 1 increases, indicating a shift in driver behavior as they move further from the trip origin.</li><li><strong>Significant Change</strong>: Around a distance of 2–5 units, there is a notable shift where the probability of action 1 increases significantly, reaching approximately 49.1% at a distance of 5 units.</li></ul><p><strong>Causal Insight</strong></p><p>The distance from the trip origin has a significant causal impact on driver actions. As drivers move further from their starting point, their likelihood of switching actions increases markedly.</p><p><strong>2. Distance to Trip Destination</strong></p><ul><li><strong>Initial Insight</strong>: At a distance of 0 units to the destination, action 0 is highly likely with a probability of about 92.9%.</li><li><strong>Trend</strong>: The likelihood of action 1 gradually increases as the distance to the destination increases.</li><li><strong>Significant Change</strong>: Beyond 5 units to the destination, there is a sharp increase in the probability of action 1, peaking at around 42.2% at a distance of 7 units.</li></ul><p><strong>Causal Insight</strong></p><p>Distance from trip origin to the trip destination also causally influences driver actions. The further a trip origin is from the destination, the higher the likelihood of changing their action, particularly beyond 5 units.</p><p><strong>3. Latitude</strong></p><ul><li><strong>Initial Insight</strong>: At a latitude of 0, the likelihood of action 0 is approximately 88.1%.</li><li><strong>Trend</strong>: Fluctuations are observed as latitude changes, but a general pattern emerges where certain latitude values significantly impact driver actions.</li><li><strong>Significant Change</strong>: At latitude 1 and 5, there is a significant decrease in the probability of action 1, indicating these points as critical for influencing driver behavior.</li></ul><p><strong>4. Longitude</strong></p><ul><li><strong>Initial Insight</strong>: At a longitude of 0, the probabilities of actions 0 and 1 are nearly equal.</li><li><strong>Trend</strong>: There is variability in driver actions with changes in longitude, showing different peaks and troughs.</li><li><strong>Significant Change</strong>: Longitudes 4 and 2 show extreme changes where action 0 becomes highly dominant at longitude 4 and less likely at longitude 2.</li></ul><p><strong>Causal Insight</strong></p><p>Latitude and longitude impacts driver actions, with certain latitudes showing a stronger tendency towards action 0 or action 1 or with specific longitudes greatly influencing the likelihood of different actions. These fluctuations suggest geographic location of driver plays a crucial role in driver behavior.</p><p><strong>5. Is Weekend</strong></p><ul><li><strong>Weekday Insight</strong>: On weekdays (is_weekend = 0), the likelihood of action 0 is approximately 58.6%.</li><li><strong>Weekend Insight</strong>: On weekends (is_weekend = 1), there is a higher probability of action 1, suggesting a significant behavioral change during weekends.</li></ul><p><strong>Casual Insight</strong></p><p>The day of the week causally affects driver actions, with weekends seeing a significant increase in the likelihood of action 1 compared to weekdays. This suggests temporal factors play a critical role in influencing driver behavior.</p><h4>Limitations and Future Improvements</h4><p>While our analysis provided valuable insights, there are opportunities for further enhancement:</p><ol><li><strong>Enhanced Analysis for Deeper Insights:</strong> Conducting more extensive analysis can refine our causal inference, providing deeper insights into driver behavior and order fulfillment dynamics.</li><li><strong>Inclusion of Additional Features:</strong> Integrating weather data and other relevant factors can enrich our understanding of driver actions and optimize delivery routes more effectively.</li></ol><p>By addressing these areas, we can improve the accuracy and effectiveness of our optimization strategies for Gokada’s delivery service.</p><h4>Conclusions</h4><p>In this project, we used causal inference to optimize Gokada’s delivery operations. By analyzing key factors influencing driver actions, we aimed to improve efficiency and customer satisfaction.</p><p><strong>Key Points</strong></p><ol><li><strong>Causal Inference Insights:</strong> We identified crucial factors impacting driver actions, vital for enhancing service efficiency.</li><li><strong>Data Analysis and Visualization:</strong> Through thorough data analysis and interactive visualization, we gained actionable insights into order fulfillment.</li></ol><p><strong>In Summary</strong></p><p>Causal inference provides a powerful tool for optimizing delivery operations, driving growth, and ensuring customer satisfaction for Gokada in Nigeria’s competitive market.</p><h4>References</h4><ul><li><a href="https://causalnex.readthedocs.io/en/latest/03_tutorial/01_first_tutorial.html">A first CausalNex tutorial - causalnex 0.12.1 documentation</a></li><li><a href="https://medium.com/data-science-at-microsoft/causal-inference-part-1-of-3-understanding-the-fundamentals-816f4723e54a">Causal inference (Part 1 of 3): Understanding the fundamentals</a></li><li><a href="https://medium.com/@natnaelmelese/causal-inference-d545262755de">Causal Inference</a></li></ul><p>OpenAI. (2024). GPT (Generative Pre-trained Transformer) [Software]. Retrieved from <a href="https://openai.com/gpt">https://openai.com/gpt</a></p><p>Project link: <a href="https://github.com/Yohanes213/Causal-Inference">Causal-Inference</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c7c45d5b56d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Precision RAG: Prompt Tuning For Building Enterprise Grade RAG Systems]]></title>
            <link>https://medium.com/@Yohanes213/precision-rag-prompt-tuning-for-building-enterprise-grade-rag-systems-964ba34b33e7?source=rss-b0e5a4e1d5de------2</link>
            <guid isPermaLink="false">https://medium.com/p/964ba34b33e7</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Yohanes Teshome Kebede]]></dc:creator>
            <pubDate>Sat, 08 Jun 2024 10:16:14 GMT</pubDate>
            <atom:updated>2024-07-26T14:25:04.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*9-tCUVULTSU5mUqk" /><figcaption>RAG</figcaption></figure><h4><strong>The Objective of the Project</strong></h4><p>PromptlyTech is an innovative e-business specializing in providing AI-driven solutions for optimizing the use of Language Models (LLMs) in various industries. The company aims to revolutionize how businesses interact with LLMs, making the technology more accessible, efficient, and effective. By addressing the challenges of prompt engineering, the company plays a pivotal role in enhancing decision-making, operational efficiency, and customer experience across various industries. PromptlyTech’s solutions are designed to cater to the evolving needs of a digitally-driven business landscape, where speed and accuracy are key to staying competitive.</p><p>The company focuses on key services: Automatic Prompt Generation, Automatic Evaluation Data Generation, and Prompt Testing and Ranking.</p><p>1. <strong>Automatic Prompt Generation Service:</strong></p><ul><li>This service streamlines the process of creating effective prompts, enabling businesses to efficiently utilize LLMs for generating high-quality, relevant content. It significantly reduces the time and expertise required in crafting prompts manually.</li></ul><p><strong>2. Automatic Evaluation Data Generation Service:</strong></p><ul><li>PromptlyTech’s service automates the generation of diverse test cases, ensuring comprehensive coverage and identifying potential issues. This enhances the reliability and performance of LLM applications, saving significant time in the QA(Quality Assurance) process.</li></ul><p><strong>3. Prompt Testing and Ranking Service:</strong></p><ul><li>PromptlyTech’s service evaluates and ranks different prompts based on effectiveness, helping Users to get the desired outcome from LLM. It ensures that chatbots and virtual assistants provide accurate, contextually relevant responses, thereby improving user engagement and satisfaction.</li></ul><h4><strong>Background</strong></h4><p>In the evolving field of artificial intelligence, Language Models (LLMs) like GPT-3.5 and GPT-4 have become crucial for various applications. Their effectiveness, however, heavily depends on the quality of the prompts they receive, leading to the emergence of “prompt engineering” as a key skill.</p><p>Prompt engineering is the craft of designing queries or statements to guide LLMs to produce desired outcomes. The challenge lies in the sensitivity of these models to prompt nuances, where slight variations can yield vastly different results. This poses a significant hurdle for users, especially in business contexts where accuracy and relevance are paramount.</p><p>The need for simplified, efficient prompt engineering is clear. Automating and optimizing this process can save time, enhance LLM productivity, and make advanced AI capabilities more accessible to a broader range of users. The tasks of Automatic Prompt Generation, Evaluation Data Generation, and Prompt Testing and Ranking are aimed at addressing these challenges, streamlining the prompt engineering process for more effective use of LLMs.</p><h4><strong>What is RAG (Retrieval Augmented Generation)</strong></h4><p>In the rapidly evolving landscape of natural language processing, Retrieval Augmented Generation (RAG) stands out as a powerful technique that marries the strengths of two distinct approaches: retrieval-based methods and generative models. Understanding RAG involves breaking down these components and exploring how they synergize to enhance performance in tasks such as question answering, summarization, and more.</p><p><strong>Retrieval-Based Methods:</strong> These methods work by fetching relevant information from a pre-existing database or corpus. When a query is presented, the system searches its knowledge base to find the most pertinent pieces of information. Think of it as a highly efficient librarian who quickly pulls out the most relevant books or articles based on your question.</p><p><strong>Generative Models: </strong>On the other hand, generative models, like those built on transformer architectures (e.g., GPT-3), create content by generating text from scratch. They are trained on vast amounts of data and can produce coherent and contextually appropriate responses. However, they may sometimes produce information that sounds plausible but is factually incorrect.</p><p><strong>The RAG Approach:</strong> RAG leverages the best of both worlds. It starts with a retrieval step, where it fetches relevant documents or data snippets based on the input query. These retrieved pieces of information provide a factual grounding. Then, in the generation step, a generative model uses this retrieved information to construct a response. This two-step process helps in ensuring that the generated content is not only contextually relevant but also factually accurate.</p><p><strong>Why RAG is Important:</strong> By combining retrieval and generation, RAG systems are particularly effective in applications requiring precise and reliable information. They reduce the chances of generating incorrect data and improve the overall quality of the responses. This hybrid approach is essential in fields like customer support, medical information systems, and any domain where accuracy is critical.</p><p>In essence, Retrieval Augmented Generation (RAG) represents a significant advancement in the quest for smarter, more reliable AI-driven text generation. It’s a testament to how integrating different AI strategies can lead to superior outcomes, blending the efficiency of retrieval with the creativity of generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*rR12YukOxCrskfIA" /><figcaption>Source: <a href="https://blog.griddynamics.com/retrieval-augmented-generation-llm/">https://blog.griddynamics.com/retrieval-augmented-generation-llm/</a></figcaption></figure><h4><strong>Methodologies</strong></h4><p>In the journey towards building an advanced Retrieval Augmented Generation (RAG) system, key methodologies are followed across various stages of development:</p><ul><li><strong>Review the Evolution of Automatic Prompt Engineering: </strong>Exploring the evolution of automatic prompt engineering involves understanding advancements in RAG systems tailored for enterprise AI applications. This includes understanding advanced prompt engineering techniques, evaluation methods, and tools for generating evaluation data.</li><li><strong>Design and Develop the Prompt Generation System: </strong>Focus is on designing an automated prompt generation system that caters to user objectives. Evaluation metrics are implemented to ensure prompt quality, and existing frameworks are leveraged for enhanced prompt generation.</li><li><strong>Implement Evaluation Data Generation and Evaluation: </strong>Automation is key in generating evaluation data for comprehensive testing. Scenarios are developed to mimic real-world usage for thorough evaluation of prompt candidates.</li><li><strong>Prompt Testing and Ranking: </strong>Methods like Monte Carlo matchmaking and ELO rating systems are employed to test and rank prompts. Advanced ranking mechanisms provide nuanced assessments for prompt effectiveness.</li><li><strong>User Interface Development: </strong>A user-friendly interface is crucial for seamless interaction with the system. An intuitive UI is designed and implemented for easy data input, prompt retrieval, and evaluation viewing.</li><li><strong>System Integration and Testing: </strong>Integration of all components is followed by thorough testing to ensure functionality and performance. Continuous refinement ensures a robust system ready for deployment</li></ul><h4><strong>Project Implementation</strong></h4><p><strong>Part 1: Model Exploration</strong></p><p>The firs part was understanding the capabilities of OpenAI model.</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;What is Prompt engineering?&quot;)<br>]<br>response = chat(messages)<br><br>print(response.content)</pre><p>The response:</p><pre>Prompt engineering is an approach to design and develop prompts or cues that <br>guide users in taking desired actions or behaviors. In the context of <br>human-computer interaction, prompt engineering involves creating clear, <br>concise, and effective prompts to help users understand what actions they need <br>to take next. These prompts can be in the form of messages, notifications,<br> alerts, or visual cues that provide users with relevant information or <br>instructions to complete a task or achieve a goal. Prompt engineering is <br>essential in user interface design to enhance usability and user experience.</pre><p><strong>Part 2: Rag Implementation</strong></p><p>The RAG system was built with Pinecone for storing vectors, enabling fast retrieval of relevant information. Data was embedded using OpenAI’s powerful embedding models, ensuring that retrieved information is contextually accurate and relevant.</p><pre>index_name = &quot;prompt-engineering&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>#Intialise the index<br>index = pinecone.Index(index_name)<br>index.describe_index_stats()<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><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>After loading our data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-m_iMd4vl2Bbl0V3YxWCg.png" /></figure><p><strong>Part 3: Automatic Prompt Generation</strong></p><p>Using this general python function, we can retrieve relevant context from our vector data.</p><pre>def retrieve(results, prompt_path, query= None, num_prompts=None):<br>    &quot;&quot;&quot;<br>    Retrieve the best prompts based on the context of the results.<br>    <br>    Args:<br>        results: The search results from the vector store.<br>        prompt_path (str): The path for the prompts.<br>        query (str): The query to generate prompts for.<br>        num_prompts (int): The number of prompts to generate.<br>    <br>    Returns:<br>        str: The augmented prompt.<br>    &quot;&quot;&quot;<br>    context = &quot;\n&quot;.join([x.page_content for x in results])<br><br>    <br>    prompt_text = FileHandler.read_file(prompt_path)<br><br>    if num_prompts and query:<br>        augmented_prompt = prompt_text.replace(&quot;{context}&quot;, context).replace(&quot;{num_prompt_output}&quot;, str(num_prompts)).replace(&quot;{query}&quot;, query) <br>    <br>    elif num_prompts and query==None:<br>       augmented_prompt = prompt_text.replace(&quot;{context}&quot;, context).replace(&quot;{num_prompt_output}&quot;, str(num_prompts))<br>    <br>    elif query and num_prompts==None:<br>       augmented_prompt = prompt_text.replace(&quot;{context}&quot;, context).replace(&quot;{num_prompt_output}&quot;, str(num_prompts)).replace(&quot;{query}&quot;, query) <br>    <br>    else:<br>        augmented_prompt = prompt_text.replace(&quot;{context}&quot;, context).replace(&quot;{query}&quot;, query) <br>        <br>    return augmented_prompt</pre><p>This function, retrieve, enhances a generic prompt by incorporating retrieved data. It merges content from the retrieved data and strategically replaces placeholders in the base prompt with this information. The result? A more contextual prompt tailored to the specific data, making it more likely to generate relevant outputs.</p><p><strong>Automatic Prompt generation</strong></p><p>The main script will then call the retrieve to get the relevant prompt. After getting the relevant prompt, we will just call our model function to get the possible prompts for the user case’s.</p><pre>def generation_prompt(text, query, prompt_path, n=5):<br><br>    insert_vector(text)<br><br>    # Initialize the vector store<br>    text_field = &#39;text&#39;<br>    vectorstore = Pinecone(index, embed_model.embed_query, text_field)<br><br>    # Define the query<br>    #query = &#39;Who are the tutors?&#39;<br><br>    # Perform similarity search<br>    results = vectorstore.similarity_search(query, k=2)<br><br>    # Retrieve the prompt<br>    prompt = retrieve(results, prompt_path, query, n)<br><br>    # Get completion from OpenAI<br>    response = assistant.get_chat_completion(messages=[HumanMessage(content=prompt)], logprobs=True, top_logprobs=1)<br><br>    return response</pre><p><strong>Part 4: Validation Dataset Generation</strong></p><p>We will then generate the validation dataset. This will be used to rank our prompts from the above.</p><pre>def generate_test_data(prompt, context, num_test_output):<br>    <br>    response = assistant.get_chat_completion(<br>        messages=[<br>            HumanMessage(content= prompt.replace(&quot;{context}&quot;, context).replace(&quot;{num_test_output}&quot;, str(num_test_output)))<br>            ],<br>        logprobs=True,<br>        top_logprobs=1<br>    )<br><br>    return response<br><br><br><br>def main(num_test_output):<br>    context_message = FileHandler.read_file(&quot;prompts/10 Academy Cohort B - Weekly Challenge_ Week - 7.pdf&quot;)<br>    prompt_message = FileHandler.read_file(&quot;prompts/data-generation-prompt.txt&quot;)<br><br>    context = str(context_message)<br>    prompt = str(prompt_message)<br><br>    response = generate_test_data(<br>                                    prompt=prompt,<br>                                    context=context,<br>                                    num_test_output=num_test_output<br>                                )<br>    <br>    test_data = response.content<br>    json_object = json.loads(test_data)<br>    with open(&#39;test_dataset/test-data.json&#39;, &#39;w&#39;) as f:<br>        json.dump(json_object, f, indent=4)<br>    <br>    print(f&quot;JSON data has been saved.&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main(10)</pre><p>The function above creates ten question-answer pairs, forming a ground truth dataset for validation. Once this validation dataset is generated, we proceed to evaluate it. We iterate through the saved JSON file, extracting questions and asking the model for its confidence level in answering based on the retrieved information. Pairs with a confidence level above 95% are retained, while others are removed.</p><pre>def get_model_confidence(message):<br><br>    #response = client.invoke(message, max_tokens=1, logprobs=True, top_logprobs=1)<br><br>    response = assistant.get_chat_completion(message, max_tokens=1, logprobs=True, top_logprobs=1)<br>    <br>    system_msg = str(response.content)<br><br>    for i, logprob in enumerate(response.response_metadata[&#39;logprobs&#39;][&#39;content&#39;][0][&#39;top_logprobs&#39;], start=1):<br>        output = f&#39;\nhas_sufficient_context_for_answer: {system_msg}, \nlogprobs: {logprob[&quot;logprob&quot;]}, \naccuracy: {np.round(np.exp(logprob[&quot;logprob&quot;])*100,2)}%\n&#39;<br>        if system_msg == &#39;true&#39; and np.round(np.exp(logprob[&quot;logprob&quot;])*100,2) &gt;= 95.00:<br>            classification = &#39;true&#39;<br>        elif system_msg == &#39;false&#39; and np.round(np.exp(logprob[&quot;logprob&quot;])*100,2) &gt;= 95.00:<br>            classification = &#39;false&#39;<br>        else:<br>            classification = &#39;false&#39;<br>    return classification<br><br>def evaluation():<br>    prompt_path = &#39;prompts/validation.txt&#39;<br><br>    with open(&#39;test_dataset/test-data.json&#39;, &#39;r&#39;) as f:<br>        data = json.load(f)<br><br>    filtered_data = []<br>    for item in data:<br>        query = item[&#39;user&#39;]<br><br><br>        text_field = &#39;text&#39;<br>        vectorstore = Pinecone(index, embed_model.embed_query, text_field)<br>        results = vectorstore.similarity_search(query, k=2)<br><br>        prompt = retrieve(results, prompt_path, query)<br><br>        classification = get_model_confidence(prompt)<br>        <br>        if classification == &#39;true&#39;:<br>            filtered_data.append(item)<br>    <br>    with open(&#39;test_dataset/test-data.json&#39;, &#39;w&#39;) as file:<br>        json.dump(filtered_data, file, indent=4)</pre><p>The new json file:</p><pre>[<br>    {<br>        &quot;user&quot;: &quot;What is the primary goal of PromptlyTech?&quot;,<br>        &quot;assistant&quot;: &quot;To revolutionize how businesses interact with LLMs.&quot;<br>    },<br>    {<br>        &quot;user&quot;: &quot;What are the key services offered by PromptlyTech?&quot;,<br>        &quot;assistant&quot;: &quot;Automatic Prompt Generation, Automatic Evaluation Data Generation, and Prompt Testing and Ranking.&quot;<br>    },<br>    {<br>        &quot;user&quot;: &quot;What is the significance of prompt engineering in the context of LLMs?&quot;,<br>        &quot;assistant&quot;: &quot;It guides LLMs to produce desired outcomes efficiently.&quot;<br>    },<br>    {<br>        &quot;user&quot;: &quot;What are the learning outcomes related to prompt engineering?&quot;,<br>        &quot;assistant&quot;: &quot;Skills development, critical analysis, technical aptitude, problem-solving, and data interpretation.&quot;<br>    },<br>    {<br>        &quot;user&quot;: &quot;What are the primary methods used for prompt testing and ranking?&quot;,<br>        &quot;assistant&quot;: &quot;Monte Carlo Matchmaking and ELO Rating System.&quot;<br>    },<br>    {<br>        &quot;user&quot;: &quot;What is the purpose of the User Interface Development task?&quot;,<br>        &quot;assistant&quot;: &quot;To create a user-friendly interface for interacting with the prompt engineering system.&quot;<br>    }<br>]</pre><p><strong>Part 5: Prompt Ranking</strong></p><p>First to rank our model, we get a response from our model for each prompts we generate.</p><pre>def generate_response(prompt, embed_model, index, prompt_path):<br><br>    text_field = &#39;text&#39;<br>    vectorstore = Pinecone(index, embed_model.embed_query, text_field)<br><br>    # Perform similarity search<br>    results = vectorstore.similarity_search(prompt, k=2)<br><br>    # Retrieve the prompt<br>    aug_prompt = retrieve(results,  prompt_path, prompt)<br><br>    #prompts = prompts.path(results, )<br><br>    # Generate a response using the model<br>    response = assistant.get_chat_completion(messages=[HumanMessage(content=aug_prompt)], logprobs=True, top_logprobs=1).content<br><br>    return response</pre><p>Prompt ranking works by generating responses for a set of prompts and then evaluating each response based on its relevance and effectiveness. The process involves:</p><ol><li><strong>Generating Responses</strong>: For each prompt, a response is generated using the RAG system.</li><li><strong>Evaluation</strong>: Each generated response is evaluated against expected responses from a validation dataset.</li><li><strong>Scoring</strong>: Responses are scored based on factors like relevance, clarity, and completeness.</li><li><strong>Ranking</strong>: Prompts are ranked based on their average score across all evaluations.</li></ol><p>Additionally, comparisons between prompts are made to adjust their ratings, ensuring a fair and accurate ranking.</p><pre>def evaluate_response(prompt, generated_response, expected_responses):<br>    # Embed the generated response<br>    generated_vector = embed_model.embed_query(generated_response)<br><br>    # Embed all expected responses and calculate their similarities<br>    scores = []<br>    for expected_response in expected_responses:<br>        expected_vector = embed_model.embed_query(expected_response)<br>        relevance = cosine_similarity([generated_vector], [expected_vector])[0][0]<br>        clarity = len(generated_response.split()) / 100<br>        completeness = len(set(prompt.split()) &amp; set(generated_response.split())) / len(set(prompt.split()))<br>        score = relevance + clarity + completeness<br>        scores.append(score)<br><br>    # Return the average score<br>    return sum(scores) / len(scores)<br><br><br>def expected_score(rating1, rating2):<br>    return 1 / (1 + 10 ** ((rating2 - rating1) / 400))<br><br><br>def update_ratings(rating1, rating2, result, k=32):<br>    expected1 = expected_score(rating1, rating2)<br>    expected2 = expected_score(rating2, rating1)<br><br>    if result == 1:  # prompt1 wins<br>        rating1 += k * (1 - expected1)<br>        rating2 += k * (0 - expected2)<br>    else:  # prompt2 wins<br>        rating1 += k * (0 - expected1)<br>        rating2 += k * (1 - expected2)<br><br>    return rating1, rating2<br><br><br><br>def ranking_prompts(prompts, prompt_path)<br>    validation_dataset = load_validation_dataset(&#39;test_dataset/test-data.json&#39;)<br>    responses = {prompt: generate_response(prompt, embed_model, index, prompt_path) for prompt in prompts}<br>    scores = {}<br><br>    for prompt in prompts:<br>        total_score = 0<br>        for data in validation_dataset:<br>            expected_responses = [data[&#39;assistant&#39;]]<br>            generated_response = responses[prompt]<br>            score = evaluate_response(prompt, generated_response, expected_responses)#, embed_model)<br>            total_score += score<br>        scores[prompt] = total_score / len(validation_dataset)<br><br>    ratings = {prompt: 1000 for prompt in prompts}<br>    comparisons = [(prompts[i], prompts[j]) for i in range(len(prompts)) for j in range(i+1, len(prompts))]<br><br>    for prompt1, prompt2 in comparisons:<br>        rating1 = ratings[prompt1]<br>        rating2 = ratings[prompt2]<br>        score1 = scores[prompt1]<br>        score2 = scores[prompt2]<br><br>        result = 1 if score1 &gt; score2 else 0<br>        new_rating1, new_rating2 = update_ratings(rating1, rating2, result)<br>        ratings[prompt1] = new_rating1<br>        ratings[prompt2] = new_rating2<br><br>    ranked_prompts = sorted(ratings.items(), key=lambda x: x[1], reverse=True)<br><br>    return ranked_prompts</pre><p><strong>Part 6: User Interface</strong></p><p>Simple user interface was developed using streamlit where a user write the question and upload the documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jW4xdmOYGGU8omywKxwnpQ.png" /></figure><p>The above are the generated validation dataset and if a user wants the file can be downloaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHfjJyzrrAS69ImNLgPaIA.png" /></figure><p>This is the ranked prompt.</p><h4><strong>Limitations and Future Improvements</strong></h4><p><strong>Limitations:</strong></p><p>While the system offers valuable functionality, it currently faces a couple of limitations:</p><ol><li><strong>Response Delay:</strong> Users may experience delays of 30–45 seconds when querying the system, which is less than ideal for real-time interactions.</li><li><strong>Documentation Quality:</strong> The existing documentation within the GitHub repository could be improved for better clarity and usability.</li></ol><p><strong>Future Improvements:</strong></p><p>To enhance user experience and system performance, several improvements are planned for future iterations:</p><ol><li><strong>Reduced Response Time:</strong> Implementing optimizations to minimize response delays, ensuring users receive outputs more quickly.</li><li><strong>Enhanced Documentation:</strong> Updating the documentation with clearer explanations, organized classes, and modules to facilitate easier understanding and usage for developers and users alike.</li><li><strong>Real-time User Feedback Mechanism:</strong> 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><li><strong>Dynamic RAG Systems:</strong> Investigate methods to make RAG systems more dynamic by adapting to evolving datasets and knowledge sources. This could involve real-time updates of external knowledge retrieval components to ensure the system’s relevance over time.</li></ol><h4>Conclusion</h4><p>In the quest to build advanced Retrieval Augmented Generation (RAG) systems, PromptlyTech has demonstrated innovative methodologies that streamline prompt engineering and enhance the capabilities of Language Models (LLMs) for enterprise-grade applications. By leveraging RAG techniques, PromptlyTech aims to revolutionize how businesses interact with AI-driven solutions, making them more accessible, efficient, and reliable.</p><p>Through the Automatic Prompt Generation, Evaluation Data Generation, and Prompt Testing and Ranking services, PromptlyTech addresses the challenges associated with prompt engineering, thereby enabling users to harness the full potential of LLMs. The integration of retrieval-based methods and generative models in RAG systems offers precise and reliable information retrieval, essential for applications where accuracy is paramount.</p><p>The implementation journey outlined in this project showcases the meticulous steps involved in building a sophisticated RAG system, from model exploration and implementation to validation and ranking of prompts. By automating prompt generation, testing, and ranking, PromptlyTech ensures that users can efficiently utilize LLMs for various tasks, ranging from question answering to summarization and beyond.</p><p>However, like any innovative endeavor, there are limitations and areas for future improvements. Despite occasional response delays and documentation quality concerns, PromptlyTech plans to enhance its system by reducing response times, improving documentation, and implementing real-time user feedback mechanisms. These enhancements aim to further refine the user experience and system performance, ensuring PromptlyTech remains at the forefront of AI-driven solutions.</p><p>In conclusion, Precision RAG represents a significant leap forward in the evolution of prompt engineering, offering businesses a powerful tool to leverage the capabilities of Language Models effectively. With continuous refinement and innovation, PromptlyTech is poised to shape the future of AI-driven text generation, facilitating smarter, more reliable interactions between humans and machines in the digital age.</p><p>If you enjoyed reading this post, please drop a 👏</p><p>Project Link: <a href="https://github.com/Yohanes213/Precision-RAG">Precision-Rag</a></p><p>Follow me on GitHub: <a href="https://github.com/Yohanes213">Yohanes213</a></p><p>Follow me on Medium: <a href="https://medium.com/@Yohanes213">Yohanes Teshome Kebede</a></p><p>Let’s connect on LinkedIn: <a href="https://www.linkedin.com/in/yohanes-teshome/">Yohanes Teshome Kebede</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=964ba34b33e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>