Posts

AI & ML Internship Weekend Assessment

Table of Contents

Section A: AI Fundamentals (20 Marks)

Q1. What is Artificial Intelligence? Explain in your own words. (3 Marks)

Artificial Intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think, learn, reason, and solve problems like humans. Instead of just following rigid, pre-written instructions, an AI system analyzes data, recognizes patterns, and makes autonomous decisions or predictions to achieve specific goals.

Q2. Differentiate between:

a) AI and Machine Learning (2 Marks)

Artificial Intelligence is the broad, overarching umbrella concept of creating smart machines capable of mimicking human behavior.

Machine Learning (ML) is a specific subset of AI that focuses on training algorithms to learn from data and improve their accuracy over time without being explicitly programmed.

b) Machine Learning and Deep Learning (2 Marks)

Machine Learning relies on structured data and often requires manual feature engineering (humans labeling and selecting relevant data points).

Deep Learning is a specialized subfield of ML inspired by the structure of the human brain. It uses multi-layered Artificial Neural Networks to automatically extract features directly from raw data (like raw images or audio).

Q3. What is Generative AI? Give 3 examples. (3 Marks)

Generative AI is a category of AI models designed to create completely new content—such as text, images, code, audio, or video—based on patterns they have learned from training data.

Examples:

  1. ChatGPT / Gemini: For generating text, code, and conversational responses.
  2. Midjourney / DALL-E: For creating realistic or artistic digital images from text prompts.
  3. GitHub Copilot: For autocompleting and generating blocks of programming code.

Q4. Write 5 real-life applications of AI. (5 Marks)

  1. E-commerce Recommendations: Personalized product suggestions on platforms like Amazon or video recommendations on YouTube and Netflix.
  2. Autonomous Vehicles: Self-driving systems and driver-assistance features in cars like Tesla.
  3. Healthcare Diagnostics: Analyzing medical imagery (X-rays, MRIs) to identify tumors or anomalies early.
  4. Virtual Personal Assistants: Voice-activated tools like Apple's Siri, Amazon's Alexa, or Google Assistant.
  5. Financial Fraud Detection: Real-time monitoring of bank transactions to spot anomalous spending patterns and prevent fraud.

Q5. Which AI technology is used in ChatGPT and Gemini? Explain briefly. (5 Marks)

Both ChatGPT and Gemini are built on Large Language Models (LLMs) that utilize the Transformer Architecture.

How it works: The core technology relies on a mechanism called Self-Attention. This allows the model to process words in a sentence simultaneously rather than one by one. It evaluates the context of every word in relation to all other words in a prompt, enabling it to grasp long-range context, nuance, and generate coherent, human-like text responses dynamically.

Key Concept: ChatGPT and Gemini use Transformer-based Large Language Models (LLMs) powered by Self-Attention mechanisms.

Section B: Python Basics (20 Marks)

Q6. What is a variable? Give an example. (2 Marks)

A variable is a named storage location or container in memory used to hold data values that can change during program execution.


# Example
score = 95

Q7. Identify the data type: (4 Marks)


name = "Rahul"        # String (str)
age = 20              # Integer (int)
height = 5.8          # Floating-point number (float)
is_student = True     # Boolean (bool)

Q8. Python program: Welcome Input (3 Marks)


# Take user's name as input
user_name = input("Enter your name: ")

# Display a welcome message
print(f"Welcome to the AI & ML program, {user_name}!")

Q9. Python program: Loop 1 to 10 (3 Marks)


for i in range(1, 11):
    print(i)

Q10. Python program: Square Function (4 Marks)


def square(number):
    return number ** 2

# Example Usage:
# print(square(4)) -> Outputs: 16

Q11. Create and print a List and a Dictionary (4 Marks)


# Create a List
tech_stack = ["Python", "React", "Next.js", "Tailwind"]

# Create a Dictionary
studio_details = {"name": "Pixartual", "focus": "AI & SaaS"}

# Print values
print("List elements:", tech_stack)
print("Dictionary data:", studio_details)

Section C: Chatbot Logic (20 Marks)

Q12. What is a Rule-Based Chatbot? (3 Marks)

A rule-based chatbot is a conversational system that operates on a strict, predefined set of conditions, workflows, or keywords (typically structured using if-else logic). It cannot understand intent or context beyond its explicit hardcoded instructions; if a user types something outside of the preprogrammed rules, the chatbot will fail to understand.

Q13. Explain why String Handling is important in chatbots. (3 Marks)

String handling is vital because all user inputs enter the chatbot as text strings. For a chatbot to interpret phrases correctly, it must normalize the data.

  1. Converting text to lowercase so "Hello", "HELLO", and "hello" trigger the same rule.
  2. Stripping out unnecessary whitespaces or punctuation.
  3. Parsing specific keywords within a sentence to figure out what the user wants.

Q14. What will be the output? (2 Marks)


msg = "HELLO"
print(msg.lower())

Output:


hello

Q15 & Q16. Chatbot with Exit Command (12 Marks Total)


print("Chatbot initialized! Type 'exit' to leave.")

while True:
    # Take input and normalize it by removing spaces and lowercasing
    user_input = input("You: ").strip().lower()

    # Q16: Check for Exit command
    if user_input == 'exit':
        print("Bot: Goodbye! Have a great day.")
        break

    # Q15: Contextual responses
    if user_input == "hello":
        print("Bot: Hey there! How can I help you today?")
    elif user_input == "bye":
        print("Bot: Bye! Talk to you later.")
    elif user_input == "who are you":
        print("Bot: I am a simple rule-based AI assistant.")
    else:
        print("Bot: I don't understand.")

Learning Outcome: This chatbot demonstrates conditional logic, string handling, user interaction, looping, and exit-command implementation using Python.

Section D: APIs & Gemini (20 Marks)

Q17. What is an API? (3 Marks)

An API (Application Programming Interface) is a software intermediary that allows two distinct applications to interact and communicate with each other. It defines a set of protocols, routines, and tools that enable one program to securely request data or services from another system without needing to know how its internal backend is implemented.

Q18. Explain Request and Response with a simple example. (4 Marks)

Request: The message or call sent by the client application to a server asking for data or performing an action.

Response: The payload or status message sent back by the server containing the requested result or an error message.

Real-world Example: Think of ordering food at a restaurant. When you tell the waiter what dish you want, you are making a Request. When the waiter brings out the plate of food from the kitchen to your table, that is the Response.

Simple Analogy Request = Ordering food from a waiter.
Response = Receiving the food from the kitchen.

Q19. What is JSON? (3 Marks)

JSON (JavaScript Object Notation) is a lightweight, text-based format used for storing and transporting data. It is language-independent but completely human-readable, utilizing a structured format of key-value pairs and arrays that mirrors standard dictionary syntax.


{
  "name": "Sagar",
  "role": "Developer"
}

Q20. Explain how Gemini API helps developers build AI applications. (5 Marks)

The Gemini API gives developers instant access to Google's highly advanced foundational models directly inside their custom software. Instead of undergoing the incredibly expensive and resource-intensive task of training a massive neural network from scratch, developers can simply make an API call to leverage features like:

  1. Advanced text generation and contextual conversation.
  2. Multimodal intelligence (processing images, video, and audio simultaneously along with text).
  3. High-efficiency structural reasoning for automation pipelines, coding assistants, and smart search apps.

Q21. Write the steps required to use Gemini API in Python. (5 Marks)

  1. Get an API Key: Sign in to Google AI Studio and generate a secure API access key.
  2. Install the SDK: Run pip install google-genai (or google-generativeai) to install the official Python library.
  3. Configure and Import: Import the package into your script and pass your API key to authenticate the client.
  4. Initialize the Model: Instantiate the desired model version (e.g., gemini-2.5-flash).
  5. Generate Content: Call the content generation method with a prompt string to receive the response text object.

pip install google-genai

Developer Benefit Gemini API enables developers to build AI-powered applications without training large machine learning models from scratch.

Section E: Prompt Engineering (20 Marks)

Q22. What is Prompt Engineering? (3 Marks)

Prompt Engineering is the practice of structured phrasing, structuring, and optimizing textual inputs (prompts) to guide Generative AI models into producing highly accurate, relevant, and correctly formatted outputs while minimizing errors or hallucinations.

Q23. What is Role Prompting? Create one example. (4 Marks)

Role Prompting tells the AI model to assume a specific persona, background profile, or expert identity before answering, which heavily guides its tone, depth, and expertise.

Example:

You are an experienced Senior Cyber Security Architect with 15 years of industry experience. Review the following snippet of backend configuration code and pinpoint any critical security vulnerabilities.

Q24. What is Structured Prompting? Create one example. (4 Marks)

Structured Prompting uses organized layouts, explicit formatting constraints (like markdown or JSON schemas), and distinct sections to ensure the AI responds within uniform boundaries.

Example:

Analyze the following book title. Output your response strictly in the following format:

Title: [Name]
Genre: [Primary Genre]
Core Theme: [One-sentence description]

Q25. Create a StudyBot personality prompt. (4 Marks)


System Prompt:

You are StudyBot, an incredibly friendly and patient programming tutor.

Your sole goal is to help students learn programming languages intuitively.

Break down complex coding paradigms using simple analogies and clean formatting.

Always keep your replies short, clear, and focused under 100 words.

Context: Matches required rules: Friendly, helps learn programming, concise.

Q26. Two prompts for Artificial Intelligence & Comparison (5 Marks)

Basic Prompt:

Tell me about Artificial Intelligence.

Structured Prompt:

Explain Artificial Intelligence. Break your response into exactly two sections:

Definition (Max 2 sentences)
Primary Impact on Software Engineering (Bullet points)

Comparison & Evaluation

The Structured Prompt is significantly better. The basic prompt results in a broad, generic wall of text that varies drastically every execution. The structured prompt forces the model to stay brief, relevant, and delivers immediate readability tailored perfectly to a developer's requirements.

Conclusion Structured prompts provide better control, consistency, readability, and output quality compared to basic prompts.

Bonus Challenge: Multi-Personality AI Assistant Code (25 Extra Marks)

Here is a clean, modular Python application that meets all 6 features—incorporating prompt parameters, clean terminal looping, file logging, and graceful crash protection.

Features Included Conversation History, Command System, Smart Logging, Multiple AI Personalities, Prompt Engineering, and Error Handling.

Complete Source Code

#Multi-Personality AI Assistant - Developed by Sagar Kewat

from google import genai

client = genai.Client(api_key="AQ.Ab.....1A")

bots = {
    "1": """
You are StudyBot.

Role: Programming Tutor

Goal: Help students learn programming.

Rules:
- Explain simply.
- Give examples.
- Keep answers under 100 words.
""",

    "2": """
You are CareerBot.

Role: Career Advisor

Goal: Help users choose careers.

Rules:
- Give practical advice.
- Suggest useful skills.
- Keep answers short and clear.
""",

    "3": """
You are MotivatorBot.

Role: Motivation Coach

Goal: Encourage and inspire users.

Rules:
- Be positive.
- Be supportive.
- Keep answers motivational and short.
""",

    "4": """
You are AI Expert Bot.

Role: AI Specialist

Goal: Teach AI concepts.

Rules:
- Explain clearly.
- Use simple language.
- Give examples.
"""
}

print("Choose Assistant:")
print("1. StudyBot")
print("2. CareerBot")
print("3. MotivatorBot")
print("4. AI Expert Bot")

choice = input("Enter Choice: ")

if choice not in bots:
    print("Invalid Choice")
    exit()

history = []

print("\nCommands: /help /history /clear /exit")

while True:
    try:
        user = input("\nYou: ").strip()

        if not user:
            print("Empty input not allowed")
            continue

        if user == "/help":
            print("/help /history /clear /exit")
            continue

        if user == "/history":
            for msg in history:
                print(msg)
            continue

        if user == "/clear":
            history.clear()
            print("History Cleared")
            continue

        if user == "/exit":
            break

        prompt = bots[choice] + "\nUser: " + user

        response = client.models.generate_content(
            model="gemini-3.5-flash",
            contents=prompt
        )

        ai = response.text

        print("\nBot:", ai)

        history.append("You: " + user)
        history.append("Bot: " + ai)

        with open("chat_history.txt", "a", encoding="utf-8") as f:
            f.write("You: " + user + "\n")
            f.write("Bot: " + ai + "\n\n")

    except Exception as e:
        print("API Error:", e)

print("\n===== Chat History =====")
for msg in history:
    print(msg)

Project Features Summary

Feature Implementation
Conversation History chat_history list
Command System /help, /history, /clear, /exit
Smart Logging chat_history.txt
Prompt Engineering System Prompt Injection
Multiple Personalities StudyBot, CareerBot, MotivatorBot, AI Expert Bot
Error Handling Input, API, Runtime, KeyboardInterrupt
Note Replace the simulated response block with Gemini API integration to convert this assessment project into a real AI-powered assistant.

Post a Comment