Tuesday, 25 March 2025

Dockerize Agent -Document Processing

 Since you are using Flask in Agent.py, I will modify the Dockerfile and steps accordingly. [WIP]


1. Update the Dockerfile

Create a Dockerfile in the same directory as Agent.py and index.html:

# Use an official Python image as the base
FROM python:3.10

# Set the working directory inside the container
WORKDIR /app

# Copy the application files to the container
COPY . .

# Install required dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Expose the Flask default port
EXPOSE 5000

# Set the environment variable to tell Flask to run on all network interfaces
ENV FLASK_APP=Agent.py
ENV FLASK_RUN_HOST=0.0.0.0

# Start the Flask server
CMD ["flask", "run", "--host=0.0.0.0", "--port=5000"]

2. Create a .dockerignore File

To exclude unnecessary files from the image, create a .dockerignore file:

__pycache__/
*.pyc
*.pyo
*.log
venv/

3. Ensure Agent.py is Properly Configured

Modify Agent.py to run the Flask server on all available network interfaces:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, Llama3.2 is running inside Docker!"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

4. Build the Docker Image

Run this command inside your project directory (where Dockerfile is located):

docker build -t my-llama3-app .

5. Run the Docker Container

Start a container and map port 5000:

docker run -d -p 5000:5000 --name llama-container my-llama3-app

Now, Flask will be running at http://localhost:5000.


6. Push the Image to RMC65

  1. Log in to RMC65:

    docker login rmc65
    
  2. Tag the Image for RMC65:

    docker tag my-llama3-app rmc65/your-username/my-llama3-app:latest
    
  3. Push the Image to RMC65:

    docker push rmc65/your-username/my-llama3-app:latest
    

7. Run the Image on Another Device

On the new device, follow these steps:

  1. Install Docker (if not installed):

    sudo apt install docker.io -y
    
  2. Pull the Image from RMC65:

    docker pull rmc65/your-username/my-llama3-app:latest
    
  3. Run the Flask Container:

    docker run -d -p 5000:5000 --name llama-container rmc65/your-username/my-llama3-app:latest
    

Now, you can access the Flask app at http://<device-ip>:5000.


Bonus: Push to Docker Hub (if needed)

If you want to push the image to Docker Hub, follow these steps:

  1. Log in:

    docker login
    
  2. Tag the image:

    docker tag my-llama3-app your-dockerhub-username/my-llama3-app:latest
    
  3. Push the image:

    docker push your-dockerhub-username/my-llama3-app:latest
    
  4. On another device, pull & run:

    docker pull your-dockerhub-username/my-llama3-app:latest
    docker run -d -p 5000:5000 --name llama-container your-dockerhub-username/my-llama3-app:latest
    

This setup ensures Flask is properly configured inside Docker, and your application can be easily deployed on any device. Let me know if you need further modifications! πŸš€

Friday, 14 February 2025

AI Agent Basics - Hands on

πŸš€ Pydantic AI Agents: Making AI Work for You (Without the Sci-Fi Apocalypse) πŸ€–

Welcome, future AI overlords (or at least enthusiastic learners)! Today, we're diving into Pydantic AI Agents, a magical blend of Python, automation, and artificial intelligence that makes your life easier (and way cooler). Whether you need an assistant, a web search ninja, or a chatbot buddy, these AI agents have your back. Let's explore three awesome use cases!


1️⃣ The Basic Agent – Your AI Sidekick πŸ¦Έβ€β™‚️

Ever wished for a personal assistant who never complains, never asks for a raise, and always has an answer? Meet our Basic AI Agent, powered by Llama 3.2!

πŸ“œ Code:

from agno.agent import Agent, RunResponse
from agno.models.ollama import Ollama

agent = Agent(
    model=Ollama(id="llama3.2"),
    markdown=True
)

# Ask the AI about government stuff (or anything else!)
agent.print_response("What is the Ministry of Corporate Affairs in India? What does it do?")

πŸ’‘ What Does It Do?

  • Reads your mind (not really, but it does understand your questions).
  • Processes your input using Llama 3.2 (a powerful AI model).
  • Prints intelligent responses without an attitude.

Response:


πŸ‘‰ Real-Life Use Case: Use this agent to automate research for your projects, emails, or just settle arguments in group chats.


2️⃣ The Web Search Agent – Your AI Detective πŸ”

Tired of Googling everything and getting lost in clickbait articles? Enter the Web Search Agent, which fetches the latest news, trends, and research papers faster than your conspiracy-theory-loving uncle.

πŸ“œ Code:

# Install the tools first: pip install phidata duckduckgo-search arxiv

from agno.agent import Agent
from agno.models.ollama import Ollama
from agno.tools.duckduckgo import DuckDuckGoTools
from agno.tools.arxiv import ArxivTools

agent = Agent(
    model=Ollama(id="llama3.2"),
    tools=[DuckDuckGoTools(), ArxivTools()],  # Internet searching powers activated!
    show_tool_calls=True,
    markdown=True
)

# Let's dig into Reinforcement Learning research!
agent.print_response("Search arXiv for 'Reinforcement Learning'")

πŸ’‘ What Does It Do?

  • Ducks into DuckDuckGo (for the latest web news).
  • Raids ArXiv (for cutting-edge research papers).
  • Finds answers instantly, without opening 100+ browser tabs.

Response:

πŸ‘‰ Real-Life Use Case: Perfect for students, researchers, and news junkies who want real-time updates on tech, finance, or cat videos (we won’t judge).


3️⃣ The Chat Agent – Your AI BFF (That Never Ignores You) πŸ’¬

Why text real people when you can chat with an AI that actually listens? The Chat Agent is a conversational AI that responds in real-time through a slick Streamlit UI.

πŸ“œ Code (chatAgent.py):

# Install dependencies: pip install pydantic requests streamlit ollama

import streamlit as st
from pydantic import BaseModel
import ollama

# 🎭 Meet your new AI buddy!
class AIAgent(BaseModel):
    name: str = "OllamaBot"
    version: str = "1.0"
    description: str = "A chatbot powered by Ollama LLM."

agent = AIAgent()

# πŸ› οΈ Streamlit UI
st.title("πŸ€– iMMSS LLM for Legal Assistance")
st.write("Ask me anything! (Type 'exit' to stop)")

# 🎀 Keep chat history alive!
if "messages" not in st.session_state:
    st.session_state.messages = []

# πŸš€ Show chat history
for msg in st.session_state.messages:
    st.write(msg)

# 🎀 Accept user input
user_query = st.text_input("You:", "")

# 🧠 AI Response Function
def get_ai_response(question: str):
    response = ollama.chat(model="llama3.2", messages=[{"role": "user", "content": question}])
    return response["message"]["content"]

# πŸš€ Processing user input
if user_query:
    if user_query.lower() == "exit":
        st.write("πŸ‘‹ Chatbot: Goodbye! Shutting down...")
        st.stop()

    # Generate response
    ai_answer = get_ai_response(user_query)

    # Save chat history
    st.session_state.messages.append(f"**You:** {user_query}")
    st.session_state.messages.append(f"**{agent.name}:** {ai_answer}")

    # Display AI response
    st.write(f"**{agent.name}:** {ai_answer}")

πŸ’‘ What Does It Do?

  • Listens to you like a good friend (no ghosting).
  • Answers your questions instantly using Llama 3.2.
  • Keeps the conversation going (until you type "exit").
Response for  streamlit run chatAgent.py


πŸ‘‰ Real-Life Use Case: Use it for legal help, customer support, or just for fun chats when your friends are too busy watching Netflix.


πŸš€ Wrapping Up: Why Pydantic AI Agents?

These AI agents make your life easier, more fun, and way more productive by automating tasks, searching the web, and chatting in real time.

πŸ€– What You Can Build Next?

  • AI-powered customer support chatbots.
  • Real-time finance & stock market trackers.
  • Automated legal advisors (because lawyers are expensive).
  • A meme generator (because why not?).

πŸš€ Ready to start? Run the code, break things, and let AI do the boring work while you relax! πŸ˜Ž

Monday, 3 February 2025

React Basics

Let's get your React app up and running! Here's a refined version of your instructions:

1. Install Node.js:

Download and install the latest version of Node.js from nodejs.org. After installation, verify it by opening your command prompt or terminal and running:

Bash
node -v

You should see the installed version (e.g., v18.15.0).

2. Create a Vite React Project:

Use npm to create a new Vite project:

Bash
npm create vite@latest

You'll be prompted with a few choices:

  • Type y and press Enter to proceed.
  • Select the Vite version (e.g., 4.1).
  • Enter your project name (e.g., react-app).
  • Choose React as the framework.
  • Select TypeScript as the variant.

This will create a new directory for your project (e.g., react-app).

3. Navigate to the Project Directory:

Bash
cd react-app

4. Install VS Code (Optional but Recommended):

If you don't have it already, download and install Visual Studio Code from code.visualstudio.com.

5. Install Project Dependencies:

Navigate to your project directory in the terminal (if you're not there already) and install the necessary dependencies:

Bash
npm install

6. Open the Project in VS Code:

Bash
code .

This command opens the project directory in VS Code.

7. Run the Development Server:

Open the terminal within VS Code (View -> Terminal) and start the development server:

Bash
npm run dev

This will start the development server, and you'll see a URL in the terminal, similar to http://localhost:5173/.

8. View the Webpage:

Click on the URL in the terminal to open the webpage in your browser. You should see the default Vite React app.

9. Create a Component (e.g., Message.tsx):

Create a new file named Message.tsx in the src folder of your project. You can then add your React component code to this file. (You didn't include the code you wanted to add, but this gets you to the point where you can add it.) 

TypeScript
// Message.tsx (Pascal Casing for component name)
function Message() {
  // JSX (not JSXML)
  const name = "RMC"; // You can uncomment this line to use the name variable

  if (name) {
    return <h1>Hello {name} World</h1>;
  }
  return <h1>Hello World</h1>;
}

export default Message;


// App.tsx
import Message from './Message';

function App() {
  return (
    <div>
      <Message /> {/* Shorthand for <Message></Message> */}
    </div>
  );
}

export default App;

Explanation of Changes and Best Practices:

  • JSX: The code within the return statement is JSX, not JSXML. JSX is a syntax extension that allows you to write HTML-like code within JavaScript.
  • Pascal Casing: The component name Message follows PascalCase convention (first letter of each word capitalized), which is standard practice for React components.
  • Conditional Rendering: The if (name) block demonstrates conditional rendering. If the name variable has a truthy value (not null, undefined, 0, false, or an empty string), the first <h1> is rendered. Otherwise, the second <h1> is rendered.
  • Shorthand for Self-Closing Tags: <Message></Message> can be shortened to <Message />. This is the preferred way to write self-closing tags in JSX.
  • name variable: I've left the const name = "RMC"; line commented out. You can uncomment it to see the "Hello RMC World" message. If you leave it commented out, it will display "Hello World".
  • Browser Check: After making these changes and saving the files, your browser should automatically update with the new content when the development server is running (npm run dev). If not, you might need to manually refresh the page.




Integrating Bootstrap 5.2.3 into your React Project in VS Code

This blog post will guide you through the process of integrating Bootstrap 5.2.3 into your React project using VS Code. We'll set up Bootstrap, create a simple ListGroup component, and demonstrate how to use Bootstrap classes for styling.

Step 1: Install Bootstrap

Open your terminal window in VS Code and install Bootstrap using npm:

Bash
npm i bootstrap@5.2.3

Step 2: Clean up CSS Files

  • App.css: Delete all content within the App.css file and save it.
  • index.css: Delete all content within the index.css file and save it.

Step 3: Import Bootstrap CSS in main.tsx

Replace the existing import statement in your main.tsx file:

TypeScript
import './index.css' // Remove this

with:

TypeScript
import 'bootstrap/dist/css/bootstrap.css'

Step 4: Create the ListGroup Component

  1. Create a directory named components under the src directory.
  2. Inside the components directory, create a file named ListGroup.tsx.
  3. Initially, add the following content to ListGroup.tsx:
TypeScript
function ListGroup() {
    return <h1>ListGroup</h1>
}
export default ListGroup;

Step 5: Use the ListGroup Component in App.tsx

Edit your App.tsx file and replace its contents with:

TypeScript
import ListGroup from "./components/ListGroup";

function App() {
  return <div><ListGroup /></div>
}

export default App;

Step 6: Populate the ListGroup Component

Replace the contents of ListGroup.tsx with the following code:

TypeScript
function ListGroup() {
  const items = [
    "Chennai",
    "Bombay",
    "New Delhi",
    "Bangalore",
    "Madurai",
    "Calcutta",
  ];

  return (
    <>
      <h1>List</h1>
      <ul className="list-group">
        {items.map((item) => (
          <li className="list-group-item" key={item}>{item}</li> // Added key prop and list-group-item class
        ))}
      </ul>
    </>
  );
}

export default ListGroup;

Key improvements in this version:

  • list-group and list-group-item classes: We've added the necessary Bootstrap classes to style the list and its items.
  • key prop: It's crucial to add a unique key prop to each list item when using map. This helps React efficiently update the list. We're using the item itself as the key in this example, which works as long as the items are unique. In more complex scenarios, you might use an ID or index.

Step 7: Check in the Browser

Open your browser and inspect the rendered list. You should see the list styled with Bootstrap's default list group styles. You can further customize the appearance by adding more Bootstrap classes or custom CSS.

This guide has shown you the basic steps to integrate Bootstrap into a React project and create a styled list component. From here, you can explore Bootstrap's extensive component library and styling options to build more complex and visually appealing user interfaces.

Dockerize Agent -Document Processing

 Since you are using Flask in Agent.py , I will modify the Dockerfile and steps accordingly. [WIP] 1. Update the Dockerfile Create a Do...