Introduction to AI
đ§ Artificial Intelligence (AI) Fundamentals
Artificial Intelligence (AI) encompasses technologies that enable machines to simulate human-like intelligence, performing tasks such as learning, problem-solving, perception, and decision-making. Recent advancements, particularly in generative AI, have made these tools increasingly ubiquitous, allowing for the creation of new content like images, sounds, video, or text.
đĻ The Evolution of AI in Problem Solving
The concept of using AI to assist with problem-solving has evolved significantly, from simple deterministic systems to complex generative models.
đģ The Rubber Duck Debugging Method
A common practice in programming is rubber duck debugging, where programmers verbalize their problems to an inanimate object (like a rubber duck). This process often helps clarify thoughts and leads to self-discovery of solutions.
Purpose: To provide a conversational partner when a human isn't available.
Mechanism: Verbalizing the problem forces a structured thought process, often revealing the solution.
đĨ The CS50 Virtual Duck
CS50 has implemented a virtual rubber duck, initially a simple chat window that responded with quacks. This alone proved effective by encouraging students to articulate their issues.
Early Version: Responded with 1-3 quacks, prompting students to articulate their problem, often leading to self-resolution.
Modern AI Integration (2023): With the advent of large language models (LLMs) like ChatGPT, Claude, and Gemini, the CS50 duck now responds in English.
Pedagogical Goal: To act as a less helpful version of a full AI chatbot, guiding students to solutions rather than providing direct answers, akin to a good teacher or tutor.
đŽ Distinguishing AI from Reality: A Game
The ability of modern AI to generate realistic content makes it challenging for humans to distinguish between AI-generated and real content.
đŧī¸ AI-Generated Images
Example: Two photographs were presented, and the audience was asked to identify the AI-generated one.
Result 1: Most identified the AI image correctly, possibly due to it looking "too good" or "unreal."
Result 2 (Trick Question): Both images were AI-generated, highlighting the advanced capabilities of the technology. Neither face existed in the real world, being synthesized from vast training data.
đ AI-Generated Text
Example: Two essays (SA1 and SA2) were presented, with the task of identifying which was written by a 4th grader and which by an AI chatbot.
SA1: "I'd like to bring a yummy sandwich and a cold juice box for lunch. Sometimes I'll even pack a tasty piece of fruit or a bag of crunchy chips. As we eat, we chat and laugh and catch up on each other's day."
SA2: "My mother packs me a sandwich, a drink, fruit, and a treat. When I get into a lunchroom, I find an empty table and sit there and eat my lunch. My friends come and sit down with me."
Outcome: SA1 was identified as AI, while SA2 was recognized as more typical of a 4th or 5th grader. The phrase "catch up on each other's day" in SA1 was noted as a potential tell-tale sign of AI, being less typical of a young child's vernacular.
Challenge: This game will become increasingly difficult to play as AI generation improves, making discernment nearly impossible.
đ ī¸ The Building Blocks of Modern AI
Modern AI, especially generative AI, is built upon decades of development and recent advances in cloud computing, memory, disk space, and the sheer volume of data available for training.
đī¸ Architecture of the CS50 Duck
The CS50 duck leverages a complex architecture:
Student Interface: Students interact via CS50's programming environment (Visual Studio Code at
CS50.dev).CS50.AI Website: This platform hosts custom code written by CS50 staff.
APIs (Application Programming Interfaces): The CS50 code communicates with third-party services from companies like Microsoft and OpenAI, which provide the core AI models.
Local Customization: CS50 adds its own "sauce" to tailor the AI's responses specifically to CS50 content and pedagogical goals.
đŖī¸ Prompt Engineering
Prompt engineering is the art of asking good, detailed questions and providing context to an AI to elicit desired responses. It involves understanding how to guide the AI effectively.
System Prompt: Instructions written by humans (often in natural language) that define the AI's personality or domain of expertise.
Example for CS50 Duck: "You are a friendly and supportive teaching assistant for CS50. You are also a rubber duck. Answer student questions only about CS50 in the field of computer science. Do not answer questions about unrelated topics. Do not provide full answers to problem sets as this would violate academic honesty. Answer this question:"
This preamble shapes the AI's behavior, ensuring it acts like a helpful, CS50-focused rubber duck.
User Prompt: The specific question or query typed in by the user (student). This is appended to the system prompt.
đ Implementing AI with Python (OpenAI Library)
Basic AI integration can be demonstrated using libraries like OpenAI's API.
Importing Library:
import openaiClient Initialization:
client = openai.OpenAI()User Input:
user_prompt = input("Question: ")System Prompt Definition: A string variable containing the instructions for the AI (e.g.,
system_prompt = "Limit your answer to one sentence. Pretend you're a cat.").Generating Response:
response = client.chat.completions.create( model="gpt-3.5-turbo", # Or another specific model messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt} ] )Printing Output:
print(response.choices[0].message.content)This structure allows developers to define the AI's role and feed it user queries to get context-aware responses.
đ AI for Code Generation: GitHub Copilot
Beyond chatbots, AI can significantly amplify programming capabilities by generating code.
đ¤ GitHub Copilot
GitHub Copilot is an AI-powered coding assistant, similar to tools from Google and Anthropic. It integrates into IDEs like Visual Studio Code.
Functionality:
Provides a chat window for asking coding questions.
Generates suggested code based on context (the open file, comments, function signatures).
Familiar with common programming patterns and public codebases (like CS50's open courseware).
Example: Implementing a Spell Checker in C
Problem: Students typically spend 5-15 hours implementing functions like
checkandloadfor a spell checker using a hash table in C.Copilot's Role: By simply typing "Implement the check function using a hash table in C," Copilot can generate significant portions of the code.
Contextual Awareness: It uses the surrounding code, comments (e.g.,
// This function checks if a word is in the dictionary), and implicit information about function arguments and return types.
Benefits:
Amplifies Programmer Capabilities: Once a programmer understands the basics and has developed "muscle memory," AI can handle the tedious parts, allowing focus on higher-level problem-solving.
Speeds Up Development: Can generate complex code snippets in minutes, drastically reducing implementation time for familiar problems.
Caveats:
Not a Replacement for Understanding: Programmers still need to understand the generated code to troubleshoot, explain, or modify it.
Potential for Errors: AI-generated code might not always be perfect or optimal, requiring human review and debugging.
Academic Honesty: Using such tools for assignments without proper understanding or disclosure can violate academic integrity.
đ§ą AI for Problem Set Solutions: Mario.c
AI can even solve entire programming problems based on natural language descriptions.
Example: Mario.c (Problem Set 1)
Prompt: "Please implement a program in C that prints a left-aligned pyramid of bricks using hash symbols for bricks and use the CS50 library to ask the user for a non-negative height as an integer."
Copilot's Response: Generates the full C code, including:
do-whileloop for height input validation.CS50library inclusion (#include <cs50.h>).Nested loops for printing the pyramid.
Implication: This capability allows for the implementation of "far grander projects" in less time by amplifying the programmer's abilities.
đĄ What is AI? Understanding the Core Concepts
AI involves making computers perform tasks that typically require human intelligence. It's a progression from simple rules to complex learning systems.
đ¯ Early AI Applications
Spam Detection: Automatically filters emails based on patterns identified as spam. This is an early example of supervised learning, where humans initially label data (spam/not spam) to train the system.
Handwriting Recognition: Recognizes handwritten text by being trained on diverse human handwriting styles.
Recommendation Systems (Netflix, etc.): Predicts user preferences (e.g., "If I watched X, I might like Y") based on viewing history and similar users' behaviors.
Voice Assistants (Siri, Alexa): Interprets spoken commands and questions, responding dynamically without exhaustive
if-elsestructures.
đšī¸ AI in Games: From Pong to Tic-Tac-Toe
Early AI was often deterministic, following explicit rules.
Pong
A simple two-player arcade game where paddles bounce a ball.
An AI player (CPU) would follow simple rules to move its paddle.
Breakout
A single-player game where a paddle bounces a ball to break bricks.
Human Instinct: We instinctively know to move the paddle left if the ball goes left.
Algorithmic Approach (Decision Trees):
Is the ball to the left of the paddle?Yes -> Move paddle left.
No -> Is the ball to the right of the paddle?Yes -> Move paddle right.No -> Stay put (paddle is under the ball).
This maps directly to
if-else if-elsestatements in code, demonstrating how simple AI can be.
Tic-Tac-Toe (Noughts and Crosses)
A game where players try to get three in a row.
Simple AI Strategy:
Can I get 3 in a row this turn?Yes -> Play to win.
No -> Can my opponent get 3 in a row next turn?Yes -> Block their move.
No -> What's the optimal move?
Optimal Play: A human playing optimally should never lose tic-tac-toe; at worst, they force a tie. Losing implies suboptimal play.
đ Minimax Algorithm
A strategy used to make optimal decisions in two-player games, minimizing the maximum possible loss for a worst-case scenario.
Scoring System:
O wins: Score = -1 (O wants to minimize score)
X wins: Score = +1 (X wants to maximize score)
Tie: Score = 0
Decision Process: The AI explores all possible future moves (a decision tree) and assigns scores to terminal game states. It then works backward, choosing moves that maximize its score (if it's X's turn) or minimize the opponent's score (if it's O's turn).
Complexity: While simple for a few moves, the number of possible tic-tac-toe games is 255,168. A computer can explore this tree to play optimally.
âī¸ Games with Higher Complexity
Chess: Even the first four moves have 85 billion possibilities.
Go: The first four moves have 266 quintillion possibilities.
Challenge: For such complex games, simply trying all possibilities (like in Minimax for tic-tac-toe) is computationally infeasible due to memory and processing limitations. This is where machine learning becomes essential.
đ§ Machine Learning: Learning from Data
Machine learning involves writing code that doesn't directly solve a problem but enables the computer to learn how to solve it by identifying patterns in vast amounts of data.
đī¸ Reinforcement Learning
A type of machine learning where an agent learns to make decisions by performing actions in an environment to maximize a reward signal.
Human Analogy: We learn through trial and error, getting rewarded for good actions and punished for bad ones.
Pancake Flipping Robot Example:
A human researcher demonstrates pancake flipping to a robot.
The robot then attempts to flip pancakes.
Rewards: Given when the robot successfully flips a pancake (e.g., hitting a key, getting a "digital cookie").
Punishments: Given when the robot fails (e.g., dropping the pancake).
Over 50 trials, the robot improves its movements (quantified as X, Y, Z coordinates) to maximize rewards.
Maze Navigation Example:
A player (yellow dot) navigates a maze to reach an exit (green dot) while avoiding lava pits (punishments).
Exploitation: Initially, the player might randomly explore, getting punished for hitting lava and rewarded for reaching the exit. It learns a path and then exploits that learned path.
Problem with Pure Exploitation: The learned path might not be optimal (e.g., taking too many steps).
Exploration vs. Exploitation: To find better solutions, a balance is needed:
Exploiting: Using existing knowledge (e.g., following a known path that avoids lava).
Exploring: Introducing a small amount of randomness (e.g.,
epsilonvariable, 10% chance of making a random move) to discover potentially better paths or strategies.
Breakout AI Example: An AI playing Breakout initially makes random moves, but through reinforcement learning (rewarded for hitting the ball, punished for missing), it learns to play effectively. It can even discover non-obvious optimal strategies, like breaking through the top row to let the game play itself.
đˇī¸ Supervised Learning
A type of machine learning where the algorithm learns from a labeled dataset, meaning the input data is paired with the correct output.
Spam Detection: Humans manually label emails as "spam" or "not spam," providing the ground truth for the algorithm to learn from.
Challenge: Manual labeling of data is expensive and doesn't scale well for massive datasets (millions or billions of data points).
đ¤ Deep Learning and Neural Networks
A subfield of machine learning that uses neural networks with multiple layers (deep networks) to learn complex patterns from data, often without explicit human labeling.
Inspiration: Biological neurons, which transmit signals.
Abstract Representation:
Neurons: Represented as circles.
Connections (Edges): Represented as lines between neurons, indicating signal flow.
Graph Structure: A network of connected neurons (inputs, hidden layers, outputs).
đ´đĩ Classification Example
Problem: Classify dots as "blue" or "red" based on their X and Y coordinates.
Neural Network (Simplified):
Inputs: X coordinate, Y coordinate.
Output: Prediction (red or blue).
Learning Process:
Initial Guess: The network might start by drawing a simple dividing line (e.g., vertical) to separate blue from red.
Training Data: As more labeled dots (blue/red at specific XY coordinates) are fed to the network, it adjusts its internal parameters.
Parameter Adjustment: The dividing line "pivots" and "squiggles" to better fit the data, becoming a more accurate predictor.
Formula: The dividing line can be represented by a mathematical formula like Ax+By+C=0. The neural network learns the optimal values for A, B, and C (these are the parameters or weights).
Prediction: If Ax+By+C>0, predict blue; otherwise, predict red.
Reality: Real neural networks have billions of neurons and edges, each representing a mathematical value (parameter) learned from vast training data. The internal workings (what each specific neuron or edge weight represents) are often opaque, a phenomenon sometimes called the black box problem.
đŖī¸ Large Language Models (LLMs) and GPTs
Generative Pre-trained Transformers (GPTs) are a type of neural network specifically designed for processing and generating human-like text. They form the basis of tools like ChatGPT.
Training: GPTs are trained on large volumes of textual information (e.g., Reddit posts, Google search results, encyclopedias, Wikipedia).
Core Mechanism: Predicting the most probable next word in a sequence.
Example: "The state's capital is __"
Challenge: Previously, AI struggled with long-distance dependencies and pronoun resolution (e.g., "Massachusetts" and "state" referring to the same entity).
Solution (GPTs):
Tokenization: Breaking sentences into individual words (tokens).
Word Embeddings: Each word is represented as a high-dimensional vector of floating-point numbers (e.g., 1,536 dimensions for "Massachusetts"). This places words in a "virtual N-dimensional space" where semantically similar words are closer.
Attention Mechanism: This is the key innovation. It calculates the relationship between all words in a sentence. "Thicker lines" in a diagram indicate stronger relationships (higher attention) between words (e.g., "Massachusetts" and "state" have high attention). This allows the model to understand context and dependencies across the sentence.
Prediction: Based on these relationships and the learned patterns from training data, the model predicts the most statistically probable next word (e.g., "Boston").
đ Hallucinations
Definition: Instances where an AI generates information that is factually incorrect, nonsensical, or made-up.
Causes:
Misinterpretation of Training Data: The AI might have been trained on unreliable or contradictory information.
Exploration (Randomness): A small degree of randomness in the AI's decision-making process (like the 10% epsilon in reinforcement learning) can sometimes lead to incorrect outputs.
Statistical Nature: LLMs are statistical models; they predict the most probable word, not necessarily the correct one every time.
Impact: Even well-engineered AI, like CS50's duck, can "hallucinate," making it crucial for users to critically evaluate AI-generated content.
"The homework machine, oh, the homework machine, Most perfect contraption that's ever been seen. Just put in your homework, then drop in a dime, Snap on the switch, and in 10 seconds' time, Your homework comes out quick and clean as can be. Here it is, 9 + 4, and the answer is 33? Oh me, I guess it's not as perfect as I thought it would be."
--- Shel Silverstein, The Homework Machine
This poem aptly captures the promise and occasional fallibility of AI, reminding us that while powerful, these tools are not always perfect.

Ask anything
We've read this whole study set, so questions about it get the best answers.