From 7b6506ddf63ef6ce66e1323ab7936523b16ebbdf Mon Sep 17 00:00:00 2001 From: Jonas Thamane <166150947+NathiJonas@users.noreply.github.com> Date: Mon, 9 Mar 2026 00:36:08 +0200 Subject: [PATCH 1/2] Create Jonas Thamane Week 8 PR.ipynb --- .../Jonas Thamane Week 8 PR.ipynb | 856 ++++++++++++++++++ 1 file changed, 856 insertions(+) create mode 100644 community-contributions/Jonas Thamane Week 8 PR.ipynb diff --git a/community-contributions/Jonas Thamane Week 8 PR.ipynb b/community-contributions/Jonas Thamane Week 8 PR.ipynb new file mode 100644 index 0000000000..e6d0a8f122 --- /dev/null +++ b/community-contributions/Jonas Thamane Week 8 PR.ipynb @@ -0,0 +1,856 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "c388efcc", + "metadata": {}, + "source": [ + "## 1 — Install Dependencies" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "8fbcd155", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "\n", + "[notice] A new release of pip is available: 24.0 -> 26.0.1\n", + "[notice] To update, run: c:\\Users\\Lenovo\\projects\\llm_engineering\\.venv\\Scripts\\python.exe -m pip install --upgrade pip\n" + ] + } + ], + "source": [ + "import sys\n", + "!{sys.executable} -m pip install -q anthropic chromadb sentence-transformers python-dotenv gradio" + ] + }, + { + "cell_type": "markdown", + "id": "dfeffb61", + "metadata": {}, + "source": [ + "## 2 — Imports & Anthropic Client" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1879a0ee", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "✅ Anthropic client ready\n", + " Fast model : claude-haiku-4-5-20251001\n", + " Smart model : claude-sonnet-4-6\n" + ] + } + ], + "source": [ + "import os\n", + "import textwrap\n", + "from pathlib import Path\n", + "from dotenv import load_dotenv\n", + "import anthropic\n", + "import chromadb\n", + "import gradio as gr\n", + "from tqdm import tqdm\n", + "from sentence_transformers import SentenceTransformer\n", + "\n", + "load_dotenv(override=True)\n", + "\n", + "ANTHROPIC_KEY = os.getenv(\"ANTHROPIC_API_KEY\", \"\")\n", + "if not ANTHROPIC_KEY:\n", + " raise ValueError(\"Set ANTHROPIC_API_KEY in a .env file or environment variable\")\n", + "\n", + "\n", + "FAST_MODEL = \"claude-haiku-4-5-20251001\"\n", + "SMART_MODEL = \"claude-sonnet-4-6\"\n", + "\n", + "claude = anthropic.Anthropic(api_key=ANTHROPIC_KEY)\n", + "print(f\"✅ Anthropic client ready\")\n", + "print(f\" Fast model : {FAST_MODEL}\")\n", + "print(f\" Smart model : {SMART_MODEL}\")" + ] + }, + { + "cell_type": "markdown", + "id": "1578e6c8", + "metadata": {}, + "source": [ + "## 3 — Build the SA Car Knowledge Base\n", + "\n", + "Reads `sa_cars.txt` line by line. \n", + "If the file doesn't exist, a rich sample dataset is created automatically." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "4493f415", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "✅ Created sample knowledge base: sa_cars.txt (120 facts)\n" + ] + } + ], + "source": [ + "SAMPLE_KNOWLEDGE = \"\"\"\n", + "Toyota Hilux is the best-selling vehicle in South Africa and is ideal for gravel and farm roads.\n", + "Toyota Fortuner is a popular family SUV in South Africa known for reliability and resale value.\n", + "Volkswagen Polo is the top-selling passenger car in South Africa, valued for fuel efficiency.\n", + "Ford Ranger is a leading double-cab bakkie popular with both urban and rural South African drivers.\n", + "Suzuki Swift and Baleno are highly affordable city cars in South Africa with low running costs.\n", + "Hyundai and Kia offer competitive warranties of up to 5 years in South Africa, reducing ownership risk.\n", + "South African petrol prices are regulated and updated on the first Wednesday of every month.\n", + "93 octane unleaded petrol is the standard fuel grade used inland (Gauteng, Limpopo, Mpumalanga).\n", + "95 octane unleaded petrol is required at coastal regions (Western Cape, KwaZulu-Natal, Eastern Cape).\n", + "Diesel vehicles are popular in South Africa for long-distance travel due to lower fuel costs per km.\n", + "South Africa has some of the highest vehicle insurance premiums in Africa due to high theft rates.\n", + "The Western Cape has the best-maintained road infrastructure in South Africa.\n", + "Gauteng has the highest concentration of highways and toll roads in South Africa.\n", + "Limpopo and Mpumalanga have many unpaved roads requiring higher ground clearance vehicles.\n", + "Load shedding (loadshedding) has driven interest in electric vehicles with home charging in South Africa.\n", + "Electric vehicles (EVs) are still niche in South Africa due to limited public charging infrastructure.\n", + "The NAAMSA vehicle registration data shows bakkies (pickup trucks) account for over 25% of SA new car sales.\n", + "South African consumers prefer automatic transmissions increasingly due to urban traffic congestion.\n", + "CarTrack and Matrix are leading vehicle tracking providers used in South Africa to reduce theft risk.\n", + "Vehicle financing through WesBank, Absa, and Standard Bank is common in South Africa.\n", + "The AA (Automobile Association of South Africa) recommends servicing every 15,000 km or annually.\n", + "Toyota and Volkswagen dominate the South African new car market with the highest dealer networks.\n", + "Second-hand car values in South Africa depreciate steeply in the first 3 years of ownership.\n", + "Tyre wear is accelerated on South African roads due to potholes and extreme summer heat.\n", + "Catalytic converter theft is a major problem in South Africa, particularly affecting SUVs and bakkies.\n", + "Smash-and-grab incidents at traffic lights are common in Johannesburg and Cape Town CBD areas.\n", + "Suzuki has the lowest cost of ownership among small cars sold in South Africa according to AA data.\n", + "Buying a certified pre-owned (CPO) vehicle from a dealership provides warranty protection in South Africa.\n", + "Private vehicle sales through AutoTrader SA are common and often 10-20% cheaper than dealers.\n", + "Vehicle roadworthiness testing (roadworthy certificate) is required for ownership transfer in South Africa.\n", + "South Africa drives on the left side of the road, same as the UK, Australia, and most of Africa.\n", + "The N1, N2, and N3 are South Africa's busiest national highways connecting major cities.\n", + "Bakkie (pickup truck) ownership is a cultural status symbol in many South African communities.\n", + "Turbocharged engines are increasingly common in South Africa for better fuel economy under load.\n", + "Annual licensing fees in South Africa vary by province and vehicle mass, costing R500-R2000 per year.\n", + "The South African Rand's weakness makes imported vehicles significantly more expensive than locally assembled ones.\n", + "Volkswagen, BMW, and Ford have local assembly plants in South Africa, reducing their vehicle prices.\n", + "Mercedes-Benz C-Class is assembled in East London, South Africa, making it competitively priced locally.\n", + "WBHO and other construction companies prefer Toyota Land Cruiser for remote South African project sites.\n", + "Minibus taxis (Toyota Quantum/HiAce) dominate South African public transport and are high-volume sellers.\n", + "Spare parts availability is best for Toyota, VW, and Ford in South Africa due to dealer network size.\n", + "Flooding in KwaZulu-Natal has highlighted the need for higher ground clearance in coastal SA provinces.\n", + "South African highways have a general speed limit of 120 km/h, with urban limits of 60 km/h.\n", + "Drunk driving is a significant road safety problem in South Africa with strict legal blood alcohol limits.\n", + "Visibility cameras and dashcams are increasingly popular in South Africa for insurance claim evidence.\n", + "The Gauteng freeway improvement project (GFIP) toll roads use e-tag systems for electronic billing.\n", + "Fuel-efficient hybrid vehicles like Toyota Corolla Cross hybrid are growing in popularity in South Africa.\n", + "South African summer temperatures can exceed 40°C, stressing cooling systems and tyre pressure management.\n", + "\"Sandton school run\" traffic makes large SUVs like Fortuner and Prado popular in Johannesburg northern suburbs.\n", + "Cape Town's mountainous terrain makes hill-start assist and strong brakes essential features for residents.\n", + "\n", + "Isuzu D-Max is a popular workhorse bakkie in South Africa used heavily in agriculture and mining sectors.\n", + "Nissan Navara offers a comfortable ride for a bakkie and is popular for mixed urban and off-road use in South Africa.\n", + "Mitsubishi Triton is a budget-friendly double-cab bakkie option in South Africa with solid off-road capability.\n", + "GWM (Great Wall Motors) P-Series bakkie has gained popularity in South Africa for its affordability and features.\n", + "Haval SUVs from GWM are rapidly growing market share in South Africa as affordable Chinese alternatives to Japanese brands.\n", + "Chery Tiggo and Omoda models are entering the South African market offering competitive pricing against Korean brands.\n", + "BYD electric vehicles are officially launched in South Africa making EVs more accessible at lower price points.\n", + "The Volvo EX30 and EX40 are the most popular premium electric SUVs available in South Africa.\n", + "South Africa's Joburg to Cape Town N1 highway (1,400 km) is one of the most-driven long-distance routes in the country.\n", + "The Garden Route along the N2 in the Western Cape is a scenic but challenging coastal drive with sharp bends.\n", + "Fog on the Huguenot Tunnel and Du Toitskloof Pass in the Western Cape requires extra caution and good headlights.\n", + "The Sani Pass in KwaZulu-Natal is a famous 4x4-only route requiring low-range 4WD and high ground clearance.\n", + "Off-road trails like Lesotho Highlands and Kruger bushveld tracks demand skid plates and all-terrain tyres.\n", + "Suspension upgrades are commonly fitted to bakkies in South Africa to handle corrugated gravel farm roads.\n", + "A canopy (tonneau cover) is a popular bakkie accessory in South Africa for security and load protection.\n", + "Tow bars are a common fitting on South African bakkies for trailers, caravans, and horse boxes.\n", + "Caravan and camping culture is strong in South Africa making towing capacity a key purchase consideration.\n", + "The Jurgens and Sprite caravan brands are popular in South Africa and compatible with most large bakkies and SUVs.\n", + "Game reserve driving in Limpopo and Mpumalanga exposes vehicles to dust, sand, and acacia thorns requiring robust tyres.\n", + "Spare wheel carriers and high-lift jacks are recommended accessories for South African bush driving.\n", + "Run-flat tyres are increasingly specified on luxury German cars sold in South Africa to reduce roadside vulnerability.\n", + "Pirelli, Bridgestone, and Goodyear are the most widely available tyre brands in South Africa.\n", + "Nitrogen tyre inflation is available at many South African fuel stations and reduces pressure variation in extreme heat.\n", + "Wheel and tyre theft from parked vehicles is a growing problem in South African townships and suburbs.\n", + "Locking wheel nuts are recommended as a basic security measure for all South African vehicles.\n", + "Ghost immobilisers are fitted by many South African vehicle owners to prevent relay key theft on keyless entry cars.\n", + "Comprehensive car insurance in South Africa typically costs 1-2% of the vehicle value per month.\n", + "Third-party only insurance is a legal minimum in South Africa and is common for older, lower-value vehicles.\n", + "OUTsurance, Santam, Discovery Insure, and Hollard are leading car insurance providers in South Africa.\n", + "Discovery Insure offers behaviour-based insurance discounts through the Vitality Drive programme in South Africa.\n", + "Tracker device installation is often required by South African insurers as a condition of comprehensive cover.\n", + "The SA Police Service (SAPS) registers over 60,000 vehicle thefts annually making security a top ownership priority.\n", + "Gauteng accounts for the highest number of vehicle hijackings in South Africa, particularly in southern Johannesburg.\n", + "Vehicle hijacking hotspots in South Africa include robot (traffic light) stops, driveways, and parking lots.\n", + "Armed response vehicle protection and private security estates are popular in South Africa for high-value car owners.\n", + "Parking in well-lit, guarded areas is strongly recommended for all vehicles in South African cities after dark.\n", + "South African law requires all vehicles to carry a valid licence disc displayed on the windscreen.\n", + "Traffic fines in South Africa can be issued for speeding, no seatbelts, using a mobile phone while driving, and rolling stops.\n", + "The AARTO demerit system in South Africa can result in licence suspension for repeat traffic offenders.\n", + "South African roads have a high incidence of pedestrians, livestock, and potholes requiring constant vigilance.\n", + "Livestock on roads is a major hazard particularly at night in the Eastern Cape, Northern Cape, and Free State.\n", + "Night driving in rural South Africa is strongly discouraged due to unlit pedestrians, animals, and abandoned vehicles.\n", + "High-beam headlights and a bull bar are recommended for rural night driving in South Africa.\n", + "South African National Parks charge entrance fees for Kruger, Addo, and other parks requiring a valid vehicle licence.\n", + "The South African school holiday seasons (December, Easter, June/July) cause extreme traffic on N1, N2, and N3.\n", + "AA Emergency Service provides roadside assistance including towing, battery jump-start, and flat tyre help across South Africa.\n", + "Budget Car Rental, Avis, and Europcar are major car hire companies operating at all South African airports.\n", + "South African hire car companies often restrict vehicles from crossing borders into neighbouring countries without prior approval.\n", + "Petrol station density is low in the Northern Cape and Free State requiring careful fuel planning on long trips.\n", + "Many South African petrol stations do not accept foreign credit cards and cash may be required in rural areas.\n", + "The Drive.co.za and WeBuyCars platforms are popular for buying and selling used vehicles in South Africa.\n", + "WeBuyCars operates physical inspection centres across South Africa providing instant cash offers for used vehicles.\n", + "AutoTrader South Africa lists over 60,000 used vehicles at any given time making it the largest local classifieds platform.\n", + "Dealerships in South Africa are regulated by the Motor Industry Ombudsman of South Africa (MIOSA) for dispute resolution.\n", + "Service plans and maintenance plans sold with new South African vehicles cover scheduled services for 3-5 years.\n", + "Extended warranties are available from South African dealerships and third parties like Motorite and Warrantywise.\n", + "Fitment centres like Tiger Wheel & Tyre and Hi-Q are national chains offering tyre, brake, and suspension services in South Africa.\n", + "Midas and Repco auto parts stores are the most widely available spare parts retailers across South Africa.\n", + "SMMEs and small businesses in South Africa commonly use the Toyota Quantum panel van for goods delivery.\n", + "Rideshare services Bolt and Uber operate in major South African cities and use Toyota Etios, Polo, and similar models.\n", + "South African taxis (metered cabs) are different from minibus taxis and operate in CBD areas of major cities.\n", + "The South African government offers a customs duty rebate on electric vehicles to encourage EV adoption.\n", + "Solar panel home charging systems for EVs are growing in South Africa as a load-shedding workaround for EV owners.\n", + "BMW i3 and i4 are popular urban EVs in South Africa used in Johannesburg and Cape Town where charging infrastructure is better.\n", + "Nissan Leaf is the most affordable used electric car available in South Africa with good inner-city range.\n", + "The MIDC (Motor Industry Development Council) supports the local assembly of vehicles and components in South Africa.\n", + "Ford Silverton plant in Pretoria assembles the Ford Ranger locally reducing its price versus fully imported competitors.\n", + "Toyota Prospecton plant in KwaZulu-Natal assembles the Hilux and Fortuner making them more competitively priced in South Africa.\n", + "BMW Rosslyn plant near Pretoria assembles the BMW 3 Series locally for both the SA market and export.\n", + "\"\"\".strip()\n", + "\n", + "\n", + "kb_path = Path(\"sa_cars.txt\")\n", + "if not kb_path.exists():\n", + " kb_path.write_text(SAMPLE_KNOWLEDGE, encoding=\"utf-8\")\n", + " print(f\"✅ Created sample knowledge base: {kb_path} ({len(SAMPLE_KNOWLEDGE.splitlines())} facts)\")\n", + "else:\n", + " print(f\"✅ Found existing knowledge base: {kb_path}\")" + ] + }, + { + "cell_type": "markdown", + "id": "cdded995", + "metadata": {}, + "source": [ + "## 4 — Create the ChromaDB Vector Store (RAG)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e1ada3f7", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Loading embedding model...\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "c:\\Users\\Lenovo\\projects\\llm_engineering\\.venv\\Lib\\site-packages\\huggingface_hub\\file_download.py:129: UserWarning: `huggingface_hub` cache-system uses symlinks by default to efficiently store duplicated files but your machine does not support them in C:\\Users\\Lenovo\\.cache\\huggingface\\hub\\models--sentence-transformers--all-MiniLM-L6-v2. Caching files will still work but in a degraded version that might require more space on your disk. This warning can be disabled by setting the `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For more details, see https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations.\n", + "To support symlinks on Windows, you either need to activate Developer Mode or to run Python as an administrator. In order to activate developer mode, see this article: https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development\n", + " warnings.warn(message)\n", + "Loading weights: 100%|██████████| 103/103 [00:00<00:00, 4217.89it/s]\n", + "\u001b[1mBertModel LOAD REPORT\u001b[0m from: sentence-transformers/all-MiniLM-L6-v2\n", + "Key | Status | | \n", + "------------------------+------------+--+-\n", + "embeddings.position_ids | UNEXPECTED | | \n", + "\n", + "\u001b[3mNotes:\n", + "- UNEXPECTED\u001b[3m\t:can be ignored when loading from different task/architecture; not ok if you expect identical arch.\u001b[0m\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "✅ Embedding model ready\n", + "✅ Vector store ready — 119 facts indexed\n" + ] + } + ], + "source": [ + "\n", + "print(\"Loading embedding model...\")\n", + "embed_model = SentenceTransformer(\"all-MiniLM-L6-v2\")\n", + "print(\"✅ Embedding model ready\")\n", + "\n", + "\n", + "chroma_client = chromadb.PersistentClient(path=\"sa_cars_db\")\n", + "\n", + "\n", + "try:\n", + " chroma_client.delete_collection(\"sa_cars\")\n", + "except Exception:\n", + " pass\n", + "\n", + "collection = chroma_client.get_or_create_collection(\"sa_cars\")\n", + "\n", + "\n", + "with open(\"sa_cars.txt\", encoding=\"utf-8\") as f:\n", + " facts = [line.strip() for line in f.readlines() if line.strip()]\n", + "\n", + "for i, fact in enumerate(facts):\n", + " embedding = embed_model.encode(fact).tolist()\n", + " collection.add(\n", + " documents=[fact],\n", + " embeddings=[embedding],\n", + " ids=[str(i)]\n", + " )\n", + "\n", + "print(f\"✅ Vector store ready — {collection.count()} facts indexed\")" + ] + }, + { + "cell_type": "markdown", + "id": "6bc06ca5", + "metadata": {}, + "source": [ + "## 5 — RAG Retrieval Function" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "5eed173a", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Test retrieval for 'best bakkie for farm roads':\n", + "Suspension upgrades are commonly fitted to bakkies in South Africa to handle corrugated gravel farm roads.\n", + "Nissan Navara offers a comfortable ride for a bakkie and is popular for mixed urban and off-road use in South Africa.\n", + "Bakkie (pickup truck) ownership is a cultural status symbol in many South African communities.\n", + "GWM (Great Wall Motors) P-Series bakkie has gained popularity in South Africa for its affordability and features.\n", + "Isuzu D-Max is a popular workhorse bakkie in South Africa used heavily in agriculture and mining sectors.\n", + "Mitsubishi Triton is a budget-friendly double-cab bakkie option in South Africa with solid off-road capability.\n" + ] + } + ], + "source": [ + "def retrieve_facts(query: str, n_results: int = 6) -> str:\n", + " \"\"\"\n", + " Embed the query and retrieve the top-n most relevant facts\n", + " from the SA car knowledge base.\n", + " \"\"\"\n", + " embedding = embed_model.encode(query).tolist()\n", + " results = collection.query(\n", + " query_embeddings=[embedding],\n", + " n_results=n_results\n", + " )\n", + " return \"\\n\".join(results[\"documents\"][0])\n", + "\n", + "\n", + "# Quick test\n", + "print(\"Test retrieval for 'best bakkie for farm roads':\")\n", + "print(retrieve_facts(\"best bakkie for farm roads\"))" + ] + }, + { + "cell_type": "markdown", + "id": "22fbc52d", + "metadata": {}, + "source": [ + "## 6 — Agent Definitions\n", + "\n", + "Four specialised agents mirror the original notebook's pipeline:\n", + "\n", + "| SA Car Equivalent |\n", + " | **Car Safety Agent** — suitability for SA roads & conditions |\n", + "| **SA Market Agent** — specific local models, prices, dealers |\n", + "| **Ownership Cost Agent** — fuel, insurance, maintenance |\n", + "| Diet Recommendation Agent | **Final Recommendation Agent** — full advice report |" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d65787ee", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "✅ All four agents defined\n" + ] + } + ], + "source": [ + "def llm(prompt: str, model: str = FAST_MODEL) -> str:\n", + " \"\"\"Simple Claude call — returns the text response.\"\"\"\n", + " response = claude.messages.create(\n", + " model=model,\n", + " max_tokens=1024,\n", + " messages=[{\"role\": \"user\", \"content\": prompt}]\n", + " )\n", + " return response.content[0].text.strip()\n", + "\n", + "\n", + "\n", + "def car_safety_agent(query: str) -> str:\n", + " \"\"\"\n", + " Uses RAG to retrieve relevant SA car facts, then assesses\n", + " which vehicles and features are safe/suitable for the user's needs.\n", + " Mirrors: food_safety_agent()\n", + " \"\"\"\n", + " context = retrieve_facts(query)\n", + "\n", + " prompt = f\"\"\"\n", + "You are a South African automotive safety and road conditions expert.\n", + "\n", + "South African car and road knowledge:\n", + "{context}\n", + "\n", + "User question:\n", + "{query}\n", + "\n", + "Based on the knowledge above, return:\n", + "- Vehicles / features WELL SUITED to South African conditions for this need\n", + "- Vehicles / features to AVOID for this need\n", + "- Key South African road or safety considerations relevant to the question\n", + "\"\"\"\n", + " return llm(prompt)\n", + "\n", + "\n", + "\n", + "def sa_market_agent(safety_advice: str) -> str:\n", + " \"\"\"\n", + " Suggests specific South African car models available locally,\n", + " with approximate pricing in ZAR.\n", + " Mirrors: nigerian_food_agent()\n", + " \"\"\"\n", + " prompt = f\"\"\"\n", + "You are a South African car dealership expert with knowledge of the local market.\n", + "\n", + "Based on this road safety and suitability advice:\n", + "{safety_advice}\n", + "\n", + "Suggest specific South African car models for these three budgets:\n", + "\n", + "Budget (under R300,000)\n", + "Mid-range (R300,000 – R600,000)\n", + "Premium (above R600,000)\n", + "\n", + "For each suggestion include:\n", + "- Model name and variant\n", + "- Approximate new price in ZAR\n", + "- One key reason it suits the user's needs in South Africa\n", + "\"\"\"\n", + " return llm(prompt)\n", + "\n", + "\n", + "\n", + "def ownership_cost_agent(market_advice: str) -> str:\n", + " \"\"\"\n", + " Explains the true cost of owning each recommended car in South Africa —\n", + " fuel, insurance, maintenance, licensing.\n", + " Mirrors: nutrition_reasoning_agent()\n", + " \"\"\"\n", + " prompt = f\"\"\"\n", + "You are a South African personal finance and motoring cost expert.\n", + "\n", + "Analyse the true monthly and annual cost of owning these recommended vehicles in South Africa:\n", + "\n", + "{market_advice}\n", + "\n", + "For each vehicle cover:\n", + "- Estimated monthly fuel cost (assume 1,500 km/month at current SA fuel prices)\n", + "- Typical comprehensive insurance premium range (ZAR/month)\n", + "- Service plan / maintenance cost\n", + "- Annual licensing fee (approximate)\n", + "- Overall value-for-money verdict for a South African buyer\n", + "\"\"\"\n", + " return llm(prompt)\n", + "\n", + "\n", + "\n", + "def final_recommendation_agent(query: str, safety: str, market: str, costs: str) -> str:\n", + " \"\"\"\n", + " Synthesises all three agents into a single, actionable recommendation report.\n", + " Uses the smarter model for the final output.\n", + " Mirrors: diet_recommendation()\n", + " \"\"\"\n", + " prompt = f\"\"\"\n", + "You are a trusted South African motoring advisor writing a final recommendation report.\n", + "\n", + "Original user question:\n", + "{query}\n", + "\n", + "Road Safety & Suitability Analysis:\n", + "{safety}\n", + "\n", + "South African Market Options:\n", + "{market}\n", + "\n", + "Ownership Cost Analysis:\n", + "{costs}\n", + "\n", + "Write a clear, friendly, well-structured final car recommendation report for a South African buyer.\n", + "Use markdown formatting with headers and bullet points.\n", + "End with one single TOP PICK recommendation and a one-sentence reason why.\n", + "\"\"\"\n", + " return llm(prompt, model=SMART_MODEL)\n", + "\n", + "\n", + "print(\"✅ All four agents defined\")" + ] + }, + { + "cell_type": "markdown", + "id": "1f54e421", + "metadata": {}, + "source": [ + "## 7 — Pipeline Orchestrator" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "420cca41", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "✅ Pipeline orchestrator ready\n" + ] + } + ], + "source": [ + "def car_recommendation(query: str) -> str:\n", + " \"\"\"\n", + " Full multi-agent pipeline — mirrors diet_recommendation() from the original.\n", + "\n", + " 1. Car Safety Agent → RAG-backed road & vehicle suitability\n", + " 2. SA Market Agent → local models & ZAR pricing\n", + " 3. Ownership Cost Agent → fuel, insurance, maintenance\n", + " 4. Final Recommendation → synthesised markdown report\n", + " \"\"\"\n", + " print(\"[1/4] Running Car Safety Agent...\")\n", + " safety = car_safety_agent(query)\n", + "\n", + " print(\"[2/4] Running SA Market Agent...\")\n", + " market = sa_market_agent(safety)\n", + "\n", + " print(\"[3/4] Running Ownership Cost Agent...\")\n", + " costs = ownership_cost_agent(market)\n", + "\n", + " print(\"[4/4] Running Final Recommendation Agent...\")\n", + " report = final_recommendation_agent(query, safety, market, costs)\n", + "\n", + " return f\"\"\"## 🚗 SA CAR RECOMMENDATION REPORT\n", + "\n", + "---\n", + "\n", + "### Road Safety & Suitability\n", + "{safety}\n", + "\n", + "---\n", + "\n", + "### South African Market Options\n", + "{market}\n", + "\n", + "---\n", + "\n", + "### Ownership Cost Analysis\n", + "{costs}\n", + "\n", + "---\n", + "\n", + "### ✅ Final Recommendation\n", + "{report}\n", + "\"\"\"\n", + "\n", + "\n", + "print(\"✅ Pipeline orchestrator ready\")" + ] + }, + { + "cell_type": "markdown", + "id": "7eff4cad", + "metadata": {}, + "source": [ + "## 8 — Quick Smoke Test" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0bfbea50", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Testing Car Safety Agent...\n", + "\n", + "# Vehicle Recommendations for Johannesburg Family Car (School Runs + Highway)\n", + "\n", + "## ✅ WELL SUITED TO YOUR NEEDS\n", + "\n", + "**Vehicle Types:**\n", + "- **Large SUVs** (Toyota Fortuner, Toyota Prado, similar) - ideal for Sandton school run traffic and highway comfort; popular choice in northern Johannesburg suburbs for good reason\n", + "- **Diesel vehicles** - excellent for highway driving with better fuel economy per km on long distances\n", + "- **Reliable mid-range family sedans/SUVs** with good safety ratings\n", + "\n", + "**Key Features to Prioritize:**\n", + "- Higher ground clearance and visibility (advantages in mixed traffic conditions)\n", + "- Proven reliability and local service network\n", + "- Good fuel efficiency for highway use\n", + "- Adequate space for school run duties\n", + "\n", + "## ❌ AVOID FOR THIS NEED\n", + "\n", + "- Nissan Leaf or electric vehicles - limited highway range unsuitable for longer trips\n", + "- Suzuki Swift/Baleno - too small for family comfort on highways; better for inner-city only\n", + "- Vehicles with poor local service support\n", + "\n", + "## 🚨 KEY SA ROAD & SAFETY CONSIDERATIONS\n", + "\n", + "- **School run traffic:** Congestion in northern suburbs requires vehicle with good visibility and maneuverability\n", + "- **Highway safety:** Ensure vehicle has modern safety features; long distances demand reliable brakes and stability control\n", + "- **Security:** Consider vehicles compatible with armed response/tracking systems (popular in JNB for high-value cars)\n", + "- **Fuel costs:** Diesel advantage significant for regular highway commuting\n", + "- **Buying platforms:** Check Drive.co.za and WeBuyCars for reliable used options with service history\n", + "\n", + "**Recommendation:** A used diesel SUV (Fortuner/Prado class) balances all requirements - school run capability, highway comfort, and long-distance fuel efficiency.\n" + ] + } + ], + "source": [ + "\n", + "test_query = \"I live in Johannesburg and need a reliable family car for school runs and highway driving\"\n", + "print(\"Testing Car Safety Agent...\\n\")\n", + "print(car_safety_agent(test_query))" + ] + }, + { + "cell_type": "markdown", + "id": "5f406fca", + "metadata": {}, + "source": [ + "## 9 — Gradio UI" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f7127f68", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\Lenovo\\AppData\\Local\\Temp\\ipykernel_14436\\2833195560.py:25: UserWarning: The parameters have been moved from the Blocks constructor to the launch() method in Gradio 6.0: theme. Please pass these parameters to launch() instead.\n", + " with gr.Blocks(theme=THEME, title=\"SA Car Advisor\") as ui:\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "* Running on local URL: http://0.0.0.0:7860\n", + "* To create a public link, set `share=True` in `launch()`.\n" + ] + }, + { + "data": { + "text/html": [ + "
" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1/4] Running Car Safety Agent...\n", + "[2/4] Running SA Market Agent...\n", + "[3/4] Running Ownership Cost Agent...\n", + "[4/4] Running Final Recommendation Agent...\n" + ] + } + ], + "source": [ + "THEME = gr.themes.Base(\n", + " primary_hue=\"green\",\n", + " secondary_hue=\"emerald\",\n", + " neutral_hue=\"slate\",\n", + " font=[gr.themes.GoogleFont(\"Inter\"), \"ui-sans-serif\", \"sans-serif\"],\n", + ").set(\n", + " body_background_fill=\"#0d1117\",\n", + " body_text_color=\"#e2e0f0\",\n", + " block_background_fill=\"#161b22\",\n", + " block_border_color=\"#30363d\",\n", + " block_title_text_color=\"#4ade80\",\n", + " input_background_fill=\"#0d1117\",\n", + " button_primary_background_fill=\"linear-gradient(135deg, #16a34a, #15803d)\",\n", + " button_primary_text_color=\"#fff\",\n", + ")\n", + "\n", + "\n", + "def run(query: str) -> str:\n", + " \"\"\"Gradio entry point — wraps the pipeline.\"\"\"\n", + " if not query or not query.strip():\n", + " return \"⚠️ Please enter a question about buying or owning a car in South Africa.\"\n", + " return car_recommendation(query)\n", + "\n", + "\n", + "with gr.Blocks(theme=THEME, title=\"SA Car Advisor\") as ui:\n", + "\n", + " gr.HTML(\"\"\"\n", + "
\n", + "

\n", + " 🚗 South African Car Advisor\n", + "

\n", + "

\n", + " Multi-agent RAG system · Powered by Anthropic Claude\n", + "

\n", + "
\n", + " \"\"\")\n", + "\n", + " with gr.Tabs():\n", + "\n", + " \n", + " with gr.Tab(\"🔍 Get Advice\"):\n", + " gr.Markdown(\n", + " \"Ask anything about buying, owning, or choosing a car in South Africa. \"\n", + " \"The system runs four specialist AI agents to build your personalised report.\"\n", + " )\n", + "\n", + " query_box = gr.Textbox(\n", + " label=\"Your question\",\n", + " placeholder=\"e.g. What is the best car for long road trips from Johannesburg to Cape Town?\",\n", + " lines=3\n", + " )\n", + "\n", + " submit_btn = gr.Button(\"🚗 Get My Car Recommendation\", variant=\"primary\", size=\"lg\")\n", + "\n", + " gr.Examples(\n", + " examples=[\n", + " [\"I live in Cape Town and need a reliable city car with low fuel costs\"],\n", + " [\"What is the best bakkie for a farm in Limpopo under R400,000?\"],\n", + " [\"I need a family SUV in Johannesburg for school runs and highway driving\"],\n", + " [\"Which car has the lowest total cost of ownership in South Africa?\"],\n", + " [\"Best car for driving between Durban and Johannesburg regularly?\"],\n", + " ],\n", + " inputs=query_box\n", + " )\n", + "\n", + " output = gr.Markdown(label=\"Car Recommendation Report\")\n", + "\n", + " submit_btn.click(fn=run, inputs=[query_box], outputs=[output])\n", + " query_box.submit(fn=run, inputs=[query_box], outputs=[output])\n", + "\n", + " # ── Tab 2: How it works ────────────────────────────────────────────\n", + " with gr.Tab(\"⚙️ How It Works\"):\n", + " gr.Markdown(\"\"\"\n", + "## Multi-Agent Pipeline\n", + "\n", + "Each query passes through **four specialist AI agents** in sequence:\n", + "\n", + "| Step | Agent | Role |\n", + "|------|-------|------|\n", + "| 1 | **Car Safety Agent** | Retrieves relevant facts from the SA car knowledge base (RAG) and assesses which vehicles suit local roads and conditions |\n", + "| 2 | **SA Market Agent** | Recommends specific models available in South Africa with ZAR pricing across three budget tiers |\n", + "| 3 | **Ownership Cost Agent** | Breaks down monthly fuel, insurance, maintenance, and licensing costs for each recommendation |\n", + "| 4 | **Final Recommendation Agent** | Synthesises all three agents into a clear report with a single top pick |\n", + "\n", + "## RAG Knowledge Base\n", + "\n", + "- Facts are loaded from `sa_cars.txt` and embedded using `all-MiniLM-L6-v2`\n", + "- Stored in a **ChromaDB** persistent vector database\n", + "- Top-6 most relevant facts are retrieved per query using cosine similarity\n", + "\n", + "## Models Used\n", + "\n", + "- **claude-haiku-4-5-20251001** — fast, cheap; used for agents 1, 2, and 3\n", + "- **claude-sonnet-4-6** — more capable; used for the final recommendation report\n", + " \"\"\")\n", + "\n", + " \n", + " with gr.Tab(\"📚 Knowledge Base\"):\n", + " gr.Markdown(\"### Facts currently in the SA Car knowledge base\")\n", + " with open(\"sa_cars.txt\", encoding=\"utf-8\") as f:\n", + " kb_text = f.read()\n", + " gr.Textbox(\n", + " value=kb_text,\n", + " label=f\"sa_cars.txt ({collection.count()} facts indexed)\",\n", + " lines=20,\n", + " interactive=False\n", + " )\n", + " gr.Markdown(\n", + " \"_To update: edit `sa_cars.txt` and re-run Cell 4 to rebuild the vector store._\"\n", + " )\n", + "\n", + " gr.HTML(\"\"\"\n", + "
\n", + " SA Car Advisor · Multi-Agent RAG · Built with Anthropic Claude\n", + "
\n", + " \"\"\")\n", + "\n", + "\n", + "ui.launch(share=False, server_name=\"0.0.0.0\", server_port=7860)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": ".venv (3.11.9)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} From 626446dabb65280c67de4002ec685bb801ddd507 Mon Sep 17 00:00:00 2001 From: Jonas Thamane <166150947+NathiJonas@users.noreply.github.com> Date: Mon, 9 Mar 2026 19:32:27 +0200 Subject: [PATCH 2/2] Update Jonas Thamane Week 8 PR.ipynb Fixed the outputs issue --- .../Jonas Thamane Week 8 PR.ipynb | 203 ++---------------- 1 file changed, 13 insertions(+), 190 deletions(-) diff --git a/community-contributions/Jonas Thamane Week 8 PR.ipynb b/community-contributions/Jonas Thamane Week 8 PR.ipynb index e6d0a8f122..ef3574f154 100644 --- a/community-contributions/Jonas Thamane Week 8 PR.ipynb +++ b/community-contributions/Jonas Thamane Week 8 PR.ipynb @@ -10,20 +10,10 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": null, "id": "8fbcd155", "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "\n", - "[notice] A new release of pip is available: 24.0 -> 26.0.1\n", - "[notice] To update, run: c:\\Users\\Lenovo\\projects\\llm_engineering\\.venv\\Scripts\\python.exe -m pip install --upgrade pip\n" - ] - } - ], + "outputs": [], "source": [ "import sys\n", "!{sys.executable} -m pip install -q anthropic chromadb sentence-transformers python-dotenv gradio" @@ -42,17 +32,7 @@ "execution_count": null, "id": "1879a0ee", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "✅ Anthropic client ready\n", - " Fast model : claude-haiku-4-5-20251001\n", - " Smart model : claude-sonnet-4-6\n" - ] - } - ], + "outputs": [], "source": [ "import os\n", "import textwrap\n", @@ -93,18 +73,10 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": null, "id": "4493f415", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "✅ Created sample knowledge base: sa_cars.txt (120 facts)\n" - ] - } - ], + "outputs": [], "source": [ "SAMPLE_KNOWLEDGE = \"\"\"\n", "Toyota Hilux is the best-selling vehicle in South Africa and is ideal for gravel and farm roads.\n", @@ -251,40 +223,7 @@ "execution_count": null, "id": "e1ada3f7", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Loading embedding model...\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - "c:\\Users\\Lenovo\\projects\\llm_engineering\\.venv\\Lib\\site-packages\\huggingface_hub\\file_download.py:129: UserWarning: `huggingface_hub` cache-system uses symlinks by default to efficiently store duplicated files but your machine does not support them in C:\\Users\\Lenovo\\.cache\\huggingface\\hub\\models--sentence-transformers--all-MiniLM-L6-v2. Caching files will still work but in a degraded version that might require more space on your disk. This warning can be disabled by setting the `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For more details, see https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations.\n", - "To support symlinks on Windows, you either need to activate Developer Mode or to run Python as an administrator. In order to activate developer mode, see this article: https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development\n", - " warnings.warn(message)\n", - "Loading weights: 100%|██████████| 103/103 [00:00<00:00, 4217.89it/s]\n", - "\u001b[1mBertModel LOAD REPORT\u001b[0m from: sentence-transformers/all-MiniLM-L6-v2\n", - "Key | Status | | \n", - "------------------------+------------+--+-\n", - "embeddings.position_ids | UNEXPECTED | | \n", - "\n", - "\u001b[3mNotes:\n", - "- UNEXPECTED\u001b[3m\t:can be ignored when loading from different task/architecture; not ok if you expect identical arch.\u001b[0m\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "✅ Embedding model ready\n", - "✅ Vector store ready — 119 facts indexed\n" - ] - } - ], + "outputs": [], "source": [ "\n", "print(\"Loading embedding model...\")\n", @@ -327,24 +266,10 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": null, "id": "5eed173a", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Test retrieval for 'best bakkie for farm roads':\n", - "Suspension upgrades are commonly fitted to bakkies in South Africa to handle corrugated gravel farm roads.\n", - "Nissan Navara offers a comfortable ride for a bakkie and is popular for mixed urban and off-road use in South Africa.\n", - "Bakkie (pickup truck) ownership is a cultural status symbol in many South African communities.\n", - "GWM (Great Wall Motors) P-Series bakkie has gained popularity in South Africa for its affordability and features.\n", - "Isuzu D-Max is a popular workhorse bakkie in South Africa used heavily in agriculture and mining sectors.\n", - "Mitsubishi Triton is a budget-friendly double-cab bakkie option in South Africa with solid off-road capability.\n" - ] - } - ], + "outputs": [], "source": [ "def retrieve_facts(query: str, n_results: int = 6) -> str:\n", " \"\"\"\n", @@ -385,15 +310,7 @@ "execution_count": null, "id": "d65787ee", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "✅ All four agents defined\n" - ] - } - ], + "outputs": [], "source": [ "def llm(prompt: str, model: str = FAST_MODEL) -> str:\n", " \"\"\"Simple Claude call — returns the text response.\"\"\"\n", @@ -524,18 +441,10 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": null, "id": "420cca41", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "✅ Pipeline orchestrator ready\n" - ] - } - ], + "outputs": [], "source": [ "def car_recommendation(query: str) -> str:\n", " \"\"\"\n", @@ -598,46 +507,7 @@ "execution_count": null, "id": "0bfbea50", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Testing Car Safety Agent...\n", - "\n", - "# Vehicle Recommendations for Johannesburg Family Car (School Runs + Highway)\n", - "\n", - "## ✅ WELL SUITED TO YOUR NEEDS\n", - "\n", - "**Vehicle Types:**\n", - "- **Large SUVs** (Toyota Fortuner, Toyota Prado, similar) - ideal for Sandton school run traffic and highway comfort; popular choice in northern Johannesburg suburbs for good reason\n", - "- **Diesel vehicles** - excellent for highway driving with better fuel economy per km on long distances\n", - "- **Reliable mid-range family sedans/SUVs** with good safety ratings\n", - "\n", - "**Key Features to Prioritize:**\n", - "- Higher ground clearance and visibility (advantages in mixed traffic conditions)\n", - "- Proven reliability and local service network\n", - "- Good fuel efficiency for highway use\n", - "- Adequate space for school run duties\n", - "\n", - "## ❌ AVOID FOR THIS NEED\n", - "\n", - "- Nissan Leaf or electric vehicles - limited highway range unsuitable for longer trips\n", - "- Suzuki Swift/Baleno - too small for family comfort on highways; better for inner-city only\n", - "- Vehicles with poor local service support\n", - "\n", - "## 🚨 KEY SA ROAD & SAFETY CONSIDERATIONS\n", - "\n", - "- **School run traffic:** Congestion in northern suburbs requires vehicle with good visibility and maneuverability\n", - "- **Highway safety:** Ensure vehicle has modern safety features; long distances demand reliable brakes and stability control\n", - "- **Security:** Consider vehicles compatible with armed response/tracking systems (popular in JNB for high-value cars)\n", - "- **Fuel costs:** Diesel advantage significant for regular highway commuting\n", - "- **Buying platforms:** Check Drive.co.za and WeBuyCars for reliable used options with service history\n", - "\n", - "**Recommendation:** A used diesel SUV (Fortuner/Prado class) balances all requirements - school run capability, highway comfort, and long-distance fuel efficiency.\n" - ] - } - ], + "outputs": [], "source": [ "\n", "test_query = \"I live in Johannesburg and need a reliable family car for school runs and highway driving\"\n", @@ -658,54 +528,7 @@ "execution_count": null, "id": "f7127f68", "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "C:\\Users\\Lenovo\\AppData\\Local\\Temp\\ipykernel_14436\\2833195560.py:25: UserWarning: The parameters have been moved from the Blocks constructor to the launch() method in Gradio 6.0: theme. Please pass these parameters to launch() instead.\n", - " with gr.Blocks(theme=THEME, title=\"SA Car Advisor\") as ui:\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "* Running on local URL: http://0.0.0.0:7860\n", - "* To create a public link, set `share=True` in `launch()`.\n" - ] - }, - { - "data": { - "text/html": [ - "
" - ], - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/plain": [] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1/4] Running Car Safety Agent...\n", - "[2/4] Running SA Market Agent...\n", - "[3/4] Running Ownership Cost Agent...\n", - "[4/4] Running Final Recommendation Agent...\n" - ] - } - ], + "outputs": [], "source": [ "THEME = gr.themes.Base(\n", " primary_hue=\"green\",\n",