<?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 Muhammad Ali on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Ali on Medium]]></description>
        <link>https://medium.com/@ali202.muhammad?source=rss-34670fa62922------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1ZEy3yFGU4j4VeGNW83rEg.jpeg</url>
            <title>Stories by Muhammad Ali on Medium</title>
            <link>https://medium.com/@ali202.muhammad?source=rss-34670fa62922------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:57:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ali202.muhammad/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[The Future of Data Pipelines: How Modern Tech is Changing ETL as We Know It]]></title>
            <link>https://medium.com/@ali202.muhammad/the-future-of-data-pipelines-how-ai-is-changing-etl-as-we-know-it-8dd379ae0817?source=rss-34670fa62922------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dd379ae0817</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[extract-transform-load]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <dc:creator><![CDATA[Muhammad Ali]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 09:43:29 GMT</pubDate>
            <atom:updated>2025-06-23T09:45:15.123Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMwien1BYc642KSVYYuRCQ.png" /></figure><p>For a long time, <strong>ETL (Extract → Transform → Load)</strong> has been the standard way to move data from one place to another. It worked well when we had simpler systems and smaller datasets. But today, with the rise of <strong>cloud computing</strong>, <strong>real-time analytics</strong>, and <strong>AI</strong>, we need faster, more flexible ways to handle data.</p><p>Now, new methods like <strong>ELT</strong>, <strong>streaming</strong>, <strong>reverse ETL</strong>, and <strong>data mesh</strong> are becoming more popular. These approaches help teams work with large volumes of data, build scalable systems, and deliver faster insights.</p><h3>1. ETL vs ELT: What’s the Difference?</h3><p>Traditional ETL moves data in this order:</p><blockquote>Extract it from the source (like a database)</blockquote><blockquote>Clean or change it (transform)</blockquote><blockquote>Load it into a target system (like a data warehouse)</blockquote><p>But ETL has a problem: it often requires a lot of setup and doesn’t scale well to big data.</p><p><strong>ELT</strong> flips the last two steps:</p><blockquote>Extract the data</blockquote><blockquote>Load it directly into a warehouse or data lake</blockquote><blockquote>Transform it <em>after</em> it’s loaded, using tools like <strong>SQL</strong>, <strong>dbt</strong>, or <strong>Spark</strong></blockquote><p><strong>ELT Architecture Diagram:</strong></p><pre>[Source Systems] → [Raw Data Lake/Warehouse] → [Transform with SQL/Notebooks/DBT] → [Analytics Layer]</pre><p>This makes it faster, cheaper, and better suited to cloud platforms like <strong>Snowflake</strong>, <strong>BigQuery</strong>, and <strong>Databricks</strong>.</p><h3>2. Real-Time Pipelines: Streaming ETL</h3><p>In today’s fast-moving world, businesses want insights instantly, not hours later. That’s where <strong>streaming ETL</strong> comes in. Instead of moving data in batches, it processes data as it arrives.</p><p><strong>Popular tools:</strong></p><p>· <strong>Apache Kafka</strong> (event streaming platform)</p><p>· <strong>Apache Flink</strong> or <strong>Spark Streaming</strong> (stream processing engines)</p><p><strong>Streaming Pipeline Example:</strong></p><pre>[Event Stream: Kafka] → [Streaming Transform: Flink/Spark] → [Dashboard or Alert System]</pre><p>This setup is great for fraud detection, monitoring systems, or real-time analytics dashboards.</p><h3>3. Reverse ETL: Putting Data Back Into Apps</h3><p>ETL and ELT usually move data into a warehouse. But what if you want that data to power your day-to-day tools like <strong>Salesforce</strong>, <strong>Zendesk</strong>, or <strong>HubSpot</strong>?</p><p>That’s where <strong>Reverse ETL</strong> helps. It takes data from your warehouse and sends it back into the tools your teams use, so they can take action.</p><p><strong>Example use case:</strong></p><p>· You calculate customer churn risk in your data warehouse.</p><p>· Then, using reverse ETL, you push that score into Salesforce.</p><p>· Your sales team sees it and follows up with at-risk customers.</p><h3>4. Metadata, Lineage, and Data Contracts</h3><p>Data pipelines can get messy quickly if you don’t keep track of what’s happening. Modern tools let you track:</p><p>· <strong>Metadata</strong> (information about your data)</p><p>· <strong>Data lineage</strong> (where data came from and where it’s going)</p><p>· <strong>Data contracts</strong> (rules for how data should look and behave)</p><p><strong>Sample dbt YAML with metadata:</strong></p><pre>version: 2<br>models:<br>  - name: customer_churn<br>    description: &quot;Calculates churn probability for each customer&quot;<br>    columns:<br>      - name: customer_id<br>        description: &quot;Primary key for customer&quot;<br>      - name: churn_score<br>        description: &quot;Score from 0 to 1&quot;<br>        tests:<br>          - not_null<br>          - accepted_values: [0.0, 1.0]</pre><p>This helps teams collaborate better and avoid surprises when data changes.</p><h3>5. AI-Ready Data: Governed and Trustworthy</h3><p>If you want to use AI or machine learning, your data needs to be: Clean, Consistent and Well-documented</p><p>Manual ETL pipelines often don’t provide that. But modern tools that include <strong>data governance</strong>, <strong>active metadata</strong>, and <strong>lineage tracking</strong> do.</p><p><strong>Governed Pipeline Example:</strong></p><pre>Raw Data → Staging → Verified Layer (with lineage) → Feature Store → AI Models</pre><h3>6. Picking the Right Approach: ETL, ELT, or Both?</h3><p>Each method has its strengths:</p><p><strong>ETL</strong> is good when you need strict data control before loading.</p><p><strong>ELT</strong> is better for big data and cloud platforms.</p><p><strong>Streaming ETL</strong> is best for real-time use cases.</p><p><strong>Reverse ETL</strong> helps make data useful to business teams.</p><p>In most cases, a hybrid approach works best.</p><h3>7. Best Practices for Today’s Data Pipelines</h3><p>1. <strong>Break things into small steps</strong> (modular pipeline design)</p><p>2. <strong>Use automation</strong> to check data quality</p><p>3. <strong>Track where data comes from and where it goes</strong> (lineage)</p><p>4. <strong>Let teams own their own data products</strong></p><p>5. <strong>Use streaming and reverse ETL where needed</strong></p><h3>8. What’s Next?</h3><p>The future of data pipelines is all about:</p><p><strong>Data products</strong>: reusable, well-defined datasets</p><p><strong>Active metadata</strong>: automatically tracked, always up-to-date</p><p><strong>AI-ready pipelines</strong>: trust, traceability, and transparency</p><p><strong>Data mesh</strong>: letting each team manage its own data domain</p><h3>Final Word</h3><p>ETL isn’t going away, but it’s changing. Whether you use ELT, streaming, or reverse ETL, the key is building smarter, faster, and more reliable pipelines. Start thinking about your data as a product and use the tools that help you move quickly without losing control.</p><h3>References</h3><p><a href="https://blog.det.life/the-end-of-etl-the-radical-shift-in-data-processing-thats-coming-next-88af7106f7a1">https://blog.det.life/the-end-of-etl-the-radical-shift-in-data-processing-thats-coming-next-88af7106f7a1</a></p><p><a href="https://www.fivetran.com/blog/reverse-etl">https://www.fivetran.com/blog/reverse-etl</a></p><p><a href="https://docs.getdbt.com/">https://docs.getdbt.com/</a></p><p><a href="https://learn.microsoft.com/en-us/azure/architecture/data-guide/relational-data/etl">https://learn.microsoft.com/en-us/azure/architecture/data-guide/relational-data/etl</a></p><p><a href="https://www.confluent.io/blog/kafka-fastest-stream-data-pipeline/">https://www.confluent.io/blog/kafka-fastest-stream-data-pipeline/</a></p><p><a href="https://towardsdatascience.com/etl-vs-elt-decoding-the-data-pipeline-buzzwords-f7d8e5c7fe91">https://towardsdatascience.com/etl-vs-elt-decoding-the-data-pipeline-buzzwords-f7d8e5c7fe91</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dd379ae0817" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cache-Augmented vs. Retrieval-Augmented Generation]]></title>
            <link>https://medium.com/@ali202.muhammad/cache-augmented-vs-retrieval-augmented-generation-31403410336a?source=rss-34670fa62922------2</link>
            <guid isPermaLink="false">https://medium.com/p/31403410336a</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[knowledge-base]]></category>
            <category><![CDATA[cache-augmented-gen]]></category>
            <dc:creator><![CDATA[Muhammad Ali]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 11:46:09 GMT</pubDate>
            <atom:updated>2025-06-02T11:49:50.192Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cache-Augmented vs. Retrieval-Augmented Generation: Why CAG Reigns Supreme for Knowledge-Intensive Tasks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQ5DeKeodZ60O28gt0Lnzw.png" /></figure><p>When building AI systems that deliver accurate, timely, and contextually relevant knowledge responses, two dominant techniques have recently emerged: Retrieval-Augmented Generation (RAG) and Cache-Augmented Generation (CAG). While RAG has enjoyed widespread popularity, CAG is increasingly gaining attention as an optimal solution for many real-world knowledge tasks. In this article, we’ll delve into the key differences between these two methods and explain why CAG often proves superior, particularly in scenarios with stable knowledge bases.</p><h3>Understanding the Fundamentals</h3><h3>Retrieval-Augmented Generation (RAG)</h3><p>Retrieval-Augmented Generation combines traditional language model techniques with real-time external data retrieval. When the model receives a query, it first searches and retrieves relevant documents or information from external databases. It then leverages this data to generate a response. This approach has been highly effective in applications involving extensive, dynamic information such as web-based question-answering systems or knowledge bases that frequently change.</p><h3>Cache-Augmented Generation (CAG)</h3><p>In contrast, Cache-Augmented Generation involves preloading a curated set of information directly into the language model’s context or cache. Instead of retrieving information on-the-fly, CAG accesses data instantly, significantly reducing latency and improving response consistency. This approach is particularly advantageous when dealing with stable, relatively unchanging knowledge bases, such as internal documentation, product manuals, or static datasets.</p><h3>Key Differences and Practical Considerations</h3><h3>Latency</h3><ul><li><strong>RAG:</strong> Has inherent latency due to real-time document retrieval, potentially causing noticeable delays.</li><li><strong>CAG:</strong> Eliminates the retrieval step entirely, enabling instant responses and significantly enhancing user experience.</li></ul><h3>Complexity</h3><ul><li><strong>RAG:</strong> Requires managing and maintaining a retrieval system, indexing, and real-time search, increasing complexity.</li><li><strong>CAG:</strong> Simpler to implement and maintain, as it does not rely on external retrieval, making it easier and cheaper to operate.</li></ul><h3>Accuracy and Reliability</h3><ul><li><strong>RAG:</strong> Accuracy can vary based on the retrieval accuracy, and the system might occasionally retrieve irrelevant or outdated documents, leading to incorrect responses.</li><li><strong>CAG:</strong> Typically more reliable, as the dataset is pre-vetted and carefully curated, drastically reducing the risk of incorrect or irrelevant information.</li></ul><h3>When is CAG Clearly Superior?</h3><h3>Stable Knowledge Bases</h3><p>CAG shines brightest when the knowledge base is stable or changes infrequently. Examples include internal knowledge management systems, corporate FAQs, and educational resources. The cache-based system ensures swift, accurate, and consistently reliable responses without the overhead of repeated real-time queries.</p><h3>Real-time and High-Performance Applications</h3><p>In scenarios demanding immediate responses, such as customer support chatbots or virtual assistants for internal teams, latency can be a critical factor. CAG’s instant access provides a seamless experience, essential for maintaining high user satisfaction.</p><h3>Lower Operational Complexity</h3><p>Companies with limited resources, such as smaller businesses or specialized domains, benefit greatly from the simplicity and lower maintenance of CAG. Without the necessity of sophisticated retrieval mechanisms, teams can focus on content quality and model optimization rather than operational overhead.</p><h3>Where RAG Falls Short</h3><p>Despite its popularity, RAG has notable challenges:</p><ul><li><strong>Retrieval Errors:</strong> Misalignment in retrieved content can result in inaccuracies and reduced user trust.</li><li><strong>Operational Overhead:</strong> Complex retrieval infrastructure requires ongoing maintenance and tuning.</li><li><strong>Latency Issues:</strong> Users expect rapid interactions, and retrieval steps inherently slow down response generation, often impacting user experience negatively.</li></ul><h3>Cache-Augmented Generation: The Practical Choice</h3><p>Recent research, including the influential paper “Don’t Do RAG: When Cache-Augmented Generation is All You Need for Knowledge Tasks,” clearly demonstrates scenarios where CAG matches or surpasses RAG’s capabilities without the added complexity. By preloading highly relevant information into the model’s cache, CAG ensures faster, more consistent, and reliable responses, making it an ideal choice for knowledge-centric tasks.</p><h3>Conclusion</h3><p>While RAG continues to have its place in highly dynamic and expansive information environments, Cache-Augmented Generation is increasingly becoming the superior approach for many practical applications. Its advantages in simplicity, speed, reliability, and lower operational complexity make it the method of choice for organizations seeking effective, scalable knowledge-based AI systems.</p><p>In the rapidly evolving world of AI, understanding and choosing the right technique for your needs can dramatically enhance your application’s success and increasingly, CAG is proving itself as the preferred solution.</p><p><strong>REFERENCES:</strong></p><p><a href="https://arxiv.org/html/2412.15605v1">Don&#39;t Do RAG: When Cache-Augmented Generation is All You Need for Knowledge Tasks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31403410336a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PyTorch Basics — A Beginners Guide to ML]]></title>
            <link>https://medium.com/@ali202.muhammad/pytorch-basics-a-beginners-guide-to-ml-5fdcf3d98a01?source=rss-34670fa62922------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fdcf3d98a01</guid>
            <category><![CDATA[tabular-data]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Muhammad Ali]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 20:27:39 GMT</pubDate>
            <atom:updated>2025-04-08T20:27:39.548Z</atom:updated>
            <content:encoded><![CDATA[<h3>PyTorch Basics — A Beginners Guide to ML</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXcCl119Dkz-GsOh2a-aMQ.png" /></figure><p>In This project I will show you how to implement a basic Text Classification project in order for you to familiarize yourself with the syntax and begin your journey into on of the most powerful and in demand python framework.</p><p>Here I will use this Kaggle Dataset: <a href="https://www.google.com/url?q=https%3A%2F%2Fwww.kaggle.com%2Fdatasets%2Fmssmartypants%2Frice-type-classification">https://www.kaggle.com/datasets/mssmartypants/rice-type-classification</a></p><p>This is a basic binary classification dataset for Rice, i would suggest you to go through the Datacard in the URL in order to understand the data we have.</p><p>Just for simplicity our rice will either be Jasmine — 1, Gonen — 0.</p><p>First step we will use the opendatasets library in order to download the data set. I will be doing everything in a Google colab notebook for ease.</p><p>ALSO MAKE SURE YOU SELECT THE T4 GPU SESSION by going to runtime &gt; change runtime type</p><h3>1. Initializations and Dataset Download</h3><pre>!pip install opendatasets </pre><p>Now i will download our dataset using this library, you will need to provide your username and API key from Kaggle when it asks for it</p><pre>import opendatasets as od<br>od.download(&quot;https://www.kaggle.com/datasets/mssmartypants/rice-type-classification&quot;)</pre><h3>2. Imports</h3><p>Now i will make all the necessary imports, also in pytorch you need to specify if you are using a GPU as a device or a CPU, so we will also do that</p><pre>import torch # Torch main framework<br>import torch.nn as nn # Used for getting the NN Layers<br>from torch.optim import Adam # Adam Optimizer<br>from torch.utils.data import Dataset, DataLoader # Dataset class and DataLoader for creatning the objects<br>from torchsummary import summary # Visualize the model layers and number of parameters<br>from sklearn.model_selection import train_test_split # Split the dataset (train, validation, test)<br>from sklearn.metrics import accuracy_score # Calculate the testing Accuracy<br>import matplotlib.pyplot as plt # Plotting the training progress at the end<br>import pandas as pd # Data reading and preprocessing<br>import numpy as np # Mathematical operations<br><br>#SPECIFY THE DEVICE A CUDA (GPU) if available else CPU<br>device = &#39;cuda&#39; if torch.cuda.is_available() else &#39;cpu&#39;<br>print(device) #SEE IF THE DEVICE IS CORRECT</pre><h3>3. Dataset</h3><p>Now let us start by referencing our Dataset to a variable and taking a look</p><pre>data_df = pd.read_csv(&quot;/content/rice-type-classification/riceClassification.csv&quot;)<br>data_df.head()</pre><h3>4. Data Preprocessing</h3><p>The Data looks good, we will do some basic pre processing nothing complex as our main goal is to familiarize us with the pytorch syntax mostly</p><p>Firstly I will do two simple things:</p><ol><li>Remove any Missing Values</li><li>Remove the ID column as it is not needed</li></ol><pre>data_df.dropna(inplace = True)<br>data_df.drop([&#39;id&#39;], axis = 1, inplace = True)<br>print(data_df.shape)</pre><p>Now as the next step of pre processing we will do some necessary normalization of our data.</p><p>We normalize the data by dividing each value in a column by the maximum value in that column, so that all values fall between 0 and 1. This specific method is called Max Normalization, which is a simpler form of Min-Max scaling. It helps the model train faster and more effectively, as neural networks perform better when input features are on a similar scale. Without scaling, large numbers can lead to unstable training, exploding gradients, or very slow learning. Although this scaling changes the actual values, it preserves the original relationships and patterns in the data. If needed, we can later reverse this process to convert the model’s outputs back to their original scale for interpretation.</p><pre>original_df = data_df.copy() # IN ORDER TO PRESERVE THE ORIGINAL DATASET SOMEWHERE FOR LATER USE<br><br>for column in data_df.columns:<br>  data_df[column] = data_df[column]/data_df[column].abs().max()<br><br>data_df.head()</pre><p>Now as you can see the maximum feature value in any column is 1 and minimum is 0</p><h3>5. Data Splitting</h3><p>Now let us split out dataset into training, validation and testing but before that we create two NumPy Arrays X and Y, X will be the input data where we will have all rows (Denoted by : sign) and all columns except the last (Denoted by :-1) as the last column has our actual data classifier i.e. either Jasmine — 1, Gonen — 0.</p><p>Y will be the corresponding outputdata of X i.e. all rows again but of only the last column (-1) which has the actual class in it (either Jasmine — 1, Gonen — 0.)</p><p>We will use the iloc function which allows to select a specific portion of the data</p><pre>X = np.array(data_df.iloc[:, :-1]) #ALL ROWNS AND ALL COLUMNS, EXCEPT THE LAST COLUMN<br>Y = np.array(data_df.iloc[:, -1]) #ALL ROWS AND ONLY THE LAST COLUMN</pre><p>Now that is done, To train and evaluate the model properly, we split the dataset into three parts: training, validation, and test sets. The training set is used to teach the model patterns in the data. The validation set helps monitor the model’s performance during training and fine-tune it to avoid overfitting. Finally, the test set evaluates the model’s performance on unseen data to check how well it generalizes. In the code, we first split the data into 70% training and 30% temporary testing data. Then, we further split this temporary data equally to create final validation and test sets, ensuring a balanced and fair evaluation process.</p><pre># First split: training data and remaining (30%) data<br>X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3)<br><br># Second split: split the 30% data equally into test and validation<br>X_test, X_val, y_test, y_val = train_test_split(X_test, y_test, test_size=0.5)</pre><p>So Basically what we did,</p><p><strong>Original Dataset</strong> 100% Data</p><p><strong>Step 1: Initial Split</strong></p><p>70% Training Data</p><p>30% Temp Data (to be split)</p><p><strong>Step 2: Split Temp Data</strong></p><p>70% Training</p><p>15% Validation</p><p>15% Test</p><p><strong>Purpose:</strong></p><p>Training: Teach the model</p><p>Validation: Tune and monitor during training</p><p>Test: Final evaluation after training</p><h3>6. Dataset Object</h3><p>Now, let’s create our custom dataset object. While this step isn’t too complex, it can feel a bit tricky at first. The goal here is to convert our dataset into a PyTorch Dataset object. Although you could work with the data as it is, using the Dataset class is a much more professional and efficient approach, especially during training.</p><p>Here’s the simple idea: PyTorch provides a base Dataset class that comes with built-in functionality. What we’re going to do is inherit from this class and customize it for our needs. Think of the original Dataset class as a template with many functions inside it. We will recreate this class and modify some of its functions to work specifically with our data.</p><p>In the code below, we start by defining the constructor function, <strong>init</strong>. We pass X and Y (our inputs and outputs) as parameters, then inside the function, we convert them into tensors and set their data type to float32. We also move our data to the CUDA device to enable GPU acceleration.</p><p>Next, we customize two important functions:</p><p><strong>len</strong>: This function returns the total number of samples in our dataset.</p><p><strong>getitem</strong>: This function allows us to access individual samples (rows) of data by their index.</p><p>By doing this, we make our dataset fully compatible with PyTorch’s data loading utilities, like DataLoader, which will help us efficiently feed data into the model during training.</p><pre>class dataset(Dataset):<br>    def __init__(self, X, Y):<br>        self.X = torch.tensor(X, dtype = torch.float32).to(device)<br>        self.Y = torch.tensor(Y, dtype = torch.float32).to(device)<br><br>    def __len__(self):<br>        return len(self.X)<br>    def __getitem__(self, index):<br>        return self.X[index], self.Y[index]<br><br>training_data = dataset(X_train, y_train)<br>validation_data = dataset(X_val, y_val)<br>testing_data = dataset(X_test, y_test)</pre><h3>7. Training Hyper Parameters</h3><p>Now, we’ll define the hyperparameters for training our model. These are the key settings that control how our model learns from the data. We start by setting the batch size, which determines how many samples the model processes at once before updating its weights. Next, we define the number of epochs, which is how many times the model will go through the entire training dataset. We also set the number of hidden neurons, which controls the capacity of our hidden layer in the neural network. Lastly, we define the learning rate, which determines how big the steps are during optimization — smaller values lead to slower but more stable learning, while larger values make training faster but risk overshooting the optimal solution.</p><pre>BATCH_SIZE = 32      # Number of samples processed before the model updates<br>EPOCHS = 10          # Number of times the model will see the entire dataset<br>HIDDEN_NEURONS = 10  # Number of neurons in the hidden layer<br>LR = 1e-3            # Learning rate, controls step size in gradient descent</pre><h3>8. Data Loaders</h3><p>DataLoaders in PyTorch help us feed data into the model in small groups called batches. Instead of processing the entire dataset at once (which is inefficient), we use batches to train the model step by step. This speeds up training, reduces memory usage, and allows for faster weight updates.</p><p>When creating a DataLoader, we specify:</p><p>Batch size: how many samples to process at a time.</p><p>Shuffle: whether to randomize the order of data each epoch, which helps the model generalize better.</p><p>In the code below, we create DataLoaders for the training, validation, and testing datasets. These will automatically handle batching and shuffling during training.</p><p>So Basically</p><p>Dataset: Full data</p><p>DataLoader: Breaks data into batches, shuffles if needed</p><p>Batches: Fed to the model one by one in training</p><p>Dataset <strong>-&gt;</strong> DataLoader (batch_size=32, shuffle=True) <strong>-&gt;</strong> Batches <strong>-&gt;</strong> Model Training Loop</p><p><strong>BONUS QUESTION FOR INTERVIEWS</strong></p><p>Shuffling means randomizing the order of data before each epoch. This prevents the model from learning the order of the data, which could cause overfitting or poor generalization. It helps the model see a different order of data each time, improving learning.</p><pre>train_dataloader = DataLoader(training_data, batch_size=BATCH_SIZE, shuffle= True)<br>validation_dataloader = DataLoader(validation_data, batch_size=BATCH_SIZE, shuffle= True)<br>testing_dataloader = DataLoader(testing_data, batch_size=BATCH_SIZE, shuffle= True)</pre><h3>9. Model Class</h3><p>Building a model in PyTorch might feel a bit complicated at first, but once you understand the flow of data in machine learning, it becomes much clearer. In PyTorch, we create models by defining a class that inherits from nn.Module, similar to how we created our custom dataset.</p><p>In the code below, we define a class called MyModel. In the constructor function <strong>init</strong>, we first call the constructor of the parent class using super(MyModel, self).<strong>init</strong>(). This ensures we initialize everything properly from PyTorch’s base class.</p><p>Next, we define our model layers:</p><ol><li>Input layer: Takes the input features (number of columns in the dataset) and connects them to the hidden neurons.</li><li>Hidden/output layer: Takes the output of hidden neurons and maps it to a single output, since we are performing binary classification.</li><li>Activation function: We use Sigmoid, which squashes the output between 0 and 1, perfect for binary classification.</li></ol><p>Then, we define the forward function. This is where we describe how the data flows through our model — from the input layer, through the hidden layer, and finally to the output with the activation function. PyTorch gives us full control here, which makes it very flexible</p><p>Input Features (X)</p><p>↓</p><p>Input Layer (nn.Linear: input size → hidden neurons)</p><p>↓</p><p>Hidden Layer (nn.Linear: hidden neurons → 1)</p><p>↓</p><p>Sigmoid Activation (nn.Sigmoid)</p><p>↓</p><p>Output (Probability between 0 and 1)</p><p>Lastly, Why do we define forward() manually? In PyTorch, the forward() function controls how data moves through the network. This flexibility allows you to build simple models like this one or complex architectures like CNNs, RNNs, or even Transformers. PyTorch doesn’t restrict you to fixed architectures.</p><pre>class MyModel(nn.Module):<br>    def __init__(self):<br><br>        super(MyModel, self).__init__()<br><br>        self.input_layer = nn.Linear(X.shape[1], HIDDEN_NEURONS)<br>        self.linear = nn.Linear(HIDDEN_NEURONS, 1)<br>        self.sigmoid = nn.Sigmoid()<br><br>    def forward(self, x):<br>        x = self.input_layer(x)<br>        x = self.linear(x)<br>        x = self.sigmoid(x)<br>        return x</pre><h3>10. Model Creation</h3><p>Now lets create our model and move it to the assigned device (cuda if you have GPU or the CPU if you don’t have any GPUs). Additionally, we will print the a summary of the model using the function summary which will take our model and the input size.</p><pre>model = MyModel().to(device)<br>summary(model, (X.shape[1],))</pre><h3>11. Loss and Optimizer</h3><p>In this step, we define the <strong>loss function</strong> and the <strong>optimizer</strong> for our model.</p><p>Since we are performing binary classification, we use <strong>Binary Cross Entropy Loss (BCELoss)</strong> as our loss function. This measures how well the model’s predicted probabilities match the actual labels (0 or 1). A lower loss means better predictions.</p><p>For the optimizer, we use <strong>Adam</strong>, which is a popular and efficient optimization algorithm. It updates the model’s weights based on the computed gradients and the specified learning rate. We pass the model parameters and our learning rate (LR) to Adam.</p><p>With the loss function and optimizer defined, our model is ready to start learning</p><pre># Define the loss function<br>criterion = nn.BCELoss()<br><br># Define the optimizer<br>optimizer = Adam(model.parameters(), lr=LR)</pre><h3>12. Training</h3><p>Now comes the exciting part — training the model!<br>It may look complicated at first, but once you understand how deep learning works, this will feel familiar. We just follow the PyTorch syntax step by step.</p><p>First, we prepare four <strong>lists</strong> to store values for loss and accuracy over each epoch. These lists will help us visualize training and validation performance later.</p><p>Then, inside the training loop, we define four <strong>variables</strong> to track training and validation loss and accuracy for each epoch:</p><ul><li>total_acc_train: Tracks training accuracy.</li><li>total_loss_train: Tracks training loss.</li><li>total_acc_val: Tracks validation accuracy.</li><li>total_loss_val: Tracks validation loss.</li></ul><h3>Training Loop</h3><p>For each epoch, we loop through the training data using the DataLoader.<br>We use enumerate() for flexibility, even though we’re not using the index for now.</p><p>For each batch:</p><ol><li>Extract inputs and labels, and feed the inputs to the model.</li><li>The model makes predictions (<strong>forward pass</strong>).</li><li>Calculate the batch loss.</li><li>Track the loss and compute accuracy.</li><li>Perform <strong>backpropagation</strong> with batch_loss.backward().</li><li>Update weights with optimizer.step().</li><li>Reset gradients with optimizer.zero_grad() (very important!).</li></ol><h3>Validation Loop</h3><p>After training batches, we move to validation — still inside the same epoch.</p><p>For validation:</p><ol><li>Use torch.no_grad() since we don’t need to compute gradients.</li><li>Pass validation data through the model.</li><li>Calculate predictions, loss, and accuracy.</li><li>Track these values for progress monitoring.</li></ol><h3>Tracking Progress</h3><p>At the end of each epoch, we:</p><ul><li>Calculate average losses and accuracies.</li><li>Store them in our lists for plotting later.</li><li>Print out the progress to see how our model is performing.</li></ul><h3>Training Process Flow Diagram</h3><p>For each epoch:</p><p>Dataset → DataLoader → Batches ↓ Training Loop: — Forward pass — Compute loss — Backpropagation — Update weights — Zero gradients ↓ Validation Loop: — Forward pass (no gradients) — Compute loss — Track accuracy ↓ Record &amp; Print Metrics</p><h3>Note: Why is optimizer.zero_grad() important?</h3><p>Before starting backpropagation for each batch, we reset the gradients using optimizer.zero_grad().<br>Without this, gradients from previous batches will accumulate, leading to incorrect updates</p><pre># Lists to store loss and accuracy for plotting<br>total_loss_train_plot = []<br>total_loss_validation_plot = []<br>total_acc_train_plot = []<br>total_acc_validation_plot = []<br><br># Training loop over all epochs<br>for epoch in range(EPOCHS):<br>    # Variables to track total loss and accuracy each epoch<br>    total_acc_train = 0<br>    total_loss_train = 0<br>    total_acc_val = 0<br>    total_loss_val = 0<br><br>    # Training phase<br>    for data in train_dataloader:<br>        inputs, labels = data<br><br>        # Forward pass<br>        prediction = model(inputs).squeeze(1)<br><br>        # Compute loss<br>        batch_loss = criterion(prediction, labels)<br><br>        # Track training loss and accuracy<br>        total_loss_train += batch_loss.item()<br>        acc = ((prediction).round() == labels).sum().item()<br>        total_acc_train += acc<br><br>        # Backpropagation<br>        batch_loss.backward()<br>        optimizer.step()<br>        optimizer.zero_grad()<br><br>    # Validation phase<br>    with torch.no_grad():<br>        for data in validation_dataloader:<br>            inputs, labels = data<br><br>            # Forward pass<br>            prediction = model(inputs).squeeze(1)<br><br>            # Compute loss<br>            batch_loss = criterion(prediction, labels)<br><br>            # Track validation loss and accuracy<br>            total_loss_val += batch_loss.item()<br>            acc = ((prediction).round() == labels).sum().item()<br>            total_acc_val += acc<br><br>    # Store results for plotting<br>    total_loss_train_plot.append(round(total_loss_train / 1000, 4))<br>    total_loss_validation_plot.append(round(total_loss_val / 1000, 4))<br>    total_acc_train_plot.append(round(total_acc_train / training_data.__len__() * 100, 4))<br>    total_acc_validation_plot.append(round(total_acc_val / validation_data.__len__() * 100, 4))<br><br>    # Print epoch summary<br>    print(f&#39;&#39;&#39;Epoch no. {epoch + 1} Train Loss: {total_loss_train / 1000:.4f} Train Accuracy: {(total_acc_train / training_data.__len__() * 100):.4f} Validation Loss: {total_loss_val / 1000:.4f} Validation Accuracy: {(total_acc_val / validation_data.__len__() * 100):.4f}&#39;&#39;&#39;)<br>    print(&quot;=&quot; * 50)</pre><h3>13. Testing</h3><p>Now it’s time to test our trained model!</p><p>We start with torch.no_grad(), which tells PyTorch that we are in evaluation mode and no gradient calculations are needed, since we are not training the model anymore.</p><p>Next, we initialize two variables to zero:</p><ul><li>total_loss_test: To track the total loss over the test dataset.</li><li>total_acc_test: To track the total accuracy over the test dataset.</li></ul><p>Then, we loop through the <strong>testing DataLoader</strong>, just like we did during training. For each batch:</p><ol><li>We get the input data and labels.</li><li>Move them to the GPU (cuda).</li><li>Pass the inputs to the model to get predictions.</li><li>Compute the batch loss and add it to the total test loss.</li><li>Compute accuracy by comparing predictions with true labels and add it to the total test accuracy.</li></ol><p>Finally, we print the overall accuracy of the model on the test set!</p><p>This gives us a clear understanding of how well our model performs on unseen data.</p><pre># Testing phase<br>with torch.no_grad():<br>    total_loss_test = 0<br>    total_acc_test = 0<br><br>    for data in testing_dataloader:<br>        inputs, labels = data<br><br>        # Forward pass<br>        prediction = model(inputs).squeeze(1)<br><br>        # Compute loss<br>        batch_loss_test = criterion(prediction, labels)<br>        total_loss_test += batch_loss_test.item()<br><br>        # Compute accuracy<br>        acc = ((prediction).round() == labels).sum().item()<br>        total_acc_test += acc<br><br># Print final test accuracy<br>print(f&quot;Accuracy Score is: {round((total_acc_test / X_test.shape[0]) * 100, 2)}%&quot;)</pre><h3>14. Plotting and Visualizations (Optional)</h3><p>Now let’s visualize how our model performed during training!</p><p>We will plot both:</p><ul><li><strong>Training and Validation Loss</strong></li><li><strong>Training and Validation Accuracy</strong></li></ul><p>These visualizations help us understand if the model is learning well, overfitting, or underfitting. If the gap between training and validation performance is too large, we might need to improve our model by adjusting layers, hyperparameters, or data preprocessing.</p><p>The current results might not be perfect, so feel free to experiment with:</p><ul><li>Model architecture (add/remove layers or neurons)</li><li>Hyperparameters (learning rate, epochs, batch size)</li><li>Data preprocessing (like cleaning or filtering text data)</li></ul><p>Play around to see if you can achieve better performance</p><pre># Plotting training and validation loss and accuracy<br><br>fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(15, 5))<br><br># Plot Loss<br>axs[0].plot(total_loss_train_plot, label=&#39;Training Loss&#39;)<br>axs[0].plot(total_loss_validation_plot, label=&#39;Validation Loss&#39;)<br>axs[0].set_title(&#39;Training and Validation Loss over Epochs&#39;)<br>axs[0].set_xlabel(&#39;Epochs&#39;)<br>axs[0].set_ylabel(&#39;Loss&#39;)<br>axs[0].set_ylim([0, 2])<br>axs[0].legend()<br><br># Plot Accuracy<br>axs[1].plot(total_acc_train_plot, label=&#39;Training Accuracy&#39;)<br>axs[1].plot(total_acc_validation_plot, label=&#39;Validation Accuracy&#39;)<br>axs[1].set_title(&#39;Training and Validation Accuracy over Epochs&#39;)<br>axs[1].set_xlabel(&#39;Epochs&#39;)<br>axs[1].set_ylabel(&#39;Accuracy&#39;)<br>axs[1].set_ylim([0, 100])<br>axs[1].legend()<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9EeBkx04SWkDjcvVc815tQ.png" /></figure><h3>15. Inference</h3><p>Finally, let’s see how we can use our trained model to make predictions!<br>This process is called <strong>inference</strong>, and it’s what you would do when using the model in a real-world application or production environment.</p><p>We start by taking inputs from the user. Since our model was trained on <strong>normalized data</strong>, we also need to normalize the user inputs by dividing them by the maximum values from the original dataset.</p><p>Once we have the normalized inputs:</p><ol><li>We create a tensor from these inputs and move it to the appropriate device (CPU/GPU).</li><li>We pass this tensor through the model to get a prediction.</li><li>Finally, we print out the raw prediction score and the predicted class (rounded output).</li></ol><p>This is a simple but practical way to deploy and use your trained model</p><pre># Inference: Making predictions with user input<br><br># Collect and normalize user inputs<br>area = float(input(&quot;Area: &quot;)) / original_df[&#39;Area&#39;].abs().max()<br>MajorAxisLength = float(input(&quot;Major Axis Length: &quot;)) / original_df[&#39;MajorAxisLength&#39;].abs().max()<br>MinorAxisLength = float(input(&quot;Minor Axis Length: &quot;)) / original_df[&#39;MinorAxisLength&#39;].abs().max()<br>Eccentricity = float(input(&quot;Eccentricity: &quot;)) / original_df[&#39;Eccentricity&#39;].abs().max()<br>ConvexArea = float(input(&quot;Convex Area: &quot;)) / original_df[&#39;ConvexArea&#39;].abs().max()<br>EquivDiameter = float(input(&quot;EquivDiameter: &quot;)) / original_df[&#39;EquivDiameter&#39;].abs().max()<br>Extent = float(input(&quot;Extent: &quot;)) / original_df[&#39;Extent&#39;].abs().max()<br>Perimeter = float(input(&quot;Perimeter: &quot;)) / original_df[&#39;Perimeter&#39;].abs().max()<br>Roundness = float(input(&quot;Roundness: &quot;)) / original_df[&#39;Roundness&#39;].abs().max()<br>AspectRation = float(input(&quot;AspectRation: &quot;)) / original_df[&#39;AspectRation&#39;].abs().max()<br><br># Prepare the input tensor<br>my_inputs = [area, MajorAxisLength, MinorAxisLength, Eccentricity, ConvexArea, EquivDiameter, Extent, Perimeter, Roundness, AspectRation]<br><br>print(&quot;=&quot; * 20)<br><br># Convert to tensor and move to device<br>model_inputs = torch.Tensor(my_inputs).to(device)<br><br># Make prediction<br>prediction = model(model_inputs)<br><br># Output prediction<br>print(prediction)<br>print(&quot;Class is: &quot;, round(prediction.item()))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fdcf3d98a01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic AI — First Building steps.]]></title>
            <link>https://medium.com/@ali202.muhammad/agentic-ai-first-building-steps-f1423f6330e4?source=rss-34670fa62922------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1423f6330e4</guid>
            <category><![CDATA[phidata]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Muhammad Ali]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 15:58:30 GMT</pubDate>
            <atom:updated>2025-02-27T15:58:30.199Z</atom:updated>
            <content:encoded><![CDATA[<h3>Agentic AI — First Building steps.</h3><p>Build your first Financial Agent using PhiData</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-b-KLj-DFmgxN3I01LtU8A.jpeg" /><figcaption>AGENTIC AI</figcaption></figure><p>What we are going to do is create an application that in turn will have multiple agents. Like for example I ask a question summarize and recommend about the stock on NVidia, so now my chat bot will go and interact with the agents, lets say</p><ol><li>Agent 1 will go and get the details about the stock</li><li>Agent 2 will go to news and get some information from there</li><li>Once we combine the info, it should go to my LLM with all that info and then try to come up with a recommendation</li></ol><p>STEPS</p><p>Open your Project Folder in your IDE, I’ll be using VS Code. Now open terminal in the VS code or any other IDE, make sure your terminal is your project folder and then create a virtual environment</p><pre>conda create -p venv python==3.12</pre><p>Now create a requirements.txt file with following packages</p><pre>phidata<br>python-dotenv<br>yfinance<br>packaging<br>duckduckgo-search<br>fastapi<br>uvicorn<br>groq<br>openai</pre><p>Now activate your conda environment</p><pre>conda activate venv </pre><p>Now python -m pip install -r requrements.txt</p><p>Since we are installing python-dotenv, we will also require a .env file so create that, here we will add our PhiData key and Groq API key</p><p>First for groq API key go to <a href="https://groq.com/">https://groq.com/</a> and navigate to devconsole ( you will need to sign up if it is first time), click on to API KEYs then create and copy your API key</p><p>Similarly for Phi data API key go to <a href="https://www.phidata.app/">https://www.phidata.app/</a>, you will need to sign up if it is first time, ), click on to API KEYs then copy your API key</p><p>Your .env file should look something like this</p><pre>GROQ_API_KEY=&quot;API KEY HERE&quot; #GROQ API KEY<br>PHI_API_KEY=&quot;API KEY HERE&quot; #PHI DATA API KEY</pre><p>Now lets start with the fun, create a financial_agent.py file,</p><p>First the imports</p><pre>from phi.agent import Agent<br>from phi.model.groq import Groq<br>from phi.tools.yfinance import YFinanceTools<br>from phi.tools.duckduckgo import DuckDuckGo</pre><p>Now we will create separate agents for each task that is to performed</p><p>AGENT 1 — This will search the web. As you can see we specified a name, a role which tells the agent what it will do, a llm imported vai Groq, we can use any model, we are using tools which are prebuilt connectons in Phidata, here we are using DuckDuckGo as a tool to search web, we also gave it some instructions, like here I told it to “Always include Sources” and lastly we set the last two properties i.e., show_tool_calls and markdown as True</p><pre># WEB SEARCH AGENT<br>websearch_agent=Agent(<br>    name=&quot;Web Search Agent&quot;,<br>    role=&quot;Search the web for information&quot;,<br>    model=Groq(id=&quot;llama3-70b-8192&quot;),<br>    tools=[DuckDuckGo()],<br>    instructions=[&quot;Always include Sources&quot;],<br>    show_tool_calls=True,<br>    markdown=True,<br>)</pre><p>Similary Agent 2 — which will be our Financial agent and here we don’t define the role as we are using yFinance which is another builtin connector in phidata to do financial analysis.</p><pre># FINANCIAL AGENT<br>finance_agent=Agent(<br>    name=&quot;Financial AI Agent&quot;,<br>    model=Groq(id=&quot;llama3-70b-8192&quot;),<br>    tools=[<br>        YFinanceTools(stock_price=True, analyst_recommendations=True, stock_fundamentals=True, company_news=True),<br>    ],<br>    instructions=[&quot;Use Table to display the data&quot;],<br>    show_tool_calls=True,<br>    markdown=True,<br>)</pre><p>To get a better understanding please do visit documentation of PhiData, it will explain in depth about tools and what parameters are we using and why.</p><p>Then we will create a multi ai agent bot which will be like a manager to both our agents and it will get the job done for us by assigning tasks to our agents based on the query.</p><pre>multi_ai_agent=Agent(<br>    team=[websearch_agent, finance_agent],<br>    model=Groq(id=&quot;llama3-70b-8192&quot;),<br>    instructions=[&quot;Always include sources&quot;, &quot;Use tables to display data&quot;],<br>    show_tool_calls=True,<br>    markdown=True,<br>)</pre><p>Lastly let us test by querying the bot about NVDA stock, here for testing I am just hard coding the query but we can also ask the user in a chatbots scenario.</p><pre>multi_ai_agent.print_response(&quot;Summarize analyst recommendations and share the latest news for NVDA&quot;, stream=True)</pre><p>After running the financial_agent.py file, I get this response</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*OsM2Ns3x_npHsGNj1M7e_w.png" /></figure><p>Here is the complete financial_agent.py file</p><pre>from phi.agent import Agent<br>from phi.model.groq import Groq<br>from phi.tools.yfinance import YFinanceTools<br>from phi.tools.duckduckgo import DuckDuckGo<br><br>#We will create separate agents for separatew tasks<br><br># WEB SEARCH AGENT<br>websearch_agent=Agent(<br>    name=&quot;Web Search Agent&quot;,<br>    role=&quot;Search the web for information&quot;,<br>    model=Groq(id=&quot;llama3-70b-8192&quot;),<br>    tools=[DuckDuckGo()],<br>    instructions=[&quot;Always include Sources&quot;],<br>    show_tool_calls=True,<br>    markdown=True,<br>)<br><br># FINANCIAL AGENT<br>finance_agent=Agent(<br>    name=&quot;Financial AI Agent&quot;,<br>    model=Groq(id=&quot;llama3-70b-8192&quot;),<br>    tools=[<br>        YFinanceTools(stock_price=True, analyst_recommendations=True, stock_fundamentals=True, company_news=True),<br>    ],<br>    instructions=[&quot;Use Table to display the data&quot;],<br>    show_tool_calls=True,<br>    markdown=True,<br>)<br><br>multi_ai_agent=Agent(<br>    team=[websearch_agent, finance_agent],<br>    model=Groq(id=&quot;llama3-70b-8192&quot;),<br>    instructions=[&quot;Always include sources&quot;, &quot;Use tables to display data&quot;],<br>    show_tool_calls=True,<br>    markdown=True,<br>)<br><br>multi_ai_agent.print_response(&quot;Summarize analyst recommendations and share the latest news for NVDA&quot;, stream=True)</pre><p>Looks pretty good now let’s try to publish these agents as a chatbots on PhiData playground platform</p><p>First create a new file, let’s call it playground.py</p><p>Now lets us start with the imports.</p><pre>from phi.agent import Agent<br>from phi.model.groq import Groq<br>from phi.tools.yfinance import YFinanceTools<br>from phi.tools.duckduckgo import DuckDuckGo<br>import phi.api<br>import phi<br>from phi.playground import Playground, serve_playground_app<br>from dotenv import load_dotenv<br>import os</pre><p>Now let us load our env file with the API keys</p><pre>#load ENV VariaBLES FROM .ENV FILE<br>load_dotenv()<br>phi.api=os.getenv(&quot;PHI_API_KEY&quot;)</pre><p>Now we will copy past both our agents without any changes</p><pre># WEB SEARCH AGENT<br>websearch_agent=Agent(<br>    name=&quot;Web Search Agent&quot;,<br>    role=&quot;Search the web for information&quot;,<br>    model=Groq(id=&quot;llama3-70b-8192&quot;),<br>    tools=[DuckDuckGo()],<br>    instructions=[&quot;Always include Sources&quot;],<br>    show_tool_calls=True,<br>    markdown=True,<br>)<br><br># FINANCIAL AGENT<br>finance_agent=Agent(<br>    name=&quot;Financial AI Agent&quot;,<br>    model=Groq(id=&quot;llama3-70b-8192&quot;),<br>    tools=[<br>        YFinanceTools(stock_price=True, analyst_recommendations=True, stock_fundamentals=True, company_news=True),<br>    ],<br>    instructions=[&quot;Use Table to display the data&quot;],<br>    show_tool_calls=True,<br>    markdown=True,<br>)</pre><p>Now we will create our Playground which will be hosted on localhost and also the main function</p><pre>app=Playground(<br>    agents=[finance_agent,websearch_agent]<br>).get_app()<br><br>if __name__==&quot;__main__&quot;:<br>    serve_playground_app(&quot;playground:app&quot;, reload=True)</pre><p>After you run, it will show you that it is live on localhost but if you click the link it won’t work</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*DqVPZS4y83_RZqSnJzflhA.png" /></figure><p>So for this go to the PhiData Dashboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*rHrtXwcB0ZQb4VavbvaC1Q.png" /></figure><p>Click on Playground</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*ztELPCxV33bVJ3m2prtHAQ.png" /></figure><p>Click on the Endpoint and it will either show you the local host or you can click on Add endpoint and add the local host url</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*MpbSuKqkqr1SmT-QhBtbkA.png" /></figure><p>To see what you URL is, after you run the playground File URL will show on your terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*WSKlHRmiAds0c44lW1OPmg.png" /></figure><p>After you select the endpoint in your playground, a chat window will show</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*c74rD7iK5xA8cyU1RhSquA.png" /></figure><p>Now you can Interact with you Chatbot and have fun.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*yY4sznqXektEzC8ul7_6ZQ.png" /></figure><h3>Hope you liked the article please like share and subscribe.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1423f6330e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>