Friday, 17 January 2025

Hands on with Llama #2

Let us play with Gradio UI!

Creating a Gradio interface only requires adding a couple lines of code to your project. Seamlessly use any python library on your computer. If you can write a python function, gradio can run it.


GROQ_API_KEY = 'Your GROQ_API_KEY '
print('key:' , GROQ_API_KEY)

from langchain_groq import ChatGroq

chat = ChatGroq(
 
    api_key = GROQ_API_KEY,
    model_name = 'mixtral-8x7b-32768',
)

from langchain_core.prompts import ChatPromptTemplate

system = " You are an Expert"
human = "{text}"

prompt = ChatPromptTemplate.from_messages(
    [
        ("system", system), ("human", human)
    ]    
)

from langchain_core.output_parsers import StrOutputParser

chain = prompt| chat | StrOutputParser()

chain.invoke(
    {"text": "why the sky is blue?"}
)
# build an app
import gradio as gr
def fetch_response(user_input):
  chat = ChatGroq(
    api_key = GROQ_API_KEY,
    model_name = "mixtral-8x7b-32768"
  )
  system = "You are a helpful assistant."
  human = "{text}"

  prompt = ChatPromptTemplate.from_messages(
      [
          ("system", system), ("human", human)
      ]
  )
  chain = prompt | chat | StrOutputParser()
  output = chain.invoke({"text": user_input})
  return output
     
user_input = "why is the sky blue?"
fetch_response(user_input)

iface = gr.Interface(
    fn = fetch_response,
    inputs = "text",
    outputs = "text",
    title = "Groq Chatbot",
    description="Ask a question and get a response."
)
iface.launch(share= True)


output

Running on local URL:  http://127.0.0.1:7860

In user_input Text Area Type 

Write a python list with simple code snippet

and click submit, you will get response 


If you click flag button,
Everything will be save in dataset2.csv under flagged directory

user_input,output,timestamp
write a python list with simple code snippet,"Sure,
here is a simple Python code snippet that creates a list of numbers from 1 to 5:
```python
numbers = [1, 2, 3, 4, 5]
print(numbers)
```
When you run this code, it will output:
```csharp
[1, 2, 3, 4, 5]
```
You can also create a list of strings, for example:
```python
fruits = ['apple', 'banana', 'cherry', 'date']
print(fruits)
```
This will output:
```csharp
['apple', 'banana', 'cherry', 'date']
```
I hope this helps! Let me know if you have any other questions.",2025-01-18 00:33:36.397634

Got a simple magical Example, how to use GroQ and Gradio!


Sunday, 12 January 2025

Web Scratch - iMM (For Sethu?)

 Let us have fun!. (as a Web Scraping  3 Minute Exercise)

As per Deliverables by Sethu ( May be useful)

We have to backup iMM website from GoDaddy.

Try this code:

import requests

import os
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse

def get_all_urls(website_url):
    try:
        response = requests.get(website_url)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'html.parser')

        urls = set()
        for a_tag in soup.find_all('a', href=True):
            full_url = urljoin(website_url, a_tag['href'])
            urls.add(full_url)
       
        return urls

    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")
        return set()

def backup_urls(urls, backup_dir="backups"):
    os.makedirs(backup_dir, exist_ok=True)

    for url in urls:
        try:
            response = requests.get(url)
            response.raise_for_status()

            # Generate a safe file name based on the URL
            parsed_url = urlparse(url)
            file_name = parsed_url.netloc + parsed_url.path.replace("/", "_") + ".html"
            file_path = os.path.join(backup_dir, file_name)

            # Save the HTML content to a file
            with open(file_path, 'w', encoding='utf-8') as file:
                file.write(response.text)
           
            print(f"Backup saved: {file_path}")
       
        except requests.exceptions.RequestException as e:
            print(f"Failed to backup {url}: {e}")

# Example usage

website = "https://intmmsw.com/"
urls = get_all_urls(website)
print(urls)
print(f"Found {len(urls)} URLs. Starting backup...")
backup_urls(urls)

Big Fun! Sweet! Got all HTML back up files on your desktop in a Minute !!! 

# Response

"""
Found 21 URLs. Starting backup...
Backup saved: backups\intmmsw.com_software-%26-hitech.html
Backup saved: backups\intmmsw.com_oil-%26-gas-1.html
Backup saved: backups\intmmsw.com_google-cloud-1.html
Backup saved: backups\intmmsw.com_rpa.html
Backup saved: backups\intmmsw.com_cloud-computing.html
Backup saved: backups\intmmsw.com_development-center.html
Backup saved: backups\intmmsw.com_software-as-a-service.html
Backup saved: backups\intmmsw.com_healthcare-%26-biotech-1.html
Backup saved: backups\intmmsw.com_professional-services-1.html
Backup saved: backups\intmmsw.com_oci.html
Backup saved: backups\intmmsw.com_artificial-intelligence.html
Backup saved: backups\intmmsw.com_data-analytics-%26-insights-1.html
Backup saved: backups\intmmsw.com_.html
Backup saved: backups\intmmsw.com_web-development.html
Backup saved: backups\intmmsw.com_digital-transformation-1.html
Backup saved: backups\intmmsw.com_education-%26-learning-1.html
Backup saved: backups\intmmsw.com_banking-%26-fintech-1.html
Backup saved: backups\intmmsw.com_govt-%26-public-sector-1.html
Backup saved: backups\intmmsw.com_data-warehouse%2Fdatalake.html
Backup saved: backups\intmmsw.com_azure-1.html
Backup saved: backups\intmmsw.com_aws.html
"""

Note : 

Pl. clone our web site with some tool and download in to your desktop for other files like jpg, png, js, css, scss!!!☝

 

Hands on with Llama

Let us try how we can build a agent using llama opensource and compare this use case with 

ChatGPT & Perplexity.

First go to the llama website,  create account, log in to that, 

Go to API page,  and generate key, copy and keep it safe.

Put that in .env file

.env file

GROQ_API_Key = '' # get your GROQ_API_Key

1_groq_agent.py

from phi.agent import Agent
from phi.model.groq import Groq
from dotenv import load_dotenv
load_dotenv()
# print(GROQ_API_KEY)
agent = Agent (
    model=Groq(id="llama-3.3-70b-versatile")
)
agent.print_response ("Write 2  sentences poem for love between dosa and idly")
# # # Create a query to find all documents containing the word 'love'

Response

Dosa and idly, a perfect pair, their love steams hot, like the sambar they share.         ┃
Together on a plate, they dance with glee, a match made in heaven, for you and me.      

2_finance_agent_groq.py

from phi.agent import Agent
from phi.model.groq import Groq
from dotenv import load_dotenv
from phi.tools.yfinance import YFinanceTools
from dotenv import load_dotenv

load_dotenv()
       

agent = Agent (
    model=Groq(id="llama-3.3-70b-versatile"),
    tools=[YFinanceTools(stock_price=True, analyst_recommendations=True,
stock_fundamentals=False)],
    show_tool_calls=True,
    markdown=True,
    instructions = ["Use tables to display data."],
    debug_mode=True,
)

agent.print_response("Summarize and compare analyst recommendations and
fundamentals for TSL and NVDA")

Response

Running:                                                                                  ┃
┃                                                                                           ┃
┃  • get_analyst_recommendations(symbol=TSLA)                                               ┃
┃  • get_analyst_recommendations(symbol=NVDA)                                               ┃
┃  • get_current_stock_price(symbol=TSLA)                                                   ┃
┃  • get_current_stock_price(symbol=NVDA)                                                   ┃
┃                                                                                           ┃
┃           Summary of Analyst Recommendations and Fundamentals for TSLA and NVDA           ┃
┃                                                                                           ┃
┃                                 Analyst Recommendations:                                  ┃
┃                                                                                           ┃
┃                                                                                           ┃
┃   Stock Symbol   Strong Buy   Buy   Hold   Sell   Strong Sell                             ┃
┃  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━                            ┃
┃   TSLA           6            14    15     9      4                                       ┃
┃   NVDA           12           46    5      0      0                                       ┃
┃                                                                                           ┃
┃                                                                                           ┃
┃                                   Current Stock Price:                                    ┃
┃                                                                                           ┃
┃                                                                                           ┃
┃   Stock Symbol   Current Price                                                            ┃
┃  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━                                                           ┃
┃   TSLA           $394.74                                                                  ┃
┃   NVDA           $135.91                                                                  ┃
┃                                                                                           ┃
┃                                                                                           ┃
┃                  Comparison of Analyst Recommendations and Fundamentals:                  ┃
┃                                                                                           ┃
┃  • TSLA (Tesla, Inc.):                                                                    ┃
┃     • Analyst recommendations: 6 Strong Buy, 14 Buy, 15 Hold, 9 Sell, 4 Strong Sell       ┃
┃     • Current stock price: $394.74                                                        ┃
┃  • NVDA (NVIDIA Corporation):                                                             ┃
┃     • Analyst recommendations: 12 Strong Buy, 46 Buy, 5 Hold, 0 Sell, 0 Strong Sell       ┃
┃     • Current stock price: $135.91                                                        ┃
┃                                                                                           ┃
┃ Overall, NVDA has a more positive analyst sentiment, with a higher number of
┃ Strong Buy and Buy recommendations. TSLA has a more mixed analyst sentiment, with a
┃ higher number of Hold and Sell recommendations.
┃                                                                                          
┃┃ Note: Please keep in mind that analyst recommendations and stock prices can change
┃┃ rapidly and may not reflect the current market situation. It's always a good idea
┃┃ to do your own research and consult with a financial advisor before making any
investment decisions.                                          

If you run with Debug mode 


PS F:/python3.11.exe f:/iMM/aiagent/2_finance_agent.py

DEBUG    Debug logs enabled
DEBUG    *********** Agent Run Start: 3ccf1064-648a-4654-a6a4-06e111db6a1c ***********      
DEBUG    Function get_current_stock_price from yfinance_tools added to model.
DEBUG    Function get_analyst_recommendations from yfinance_tools added to model.
DEBUG    ---------- Groq Response Start ----------
DEBUG    ============== system ==============
DEBUG    ## Instructions
         - Use tables to display data.
         - Use markdown to format your answers.
DEBUG    ============== user ==============
DEBUG    Summarize and compare analyst recommendations and fundamentals for TSL
and NVDA    
DEBUG    ============== assistant ==============
DEBUG    Tool Calls: [
           {
             "id": "call_wz34",
             "function": {
               "arguments": "{\"symbol\": \"TSLA\"}",
               "name": "get_analyst_recommendations"
             },
             "type": "function"
           },
           {
             "id": "call_fkv1",
             "function": {
               "arguments": "{\"symbol\": \"NVDA\"}",
               "name": "get_analyst_recommendations"
             },
             "type": "function"
           },
           {
             "id": "call_rvt4",
             "function": {
               "arguments": "{\"symbol\": \"TSLA\"}",
               "name": "get_current_stock_price"
             },
             "type": "function"
           },
           {
             "id": "call_0ge1",
             "function": {
               "arguments": "{\"symbol\": \"NVDA\"}",
               "name": "get_current_stock_price"
             },
             "type": "function"
           }
         ]
DEBUG    **************** METRICS START ****************
DEBUG    * Time to generate response:   4.1421s
DEBUG    * Tokens per second:           22.6938 tokens/s
DEBUG    * Input tokens:                703
DEBUG    * Output tokens:               94
DEBUG    * Total tokens:                797
DEBUG    * Completion time:             0.4474s
DEBUG    * Prompt time:                 0.1129s
DEBUG    * Queue time:                  -1.8120s
DEBUG    * Total time:                  0.5603s
DEBUG    **************** METRICS END ******************
DEBUG    Getting function get_analyst_recommendations
DEBUG    Getting function get_analyst_recommendations
DEBUG    Getting function get_current_stock_price
DEBUG    Getting function get_current_stock_price
DEBUG    Running: get_analyst_recommendations(symbol=TSLA)
DEBUG    Running: get_analyst_recommendations(symbol=NVDA)
DEBUG    Running: get_current_stock_price(symbol=TSLA)
DEBUG    Running: get_current_stock_price(symbol=NVDA)
DEBUG    ---------- Groq Response Start ----------
DEBUG    ============== system ==============
DEBUG    ## Instructions
         - Use tables to display data.
         - Use markdown to format your answers.
DEBUG    ============== user ==============
DEBUG    Summarize and compare analyst recommendations and fundamentals for TSL and NVDA    
DEBUG    ============== assistant ==============
DEBUG    Tool Calls: [
           {
             "id": "call_wz34",
             "function": {
               "arguments": "{\"symbol\": \"TSLA\"}",
               "name": "get_analyst_recommendations"
             },
             "type": "function"
           },
           {
             "id": "call_fkv1",
             "function": {
               "arguments": "{\"symbol\": \"NVDA\"}",
               "name": "get_analyst_recommendations"
             },
             "type": "function"
           },
           {
             "id": "call_rvt4",
             "function": {
               "arguments": "{\"symbol\": \"TSLA\"}",
               "name": "get_current_stock_price"
             },
             "type": "function"
           },
           {
             "id": "call_0ge1",
             "function": {
               "arguments": "{\"symbol\": \"NVDA\"}",
               "name": "get_current_stock_price"
             },
             "type": "function"
           }
         ]
DEBUG    ============== tool ==============
DEBUG    Tool call Id: call_wz34
DEBUG    {"0":{"period":"0m","strongBuy":6,"buy":14,"hold":15,"sell":9,"strongSell":4},"1":{"
         period":"-1m","strongBuy":6,"buy":14,"hold":15,"sell":8,"strongSell":5},"2":{"period
         ":"-2m","strongBuy":5,"buy":13,"hold":17,"sell":8,"strongSell":5},"3":{"period":"-3m
         ","strongBuy":6,"buy":12,"hold":19,"sell":7,"strongSell":4}}
DEBUG    ============== tool ==============
DEBUG    Tool call Id: call_fkv1
DEBUG    {"0":{"period":"0m","strongBuy":12,"buy":46,"hold":5,"sell":0,"strongSell":0},"1":{"
         period":"-1m","strongBuy":12,"buy":48,"hold":4,"sell":0,"strongSell":0},"2":{"period
         ":"-2m","strongBuy":12,"buy":48,"hold":4,"sell":0,"strongSell":0},"3":{"period":"-3m
         ","strongBuy":11,"buy":48,"hold":3,"sell":0,"strongSell":1}}
DEBUG    ============== tool ==============
DEBUG    Tool call Id: call_rvt4
DEBUG    394.7400
DEBUG    ============== tool ==============
DEBUG    Tool call Id: call_0ge1
DEBUG    135.9100
DEBUG    ============== assistant ==============
DEBUG    ### Analyst Recommendations for TSLA and NVDA

         The following tables summarize the analyst recommendations for TSLA and NVDA:      

         #### TSLA Analyst Recommendations
         | Period | Strong Buy | Buy | Hold | Sell | Strong Sell |
         | --- | --- | --- | --- | --- | --- |
         | 0m | 6 | 14 | 15 | 9 | 4 |
         | -1m | 6 | 14 | 15 | 8 | 5 |
         | -2m | 5 | 13 | 17 | 8 | 5 |
         | -3m | 6 | 12 | 19 | 7 | 4 |

         #### NVDA Analyst Recommendations
         | Period | Strong Buy | Buy | Hold | Sell | Strong Sell |
         | --- | --- | --- | --- | --- | --- |
         | 0m | 12 | 46 | 5 | 0 | 0 |
         | -1m | 12 | 48 | 4 | 0 | 0 |
         | -2m | 12 | 48 | 4 | 0 | 0 |
         | -3m | 11 | 48 | 3 | 0 | 1 |

         ### Comparison of Analyst Recommendations

         TSLA has a more mixed set of analyst recommendations, with a significant number of  
         "Hold" and "Sell" ratings. In contrast, NVDA has a much more positive set of analyst
         recommendations, with a large majority of "Strong Buy" and "Buy" ratings.

         ### Current Stock Prices

         The current stock prices for TSLA and NVDA are:

         * TSLA: $394.74
         * NVDA: $135.91

         ### Fundamental Comparison

         Without additional data, it's difficult to make a direct comparison of the
         fundamentals of TSLA and NVDA. However, based on the analyst recommendations, it    
         appears that NVDA is currently viewed more favorably by analysts.
DEBUG    **************** METRICS START ****************
DEBUG    * Time to generate response:   2.3808s
DEBUG    * Tokens per second:           169.6931 tokens/s
DEBUG    * Input tokens:                699
DEBUG    * Output tokens:               404
DEBUG    * Total tokens:                1103
DEBUG    * Completion time:             1.4691s
DEBUG    * Prompt time:                 0.0763s
DEBUG    * Queue time:                  0.0188s
DEBUG    * Total time:                  1.5454s
DEBUG    **************** METRICS END ******************
DEBUG    ---------- Groq Response End ----------
DEBUG    Added 7 Messages to AgentMemory
DEBUG    Added AgentRun to AgentMemory
DEBUG    --**-- Logging Agent Run
DEBUG    *********** Agent Run End: 3ccf1064-648a-4654-a6a4-06e111db6a1c ***********
┏━ Message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                                                                                           ┃
┃ Summarize and compare analyst recommendations and fundamentals for TSL and NVDA           ┃
┃                                                                                           ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┏━ Response (11.6s) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                                                                                           ┃
┃ Running:                                                                                  ┃
┃                                                                                           ┃
┃  • get_analyst_recommendations(symbol=TSLA)                                               ┃
┃  • get_analyst_recommendations(symbol=NVDA)                                               ┃
┃  • get_current_stock_price(symbol=TSLA)                                                   ┃
┃  • get_current_stock_price(symbol=NVDA)                                                   ┃
┃                                                                                           ┃
┃                         Analyst Recommendations for TSLA and NVDA                         ┃
┃                                                                                           ┃
┃ The following tables summarize the analyst recommendations for TSLA and NVDA:             ┃
┃                                                                                           ┃
┃                               TSLA Analyst Recommendations                                ┃
┃                                                                                           ┃
┃                                                                                           ┃
┃   Period   Strong Buy   Buy   Hold   Sell   Strong Sell                                   ┃
┃  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━                                  ┃
┃   0m       6            14    15     9      4                                             ┃
┃   -1m      6            14    15     8      5                                             ┃
┃   -2m      5            13    17     8      5                                             ┃
┃   -3m      6            12    19     7      4                                             ┃
┃                                                                                           ┃
┃                                                                                           ┃
┃                               NVDA Analyst Recommendations                                ┃
┃                                                                                           ┃
┃                                                                                           ┃
┃   Period   Strong Buy   Buy   Hold   Sell   Strong Sell                                   ┃
┃  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━                                  ┃
┃   0m       12           46    5      0      0                                             ┃
┃   -1m      12           48    4      0      0                                             ┃
┃   -2m      12           48    4      0      0                                             ┃
┃   -3m      11           48    3      0      1                                             ┃
┃                                                                                           ┃
┃                                                                                           ┃
┃                           Comparison of Analyst Recommendations                           ┃
┃                                                                                           ┃
┃ TSLA has a more mixed set of analyst recommendations, with a significant number of "Hold"
and "Sell" ratings. In contrast, NVDA has a much more positive set of analyst             ┃
┃ recommendations, with a large majority of "Strong Buy" and "Buy" ratings.                 ┃
┃                                                                                           ┃
┃                                   Current Stock Prices                                    ┃
┃                                                                                           ┃
┃ The current stock prices for TSLA and NVDA are:                                           ┃
┃                                                                                           ┃
┃  • TSLA: $394.74                                                                          ┃
┃  • NVDA: $135.91                                                                          ┃
┃                                                                                           ┃
┃                                  Fundamental Comparison                                   ┃
┃                                                                                           ┃
┃ Without additional data, it's difficult to make a direct comparison of the fundamentals   ┃
┃ of TSLA and NVDA. However, based on the analyst recommendations, it appears that NVDA is  ┃
┃ currently viewed more favorably by analysts.    

ChatGPT Prompt

Summarize and compare analyst recommendations and fundamentals for TSL and NVDA

Response

Tesla Inc. (TSLA) and NVIDIA Corporation (NVDA) are prominent players in the technology and automotive sectors, attracting significant attention from investors and analysts. Here's a comparative overview of their analyst recommendations and financial fundamentals:

Analyst Recommendations:

  • **Tesla (TSLA):**

    • Mixed Outlook: Approximately 40% of analysts have issued 'buy' ratings for Tesla, indicating a cautious stance among market experts. citeturn0search0
    • Recent Downgrade: Bank of America recently downgraded Tesla from 'buy' to 'neutral,' citing concerns that the stock's current valuation does not fully account for execution risks associated with ventures like robotaxis and energy storage. citeturn0news26
  • **NVIDIA (NVDA):**

    • Positive Sentiment: NVIDIA continues to receive favorable evaluations from Wall Street analysts, who highlight its leadership in AI hardware and software. citeturn0news24
    • Recent Developments: Following CEO Jensen Huang's presentation at CES 2025, analysts reaffirmed their positive ratings, emphasizing NVIDIA's advancements in AI technology and strategic partnerships. citeturn0news27

Financial Fundamentals:

  • **Tesla (TSLA):**

    • Market Position: Tesla is a leading electric vehicle manufacturer with ventures in energy storage and autonomous driving technology.
    • Valuation Concerns: Analysts have noted that Tesla's forward price-to-earnings (P/E) ratio is relatively high compared to traditional automakers, suggesting that the stock may be priced with significant growth expectations. citeturn0search0
  • **NVIDIA (NVDA):**

    • Market Position: NVIDIA is a dominant player in the AI and GPU markets, with its technologies widely used across various industries, including gaming, data centers, and autonomous vehicles.
    • Growth Prospects: The company's recent product launches, such as the GeForce RTX 50 series and the Blackwell AI processor series, are expected to drive future revenue growth. citeturn0news24

Recent Stock Performance:

  • **Tesla (TSLA):**

    • Current Price: As of January 11, 2025, Tesla's stock is trading at $394.74, reflecting a slight decrease of 0.07% from the previous close.
  • **NVIDIA (NVDA):**

    • Current Price: As of January 11, 2025, NVIDIA's stock is priced at $135.91, showing a decline of 2.98% from the previous close.

Conclusion:

Both Tesla and NVIDIA are at the forefront of innovation in their respective fields, attracting substantial interest from investors and analysts. While NVIDIA enjoys a broadly positive outlook due to its advancements in AI technology, Tesla faces a more mixed reception, with concerns about execution risks and high valuations. Investors should consider these factors, along with their financial goals and risk tolerance, when evaluating potential investments in these companies....

Hands on with Llama #2

Let us play with Gradio UI! Creating a Gradio interface only requires adding a couple lines of code to your project.  Seamlessly use any pyt...