AI-Foundry-Game / app.py
Andbarker's picture
Update app.py
aedcedb verified
Raw History Blame Contribute Delete
9.39 kB
import streamlit as st
import pandas as pd
import numpy as np
# --- CONFIGURATION ---
st.set_page_config(page_title="AI Concept Lab", page_icon="πŸ§ͺ", layout="wide")
# --- STYLING ---
st.markdown("""
<style>
.main-header { font-size: 2.5rem; color: #4F46E5; font-weight: 700; margin-bottom: 1rem; }
.sub-header { font-size: 1.5rem; color: #1F2937; margin-top: 2rem; margin-bottom: 1rem; }
.concept-box { background-color: #F3F4F6; padding: 20px; border-radius: 10px; border-left: 5px solid #4F46E5; margin-bottom: 20px; color: #1f2937}
.simulation-box { background-color: #1e1e1e; color: #e5e7eb; padding: 20px; border-radius: 10px; margin-top: 20px; font-family: 'Courier New', monospace; }
.stButton>button { width: 100%; border-radius: 5px; height: 3em; }
</style>
""", unsafe_allow_html=True)
# --- STATE MANAGEMENT ---
if 'xp' not in st.session_state: st.session_state.xp = 0
if 'completed_modules' not in st.session_state: st.session_state.completed_modules = set()
# --- SIDEBAR CURRICULUM ---
with st.sidebar:
st.title("πŸ§ͺ AI Concept Lab")
st.write(f"**XP Gained:** {st.session_state.xp}")
st.progress(len(st.session_state.completed_modules) / 3)
st.write("---")
st.header("πŸ“š Curriculum")
page = st.radio("Select Module:", [
"1. The Stochastic Parrot (Temperature)",
"2. Meaning in Numbers (Embeddings)",
"3. The Knowledge Bridge (RAG)"
])
st.write("---")
if st.button("Reset Progress"):
st.session_state.xp = 0
st.session_state.completed_modules = set()
st.rerun()
# --- MODULE 1: TEMPERATURE ---
if page == "1. The Stochastic Parrot (Temperature)":
st.markdown('<div class="main-header">Module 1: Controlling Creativity</div>', unsafe_allow_html=True)
st.caption("Reference: *Prompt Engineering for LLMs* / *Building LLMs for Production*")
# 1. THE LESSON
st.markdown("### πŸ“– The Concept")
st.markdown("""
Large Language Models don't just "know" the answer; they predict the next word based on probability.
**Temperature** is a hyperparameter that controls how "risky" the model is when choosing that next word.
* **Low Temperature (0.0 - 0.3):** The model always picks the most likely word. It is precise, deterministic, and boring. Good for coding.
* **High Temperature (0.7 - 1.0+):** The model takes chances on less likely words. It is creative, diverse, but prone to errors (hallucinations).
""")
# 2. THE SIMULATION
st.markdown("### πŸ•ΉοΈ Interactive Simulation")
st.info("Adjust the temperature slider below to see how the AI completes the sentence: **'The sky is...'**")
temp = st.slider("Temperature", 0.0, 1.5, 0.1)
st.markdown('<div class="simulation-box">', unsafe_allow_html=True)
st.write(f"SYSTEM: Generating completion with Temperature = {temp}...")
# Simulated Logic (Deterministic vs Random)
if temp < 0.3:
output = "blue."
explanation = "(The model picked the probability winner: 99%)"
elif temp < 0.7:
output = "filled with scattered clouds drifting slowly."
explanation = "(The model picked a top-5 probability choice)"
elif temp < 1.1:
output = "a canvas of infinite azure, weeping rain."
explanation = "(The model took a risk on lower probability words like 'weeping')"
else:
output = "blue fish guitar singing backwards yesterday."
explanation = "(Complete chaos. The model picked very low probability tokens)"
st.write(f"**OUTPUT:** The sky is {output}")
st.markdown("</div>", unsafe_allow_html=True)
st.caption(explanation)
# 3. KNOWLEDGE CHECK
st.markdown("### βœ… Knowledge Check")
q1 = st.radio("Which temperature should you use for a Code Generation assistant?",
["0.1 (Precise)", "0.7 (Balanced)", "1.2 (Creative)"], index=None)
if st.button("Submit Answer"):
if q1 == "0.1 (Precise)":
st.success("Correct! Code requires precision. You don't want 'creative' syntax errors.")
if "Mod1" not in st.session_state.completed_modules:
st.session_state.xp += 100
st.session_state.completed_modules.add("Mod1")
st.balloons()
else:
st.error("Not quite. High temperature introduces randomness, which breaks code syntax.")
# --- MODULE 2: EMBEDDINGS ---
elif page == "2. Meaning in Numbers (Embeddings)":
st.markdown('<div class="main-header">Module 2: How Machines "Understand" Meaning</div>', unsafe_allow_html=True)
st.caption("Reference: *Hands-On Large Language Models* / *Deep Learning*")
# 1. THE LESSON
st.markdown("### πŸ“– The Concept")
st.markdown("""
Computers cannot understand text. They only understand numbers.
**Vector Embeddings** are lists of numbers (coordinates) that represent the *meaning* of a word.
Imagine a 2D map:
* "King" is close to "Queen".
* "Apple" is far away from "King", but close to "Banana".
When we want to search for something, we don't match keywords; we measure the **distance** between these points.
""")
# 2. THE SIMULATION
st.markdown("### πŸ•ΉοΈ Vector Laboratory")
st.info("See how the math groups related concepts together.")
# Mock Data for Visualization
data = pd.DataFrame({
'word': ['King', 'Queen', 'Prince', 'Apple', 'Banana', 'Cherry', 'Car', 'Truck'],
'x': [1, 1.2, 1.1, 5, 5.2, 5.1, 8, 8.2], # X Coordinate (Theme)
'y': [1, 1.1, 0.9, 5, 4.8, 5.2, 1, 1.2], # Y Coordinate (Sub-theme)
'Category': ['Royalty', 'Royalty', 'Royalty', 'Fruit', 'Fruit', 'Fruit', 'Vehicle', 'Vehicle']
})
st.scatter_chart(data, x='x', y='y', color='Category', size=200)
st.markdown("""
**Observation:** Notice how the "Royalty" words are clustered in the bottom-left, and "Fruit" is in the top-right?
If you search for "Throne", the math looks for points in that bottom-left cluster.
""")
# 3. KNOWLEDGE CHECK
st.markdown("### βœ… Knowledge Check")
q2 = st.selectbox("In vector math, 'King' minus 'Man' plus 'Woman' equals...?",
["Select...", "Prince", "Queen", "Apple"])
if st.button("Submit Answer"):
if q2 == "Queen":
st.success("Correct! This is the most famous example of vector arithmetic preserving semantic relationships.")
if "Mod2" not in st.session_state.completed_modules:
st.session_state.xp += 100
st.session_state.completed_modules.add("Mod2")
st.balloons()
else:
st.error("Try again. Think about the relationship pairs: Man is to Woman as King is to...?")
# --- MODULE 3: RAG ARCHITECTURE ---
elif page == "3. The Knowledge Bridge (RAG)":
st.markdown('<div class="main-header">Module 3: Teaching the AI New Facts</div>', unsafe_allow_html=True)
st.caption("Reference: *AI Engineering* / *Designing Machine Learning Systems*")
# 1. THE LESSON
st.markdown("### πŸ“– The Concept")
st.markdown("""
Standard LLMs are frozen in time (training cut-off). They don't know your private data or recent news.
**RAG (Retrieval Augmented Generation)** fixes this without retraining the model.
1. **Retrieve:** You search your database for relevant text chunks.
2. **Augment:** You paste those chunks into the prompt (context).
3. **Generate:** You tell the LLM "Answer using only the text above."
""")
# 2. THE SIMULATION
st.markdown("### πŸ•ΉοΈ RAG Builder")
st.info("Simulate a RAG pipeline query.")
user_query = st.text_input("User Query:", value="What is the company vacation policy?")
col1, col2 = st.columns(2)
with col1:
st.markdown("**1. Without RAG**")
st.markdown(f"""
> **User:** {user_query}
> **AI:** I don't know which company you are talking about. I only know public information up to 2023.
""")
with col2:
st.markdown("**2. With RAG**")
if st.button("Run Retrieval"):
st.markdown("... *Searching Vector Database* ...")
st.success("Found 1 Document: 'Employee_Handbook.pdf'")
st.code(f"""
PROMPT SENT TO AI:
Context: "Employees are entitled to 20 days of PTO per year."
Question: {user_query}
Answer: Based on the handbook, the policy is 20 days per year.
""")
# 3. KNOWLEDGE CHECK
st.markdown("### βœ… Knowledge Check")
q3 = st.radio("Why is RAG often better than Fine-Tuning for facts?",
["It makes the model smarter generally.", "It allows you to update facts instantly by changing the database.", "It is faster to train."], index=None)
if st.button("Submit Answer"):
if "update facts instantly" in str(q3):
st.success("Correct! If the vacation policy changes tomorrow, you just update the PDF. You don't need to re-train the brain.")
if "Mod3" not in st.session_state.completed_modules:
st.session_state.xp += 100
st.session_state.completed_modules.add("Mod3")
st.balloons()
else:
st.error("No. Fine-tuning is better for 'style' or 'behavior'. RAG is better for 'facts' that change.")