Zero Labs
Industry News / AI

How I Built an AI Agent That Automates My Daily Tasks

Source Β· Towards AI By Ishwar Ambare

From the publisher’s feed, collected in the ZeroLabs newsroom.

Part 1πŸ€– Generative AI β€” Complete Study NotesThis is a complete, beginner-friendly study guide I compiled while learning Generative AI β€” covering everything from transformers to RAG, prompt engineering, and real-world case studiesπŸ“ Compiled by: Ishwar Ambare πŸŽ“ Source: Generative AI Basics ModuleπŸ“‘ Full Table of ContentsπŸ—‚οΈ Part 1 β€” GenAI Introduction & LandscapeWhy Generative AI? The BuzzWhat is Generative AI?GenAI Technology StackTimeline / Journey of GenAIAI HierarchyIndustry ApplicationsMarket Reports & Economic ImpactKey TakeawaysπŸ—‚οΈ Part 2 β€” Prerequisites & API BasicsPython Libraries β€” The β€œWhy”Machine Learning β€” Predictions on Table DataDeep Learning β€” Predictions on Images/Audio/VideoNLP β€” Predictions on TextThe Godfather Paper: β€œAttention is All You Need”OpenAI API SetupPricing Model & TokensHands-On: First API CallsKey Parameters ExplainedKey TakeawaysπŸ—‚οΈ Part 3 β€” Prompt EngineeringDynamic Prompt Templates with .format()Case Study 1 β€” Financial Document Q&A (Asian Paints)Case Study 2 β€” Few-Shot Prompting & Conversational AI (Math Tutor)Case Study 3 β€” Structured Data Extraction & Classification (Laptops)The 3-Step Prompt Engineering FrameworkHomework β€” Wikipedia Q&A BotRate Limiting & Exponential BackoffOpen-Source LLMs via Hugging Face (LLaMA)Key TakeawaysπŸ—‚οΈ PART 1 β€” GenAI Introduction & LandscapeTopic: Introduction & Landscape1. Why Generative AI? The BuzzπŸš€ ChatGPT vs Other Platforms β€” Time to 1 Million Usershttps://medium.com/media/36d2d680a4e03b5e67d8f6e828d0a697/hrefInsight: ChatGPT hit 1M users faster than any platform in history, with 1.8 billion total visits and an avg. session of 7 min 51 sec.πŸ’° Startup Funding in GenAI (as of 2023)Even relatively unknown GenAI startups are securing:$5M–$15M in early rounds$16M–$40M in mid rounds$41M–$100M in later roundsHappening during a low job market β€” investors are betting big on GenAI.The WWW Analogyβ€œGenAI is the new WWW.” Just like the internet created an entire IT industry, GenAI will spawn a new wave of industries and jobs. Being early = massive advantage.2. What is Generative AI?πŸ“– Theoretical DefinitionGenerative AI is a class of machine learning models that learn the statistical distribution of training data and can sample from that distribution to produce entirely new, plausible outputs. Unlike discriminative models (which classify existing data), generative models create β€” they synthesize new data that was never seen during training.πŸ”΄ The Problem It SolvesBefore Generative AI, computers could only recognize or classify content (e.g., β€œthis is a cat” or β€œthis email is spam”). They could not create content from scratch. Generative AI solves this by allowing machines to:Draft letters, code, and reportsCreate images, music, and videoHold multi-turn conversationsSummarize and reason over large documentsSimple DefinitionGenerative AI = A system that takes an input (text, image, audio) and generates new content (text, image, audio, video, code) as output.Exampleshttps://medium.com/media/e84ed5e130747cbe85136b0841fc91c4/hrefFormal StackInput Prompt ──► [LLM / GenAI Model] ──► Generated Output3. GenAI Technology StackLayer 1: Models & APIsπŸ”’ Closed LLMs (Paid / Not Open Source)https://medium.com/media/e09eee5471912f9d39b773acafc4b67d/hrefπŸ”“ Open LLMs (Free / Open Source)https://medium.com/media/10923baf54b0277cffd71d6a5a48ea41/hrefKey difference: Closed = fast, paid. Open = slower, free.🎨 Image Modelshttps://medium.com/media/0b166f03d125378d26df51b8006648b3/href🎡 Music Modelshttps://medium.com/media/8b12bcc9562969d9f5037814baffcc2a/hrefLayer 2: Vector DatabasesπŸ“– Theoretical DefinitionA Vector Database is a specialized database designed to store and query high-dimensional numerical representations (called embeddings) of data (text, images, audio). Embeddings are generated by ML models (like OpenAI’s text-embedding-ada-002) that map semantically similar content to nearby points in a high-dimensional space. Search is done using Approximate Nearest Neighbour (ANN) algorithms (e.g., HNSW, IVF) which find close vectors in milliseconds β€” much faster than comparing every entry.πŸ”΄ The Problem It Solveshttps://medium.com/media/95c15ec64a61ea6d5627715c5a885c15/hrefCore Use Case (RAG): When building a chatbot that knows about your company’s data, you store all your documents as vectors. At query time, find the most relevant chunks and pass them to the LLM.Why Vector DBs?Text data is converted to numerical vectors (e.g., via embeddings)Words/phrases with similar meaning β†’ similar vectors (small angle between them)Enables extremely fast similarity searchIntuition: Word β†’ Vector Spaceking β†’ [1.2, 0.8, ...] ──┐prince β†’ [1.1, 0.9, ...] ──┴── Close together (similar meaning)McDonald's β†’ [8.3, 0.1, ...] ──── Far apart from "king"Popular Vector Databaseshttps://medium.com/media/8d29f99442f99e7ca465f312d0d969e1/hrefUsed by companies like Grammarly to enable fast semantic searches.Layer 3: LLM FrameworksπŸ“– Theoretical DefinitionLLM Frameworks are orchestration libraries that abstract the plumbing required to build complex AI applications. A single LLM call (prompt β†’ response) is simple. But real products require chaining multiple calls, managing memory, routing queries to external tools (calculators, databases, APIs), and handling errors. Frameworks like LangChain implement the β€œchain of thought” and β€œReAct” (Reason + Act) patterns to allow LLMs to reason in steps and use tools.πŸ”΄ The Problem It SolvesProblem: GPT alone can’t access real-time stock prices, your company database, or run code.Solution: LangChain wraps the LLM with tools (search, calculator, SQL) so the model can decide which tool to call next.Problem: Each API call is stateless β€” GPT forgets everything between calls.Solution: LangChain provides memory modules (conversation buffer, summary memory) to persist context across turns.Used when you have a chain of LLM tasks (one output feeds the next):https://medium.com/media/aff9026f42495ad0a9b1424e6504596e/hrefLayer 4: Deploymenthttps://medium.com/media/b0b50c1cb5a7ad690846f82ca01198cc/href4. Timeline / Journey of GenAI1642 ── Machine Learning concepts begin2014 ── GAN Networks introduced (Ian Goodfellow) β€” image generation2017 ── Transformers paper published ("Attention is All You Need") β€” NLP breakthrough2018 ── GPT-1 released (OpenAI) β€” largely unnoticed2019 ── GPT-2 released2020 ── GPT-3 released2021 ── DALLΒ·E released (image generation from text)2022 ── DALLΒ·E 2, ChatGPT 3.5 launches β€” goes viral2023 ── GPT-4 released (limited access)2024+ ── GPT-5 expected; explosive growth across all verticalsKey insight: We are at the very beginning of the GenAI era. By 2030, the transformation will be remarkable.5. AI Hierarchyβ”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚ AI β”‚β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚β”‚ β”‚ Machine Learning β”‚ β”‚β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚β”‚ β”‚ β”‚ Deep Learning β”‚ β”‚ β”‚β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚β”‚ β”‚ β”‚ β”‚ NLP / Transformers β”‚ β”‚ β”‚ β”‚β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β”‚β”‚ β”‚ β”‚ β”‚ β”‚ Generative AI β”‚ β”‚ β”‚ β”‚ β”‚β”‚ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜GenAI sits at the deepest layer but leverages all parent concepts β€” ML, Deep Learning, NLP, Transformers.Key techniques inherited:RNN (Recurrent Neural Networks) β†’ basis for early NLPAutoencoders β†’ used in TransformersTransformers β†’ backbone of modern LLMs (GPT, BERT, etc.)6. Industry ApplicationsπŸ‘¨β€πŸ’» Software Engineering β€” GitHub CopilotWrite a comment β†’ Copilot generates full codeAuto-suggests code completions (just press Tab)Generates unit tests automaticallyCreates components from natural languageImpact: 1 tester can replace 4; 1 dev can write 10x more code.πŸ₯ Healthcare β€” Med-PaLM 2 (Google)Trained on medical knowledgeScored 87% on MBBS-equivalent examsOutperforms many medical studentsAsk symptoms β†’ get diagnosticsπŸŽ“ Education β€” Khanmigo (Khan Academy)AI tutor powered by ChatGPTGuides students through problems (doesn’t just give answers)Can roleplay as a mentor🎨 Marketing & Designhttps://medium.com/media/2b8174427294c532af8b31b96a8dfa37/hrefReal-world: Microsoft ads now use GenAI to generate personalized images per user, in real-time.πŸ’Ή Finance β€” Bloomberg GPTTrained on 50 billion financial parametersAnswers: fundamental analysis, sentiment analysis of newsPotential to replace portfolio managersπŸ›’ E-Commerce β€” MyFashionGPTTell it your occasion β†’ get outfit recommendationsVirtual try-on: see how clothes look on a body similar to yoursβš–οΈ LegalCan analyze case law, draft documentsStill in early stages but growing fast7. Market Reports & Economic ImpactMcKinsey Reporthttps://medium.com/media/e3ff8d7259bf31655f2adf7e7626a6df/hrefThe $2.6T–$4.4T additional value β‰ˆ GDP of the United Kingdom (6th largest economy)Most Impacted Sectors:πŸ† Software Engineering (highest impact)πŸ“Š FinanceπŸ“£ Sales & MarketingGoldman Sachs Reportβ€œGenAI could raise global GDP by 7%.”8. Key Takeaways🎯 Core InsightsGenAI is not a trend β€” it’s the next foundational technology (like the internet)Even non-tech professionals (sales, marketing, doctors, lawyers) need basic GenAI literacyPeople who master this will create job disruption, not suffer from it🧠 The Darwin Principleβ€œYou either adapt or get replaced. It’s Darwin’s theory β€” you need to survive.β€πŸ’‘ Startup OpportunityCompanies with just an idea are getting $100M+ in fundingOpen-source models (Stable Diffusion, etc.) let you build startups on top for freeEarly movers have massive advantagesπŸ—ΊοΈ Learning PathPython Basics β”‚ β–ΌGenAI Fundamentals + Prompt Engineering β”‚ β–ΌMachine Learning + NLP β”‚ β–ΌLLM Fine-tuning, RAG, Vector DBs, Deployment β”‚ β–ΌBuild β†’ Ship β†’ Fund πŸš€πŸ“š Resourceshttps://medium.com/media/2a24e251f078e91aa672dc34760b40f5/hrefπŸ—‚οΈ PART 2 β€” Prerequisites & API BasicsTopic: Prerequisites & API Basics9. Python Libraries β€” The β€œWhyβ€πŸ“– Theoretical DefinitionA Python Library (also called a package or module) is a pre-built collection of functions, classes, and constants written by domain experts and published to the Python Package Index (PyPI). Instead of implementing complex algorithms (matrix multiplication, gradient descent, chart rendering) from scratch, you install the library (pip install numpy) and call its functions β€” abstracting away thousands of lines of optimized, tested code.πŸ”΄ The Problem It Solveshttps://medium.com/media/06153696b2a6c4f6c58a2f8f53a32f01/hrefKey Principle: Don’t reinvent the wheel. The entire GenAI ecosystem (OpenAI, LangChain, HuggingFace) is built on the shoulders of Python libraries.The Jungle Analogyhttps://medium.com/media/319ddc9827dfea5dd27686d89870e31b/hrefPython Libraries = Pre-written expert code so you don’t reinvent the wheel.Key Librarieshttps://medium.com/media/b8bc4ec7c00d529b8bf1419eb2c0d766/href# Raw Python (From Scratch)total = 0for num in [1, 2, 7, 10, 50]: total += num# With NumPy (Library)import numpy as nptotal = np.sum([1, 2, 7, 10, 50])# Load CSV with Pandasimport pandas as pddata = pd.read_csv("a.csv")print(data) # Stored as a DataFrameDataFrame = The variable that holds your loaded table data in Pandas.10. Machine Learning β€” Predictions on Table DataThe Astrologer AnalogyMachine Learning works like an astrologer β€” it predicts the future based on data.Real-World Examples🌦️ Weather forecast (β€œwill it rain today?”)πŸ” Google search autocomplete🏏 IPL winning probability during a matchHow It Works β€” The Core IdeaExample: Experience β†’ Salaryhttps://medium.com/media/78ae94d3a6a43eedcb3f8f65bc8beada/hrefYour brain derived: Salary = 10,000 Γ— ExperienceThis is exactly what ML does β€” find the mathematical function (model) that fits the data.Goal of ML: Given data β†’ Find a mathematical function (model) β†’ Use that model to make predictions β†’ Minimize the prediction errorModel = A mathematical function derived from data, used for predictions.Reality CheckReal-world data is never β€œperfect”Strong maths foundation (stats, probability, calculus) = ML becomes easier11. Deep Learning β€” Predictions on Images/Audio/VideoWhat’s Different?ML β†’ works on structured/tabular dataDeep Learning β†’ works on unstructured data (images, video, audio)Uses Neural Networks at its coreReal-World ExamplesπŸ“Έ Facebook Photo TaggingYou upload a photo β†’ FB automatically detects and tags faces🫁 Tuberculosis Detection (Real Project β€” Portus Hospital)Problem: X-ray β†’ Radiologist β†’ 3 days β†’ Result 90% of cases β†’ No TB (over-prescribed medicine β†’ side effects)Solution: X-ray Image β†’ Deep Learning Model β†’ TB / No TB (instantly) If model says NO TB β†’ Immediate relief, no side effects If model says YES TB β†’ Still send to radiologistResult: Reduced over-prescription from 90% β†’ 10-20% of patientsπŸš— Object Detection on RoadsCars, trucks, bikes, number plate recognitionUsed in advanced military applicationsNeural Network = The algorithm powering Deep Learning predictions.12. NLP β€” Predictions on TextπŸ“– Theoretical DefinitionNatural Language Processing (NLP) is the subfield of AI concerned with enabling computers to understand, interpret, and generate human language. The core challenge: computers process numbers, not language. NLP bridges this gap by representing words and sentences as vectors (embeddings) in a mathematical space where similar meanings map to similar positions. Early NLP used hand-crafted rules. Modern NLP uses deep learning (especially Transformers) to learn language patterns from billions of text examples.πŸ”΄ The Problem It Solveshttps://medium.com/media/fec8ff63eb2df24bdf1684dc18f13c60/hrefTransformers (2017) solved all of the above by introducing the attention mechanism, which weighs the relevance of every word relative to every other word in a sentence.What is NLP?Natural Language Processing (NLP) = Making predictions / generating output based on human text/language.Exampleshttps://medium.com/media/dd83ce71ac114d4b9d3587ab01978bb1/hrefThe Breakthrough: Transformers (2017)Paper: β€œAttention is All You Need” β€” Google, 2017This single paper made ChatGPT possibleAll authors eventually left Google to start their own companies or join OpenAIGenAI is simply an extension of NLP + Transformers.13. The Godfather Paper: β€œAttention is All You Need”Title: Attention Is All You NeedAuthors: Vaswani et al. (Google Brain / Google Research)Year: 2017Impact: Foundation of ALL modern LLMs (GPT, BERT, etc.)πŸ“„ Read the paperKey concepts introduced:Transformer architecture β€” replaces RNNs with attention mechanismsSelf-attention β€” understands context of each word relative to othersEncoder-Decoder β€” basis for translation, summarization, generationWithout this paper, there is no ChatGPT.14. OpenAI API SetupStep-by-Step Account Setup1. Go to: https://platform.openai.com2. Create account (sign up)3. Add credit card / debit card details4. Navigate to: API Keys β†’ Create new secret key5. COPY and SAVE the key immediately (You cannot view it again after closing the dialog)6. DO NOT share your API key with anyone⚠️ Warning: Sharing your secret key = others can rack up charges on your card.In Codeimport openaiopenai.api_key = "sk-xxxxxxxxxxxx"# Use environment variables in production β€” never hardcode in shared code15. Pricing Model & TokensWhat is a Token?Token β‰ˆ 4–5 characters β‰ˆ roughly 1 word (simplified rule of thumb)Example: "Who won IPL 2023"β†’ Approximately 6 tokensTwo types of tokens:https://medium.com/media/0755e37fa3c62c8450d4188e446601d5/hrefBoth input AND output tokens are billed.Pricing Table (as of lecture date)https://medium.com/media/04a8b185201b73df8b7a84c1274fa87a/hrefπŸ’‘ Use gpt-3.5-turbo-16k for all practice.πŸ” Token VisualizerTry: platform.openai.com/tokenizer β€” paste any text to see token count.16. Hands-On: First API CallsSetup!pip install openaifrom openai import OpenAIclient = OpenAI(api_key="YOUR_KEY")Concept: Message Roleshttps://medium.com/media/d7d05b9c24ccdf6c8e312ac4ac2cc933/hrefBasic API Callmessages = [ {"role": "system", "content": "You are a very helpful assistant."}, {"role": "user", "content": "Who won IPL 2020?"}]response = client.chat.completions.create( model="gpt-3.5-turbo-16k", messages=messages)print(response.choices[0].message.content)# Output: "Mumbai Indians won the IPL in 2020."Getting JSON Outputmessages = [ { "role": "system", "content": "You are a helpful assistant designed to output JSON with the key 'answer'." }, { "role": "user", "content": "Who won IPL 2020?" }]response = client.chat.completions.create( model="gpt-3.5-turbo-16k", messages=messages)import jsonoutput = json.loads(response.choices[0].message.content)result = output.get("answer", None)print(result)# Output: "Mumbai Indians"πŸ’‘ Why JSON output? In LangChain pipelines, the output of one LLM call becomes the input of the next.Personality Injectionmessages = [ {"role": "system", "content": "You are a mean teenager assistant."}, {"role": "user", "content": "What is machine learning?"}]# GPT responded: "Go Google it yourself."GPT adopts whatever personality you define in the system role.17. Key Parameters Explainedhttps://medium.com/media/8b8f1cc59f283efa7f44f0c5d10ac93f/hrefTemperature Intuitiontemperature = 0 β†’ Same answer every time (cold, rigid)temperature = 0.5 β†’ Some variation (balanced)temperature = 1 β†’ High creativity, different answer each run (hot, random)Stop Parameterstop=["deep learning"]# GPT stops generating the moment "deep learning" appears# Useful for: content filters, child-safe apps, staying on topicPenalty Intuitionfrequency_penalty = 0 β†’ Words can repeat freelyfrequency_penalty = 1 β†’ Penalizes every repeated wordUse high penalty: long outputs where you want varietyUse low penalty: technical terms MUST repeat (e.g., "gradient descent")18. Key TakeawaysπŸ—οΈ Prerequisites SummaryPython Basics └─► Python Libraries (NumPy, Pandas) └─► Machine Learning β€” predict on table data └─► Deep Learning β€” predict on images/audio └─► NLP β€” predict on text data └─► Transformers (2017) β€” the breakthrough └─► Generative AI (ChatGPT, etc.)πŸ’» API vs ChatGPT Websitehttps://medium.com/media/02b2e8bdd8ea115a92d5e762ca025336/hrefπŸ“š Resourceshttps://medium.com/media/6f6048fe53a714cee583b9201c226dfd/hrefπŸ—‚οΈ PART 3 β€” Prompt EngineeringTopic: Prompt Engineering19. Dynamic Prompt Templates with .format()πŸ“– Theoretical DefinitionPrompt Templating is the practice of separating the static instruction structure of a prompt from the dynamic variable data that changes per request. This is analogous to SQL prepared statements (e.g., SELECT * FROM users WHERE id = ?) β€” the query structure is fixed; only the parameter changes. At runtime, variables (row data, user input, document text) are injected into the template using Python's .format() method or f-strings.πŸ”΄ The Problem It Solveshttps://medium.com/media/64623583aed8a9dabfe9cdb72ed809d3/hrefInstead of hardcoding values, use Python’s .format() to inject values at runtime β€” like command-line arguments.base_prompt = """You are a helpful teaching assistant.The topic is: {0}Please explain it clearly with examples."""topic_name = "Autoencoders"final_prompt = base_prompt.format(topic_name)print(final_prompt)# β†’ "You are a helpful teaching assistant.# The topic is: Autoencoders# Please explain it clearly with examples."Why this matters: In Case Study 3, each row of a dataset gets injected into the prompt one by one β€” making it scalable over thousands of rows.20. Case Study 1 β€” Financial Document Q&A (Asian Paints)πŸ“– Theoretical Definition β€” Retrieval-Augmented Generation (RAG) LiteThis pattern is a simplified form of Retrieval-Augmented Generation (RAG). RAG = Instead of relying on the LLM’s internal (pre-trained) knowledge, you retrieve the relevant document and augment the LLM’s prompt with it β€” forcing it to reason over your data. The LLM acts as a reasoning engine, not a knowledge store. The document is the knowledge store.πŸ”΄ The Problem It Solveshttps://medium.com/media/7f29b248867f87eece4ac17e752d9cc8/hrefSolution Pattern: Load document β†’ Pass it in the prompt β†’ Ask GPT to reason only from that document β†’ Get precise, citeable answers in seconds.Problem StatementCompany quarterly earnings calls are publicly available (screener.in)Reading a full PDF manually is time-consumingGoal: Ask GPT specific questions about the document and get precise answersStep 1: Mount Google Drive & Read the Filefrom google.colab import drivedrive.mount('/content/drive')file_path = "/content/drive/My Drive/genai/"!ls {file_path}transcript = ""with open(file_path + "AsianPaints.txt", "r") as f: for line in f: transcript += lineprint(len(transcript)) # e.g. 43146 charactersNote: Convert PDF β†’ TXT first. Libraries like PyPDF2 also work directly. Clarification: max_tokens=800 is the output limit, not input. Your 43k-char transcript goes in as input β€” that's fine.Step 2: Write the Base Instruction Promptbase_instruction = """You are a helpful assistant helping a financial analystretrieve relevant financial and business information from a document.Given below is a question and the transcript of an earnings call of Asian Paints,attended by the top management of the firm. Try to respond with specific numbersand facts wherever possible. If you are not sure about the accuracy of theinformation, just say: "I do not know.""""Step 3: Ask a Questionfrom openai import OpenAIclient = OpenAI(api_key="YOUR_KEY")question = "How much has Asian Paints' business grown?"prompt = base_instruction + "\n\nQuestion: " + question + "\n\nTranscript:\n" + transcriptmessages = [{"role": "user", "content": prompt}]response = client.chat.completions.create( model="gpt-3.5-turbo-16k", messages=messages, max_tokens=1000)print(response.choices[0].message.content)Ask Different Questions (Same Structure)# Summarize financialsquestion = """Summarize the key financial metrics: revenue growth, profitability, cash flow, and debt."""# Check for acquisitionsquestion = "Which company has Asian Paints acquired?"# If info not in doc β†’ GPT replies: "No specific information available."Key InsightWithout GenAI: Read 40-page PDF manually β†’ find answerWith GenAI: Pass PDF text + question β†’ get answer in secondsCritical Rule: GPT's training data is pre-2021. For latest company data β†’ pass it in the prompt. GPT then reasons over YOUR data, not its own training data.Real-World ApplicationsInternal company FAQ chatbot (pass policy docs as context)Legal document analyzerSupport ticket knowledge base21. Case Study 2 β€” Few-Shot Prompting & Conversational AI (Math Tutor)πŸ“– Theoretical Definition β€” In-Context LearningFew-Shot Prompting is a technique that leverages a property of large language models called In-Context Learning (ICL). During training, LLMs saw billions of pattern-completion examples. ICL exploits this by embedding demonstration examples (input-output pairs) directly inside the prompt β€” conditioning the model’s behavior without changing its weights. Formally:Zero-shot: No examples β€” just instructions β†’ works for simple, well-known tasksOne-shot: 1 example β†’ useful for niche formatsFew-shot: 2–10 examples β†’ significantly shapes model tone, style, and output formatπŸ”΄ The Problem It Solveshttps://medium.com/media/85e37d62a472f38b7b9a81828f68ec0f/hrefKey insight: You are not changing the model. You are changing the context the model sees β€” which changes its predictions. This is the power and limitation of few-shot prompting.What is Few-Shot Prompting?Few-Shot Prompting = Giving GPT example conversations so it learns how to behave, not just what to answer.Three roles in the messages array:https://medium.com/media/2c205ab7b69f5826b5443baaf41955a1/hrefBasic Few-Shot Examplemessages = [ { "role": "system", "content": """You are an AI tutor that assists school students with math homework.You never reveal the right answer to the student.You ask probing questions to identify where the student needs help.Provide hints and directional feedback. Do NOT reveal the correct answer.""" }, # Training examples {"role": "user", "content": "Help me solve: 3x - 9 = 21"}, {"role": "assistant", "content": "Try moving the -9 to the right side. What do you get?"}, {"role": "user", "content": "Is 3x = 12 correct?"}, {"role": "assistant", "content": "There's a mistake. When you move -9, its sign changes. Try again."}, {"role": "user", "content": "3x = 30"}, {"role": "assistant", "content": "Great! Now divide both sides by 3. What do you get?"}, {"role": "user", "content": "x = 10"}, {"role": "assistant", "content": "Correct! Well done."}, # New question {"role": "user", "content": "Can you help me solve: 3x - 4 = 7?"}]response = client.chat.completions.create( model="gpt-3.5-turbo-16k", messages=messages)print(response.choices[0].message.content)Why GPT is bad at math: GPT was trained on text, not mathematical reasoning. Few-shot prompting helps but doesn’t fully fix it. LangChain with calculator tools is the proper solution.Making It Conversational (While Loop)The key problem: after one exchange, GPT forgets the context. Solution: keep appending every message to the history.MAX_CONVERSATIONS = 20 # Stop after N turns (credit card protection)message_history = [ {"role": "system", "content": "You are an AI math tutor..."}, # ... few-shot examples here ...]conversation_length = 0while conversation_length user_input = input("You: ") if user_input.lower() == "exit": break # Append user message message_history.append({"role": "user", "content": user_input}) # Call GPT with full history response = client.chat.completions.create( model="gpt-3.5-turbo-16k", messages=message_history ) gpt_reply = response.choices[0].message.content print(f"GPT: {gpt_reply}") # Append GPT's reply message_history.append({"role": "assistant", "content": gpt_reply}) conversation_length += 1Tracking Token Usageresponse = client.chat.completions.create( model="gpt-3.5-turbo-16k", messages=message_history)total_tokens = response.usage.total_tokensprint(f"Tokens used this turn: {total_tokens}")# Accumulate across turnstotal_tokens_used += total_tokensprint(f"Total tokens used: {total_tokens_used}")Why MAX_CONVERSATIONS matters: Each turn sends the entire history to GPT. Without a limit, a student could run 1000 turns and drain your API credits.22. Case Study 3 β€” Structured Data Extraction & Classification (Laptops)Problem StatementGiven a CSV of laptop descriptions, use GPT to:Classify each laptop into a category (General / Business / Gamer / Programmer / Multimedia)Extract structured attributes (brand, GPU, display, weight, processor, budget) as JSONimport pandas as pddf = pd.read_csv("/content/drive/My Drive/genai/laptop_descriptions.csv")print(df.head())Task A β€” ClassificationStep 1: GPT API Functiondef get_chat_response_mcq1(user_request): system_message = """You are a shopping assistant. The user will give you alaptop description and some categories with their details.Find out which category the laptop fits best according to the description.Give ONLY ONE WORD output β€” the category name from the list only.""" messages = [ {"role": "system", "content": system_message}, {"role": "user", "content": user_request} ] response = client.chat.completions.create( model="gpt-3.5-turbo-16k", messages=messages ) return response.choices[0].message.contentStep 2: The Prompt with PlaceholderMCQ1_prompt = """From the description of the laptop below, identify what rolethe laptop serves. Refer to the key-value pair of categories:- General: Light web browsing, editing documents.- Business: Portability, battery backup, general use.- Gamer: High-performance GPU, high refresh rate.- Programmer: Strong CPU, high RAM, developer tools.- Multimedia: Large screen, high-quality audio, video editing.Laptop Description: {description}"""Step 3: Loop Through Datasetdef tag_laptop(df): tagged_df = df.copy() laptop_dict = tagged_df.to_dict(orient="records") for i, record in enumerate(laptop_dict): prompt = MCQ1_prompt.format(description=record["laptop_description"]) category = get_chat_response_mcq1(prompt) tagged_df.loc[i, "category"] = category return tagged_dfresult_df = tag_laptop(df)print(result_df.head())Task B β€” Structured JSON ExtractionTarget Structureoutput_structure = { "brand": "", "model_name": "", "gpu_processor": "", "display_resolution": "", "weight": "", "processor_clock_speed": "", "budget": ""}The Extraction Prompt (Two Inputs)MCQ2_prompt = """From the laptop description below, extract values for:{str_input}Rules:- Give quantitative, numerical output only (e.g., "2.4 GHz", NOT "very fast")- Do NOT give qualitative answers or adjectives- If a value is missing, write "N/A"- Output in valid JSON formatExample: if processor speed is 2.4 GHz β†’ write "2.4 GHz", NOT "fast"Laptop Description: {description}"""Loop with Two Inputsdef extract_laptop_info(df): result_df = df.copy() laptop_dict = result_df.to_dict(orient="records") for i, record in enumerate(laptop_dict): prompt = MCQ2_prompt.format( str_input=str(output_structure), description=record["laptop_description"] ) raw_output = get_chat_response_mcq2(prompt) result_df.loc[i, "extracted_json"] = raw_output return result_dffinal_df = extract_laptop_info(df)print(final_df.head())The str_input trick: When you need to pass a Python dict into the prompt, use str() and .format(str_input=...). Count of {} placeholders = number of .format() arguments.23. The 3-Step Prompt Engineering FrameworkThis framework works for any prompt engineering problem β€” including interviews.β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚ STEP 1: Write the GPT API function β”‚β”‚ def get_chat_response(user_request): β”‚β”‚ system_message = "..." ← changes per problem β”‚β”‚ messages = [system, user_request] β”‚β”‚ response = client.chat.completions.create(...) β”‚β”‚ return response.choices[0].message.content β”‚β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”‚ STEP 2: Write the prompt with placeholders β”‚β”‚ prompt = """...context... β”‚β”‚ {description} ← replaced per row at runtime β”‚β”‚ {str_input} ← only if 2nd input needed β”‚β”‚ """ β”‚β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”‚ STEP 3: Loop through data & stitch it together β”‚β”‚ for record in data: β”‚β”‚ final_prompt = prompt.format( β”‚β”‚ description=record["col"], β”‚β”‚ str_input=structure β”‚β”‚ ) β”‚β”‚ result = get_chat_response(final_prompt) β”‚β”‚ store result β”‚β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜Interview tip: When given a dataset + task, this is the template to follow. Only the system message and prompt text change. The structure stays the same every time.24. Homework β€” Wikipedia Q&A BotGoalGiven a question, automatically:Extract the search topicFetch the relevant Wikipedia pageAsk GPT to answer from that page’s contentStep 1: Install & Fetch a Wikipedia Page!pip install wikipedia-apiimport wikipediaapidef wiki_search(query_term): wiki = wikipediaapi.Wikipedia( user_agent="my-genai-project", language="en" ) page = wiki.page(query_term) return page.text # Full text of the Wikipedia articlecontext = wiki_search("India")user_agent = Like a return address β€” tells Wikipedia who is sending the request.Step 2: Extract Topic from Question (GPT Call #1)def get_wiki_query(user_request): system_message = """The user will ask you a question.Extract the general topic as a single word or short phrase.Examples:- "What is the height of Narendra Modi?" β†’ "Narendra Modi"- "When was the Eiffel Tower built?" β†’ "Eiffel Tower"- "Where is the next FIFA World Cup?" β†’ "FIFA World Cup"Give only the noun/topic. No extra text.""" messages = [ {"role": "system", "content": system_message}, {"role": "user", "content": user_request} ] response = client.chat.completions.create( model="gpt-3.5-turbo-16k", messages=messages ) return response.choices[0].message.content.strip()Step 3: Answer from Wikipedia (GPT Call #2)def answer_from_wiki(user_request, context): system_message = """You are a helpful assistant that responds to user queriesbased on the provided context only.If you do not find the information, say: "Information not found." """ content = f"Context:\n{context}\n\nQuestion: {user_request}" messages = [ {"role": "system", "content": system_message}, {"role": "user", "content": content} ] response = client.chat.completions.create( model="gpt-3.5-turbo-16k", messages=messages, max_tokens=500 ) return response.choices[0].message.contentFull Pipelineuser_request = "Who is the current President of India?"search_term = get_wiki_query(user_request) # β†’ "India"context = wiki_search(search_term) # β†’ Full Wikipedia pageanswer = answer_from_wiki(user_request, context)print(answer)Flow:User Question β”‚ β–ΌGPT Call #1: extracts topic β†’ "India" β”‚ β–ΌWikipedia API: fetches full page text β”‚ β–ΌGPT Call #2: answers from page context only β”‚ β–ΌFinal AnswerImportant: Do NOT load all of Wikipedia. Always fetch only the single relevant page per query.25. Rate Limiting & Exponential BackoffπŸ“– Theoretical DefinitionRate Limiting is a server-side constraint that throttles the number of API requests a client can make within a time window (e.g., 60 requests/minute for a free tier). Exponential Backoff is a standard error-handling algorithm where the client, after receiving a rate-limit error (HTTP 429), waits for an exponentially increasing delay before retrying β€” preventing a β€œthundering herd” of simultaneous retries from overwhelming the server further. The pattern is defined in RFC 2616 and widely used in distributed systems (AWS SDKs, GCP clients, HTTP clients).πŸ”΄ The Problem It Solveshttps://medium.com/media/41b356ca876664b8f0b926a3ed18992d/hrefThe ProblemOpenAI limits requests per second. With many concurrent users you get:Error: 429 Too Many RequestsThe Solution: Exponential BackoffAttempt 1 β†’ fail β†’ wait 1sAttempt 2 β†’ fail β†’ wait 2sAttempt 3 β†’ fail β†’ wait 4sAttempt 4 β†’ fail β†’ wait 8sAttempt 5 β†’ fail β†’ wait 16sAttempt 6 β†’ stopImplementation with tenacity!pip install tenacityfrom tenacity import retry, wait_exponential, stop_after_attempt@retry( wait=wait_exponential(multiplier=1, min=1, max=20), stop=stop_after_attempt(6))def get_chat_response_with_backoff(messages): response = client.chat.completions.create( model="gpt-3.5-turbo-16k", messages=messages ) return response.choices[0].message.content@retry is a Python decorator β€” wraps the function and handles retries automatically. When to use: Not needed for personal learning. Critical for production chatbots with many concurrent users.26. Open-Source LLMs via Hugging Face (LLaMA)πŸ“– Theoretical DefinitionOpen-Source LLMs are language models whose model weights (the billions of learned parameters) are publicly released, allowing anyone to download, run, fine-tune, or modify them without cost or API dependency. Hugging Face is the central repository and toolkit for open-source ML models. It provides:transformers library: Standardized Python API to load and run models (AutoTokenizer, AutoModelForCausalLM)accelerate library: Handles distributing the model across GPUs/CPUs automaticallyModel Hub: Over 500,000 pre-trained models in one searchable registry LLMs like LLaMA 3 use a decoder-only Transformer architecture. During inference, they predict the next token in a sequence, one at a time (autoregressive generation), until an end-of-sequence token is produced.πŸ”΄ The Problem It Solveshttps://medium.com/media/0698e41bef87c09c219596673caafd1f/hrefWhat is Hugging Face?Hugging Face = The β€œscikit-learn” of LLM models.https://medium.com/media/9e14c82bc323d5bcd3f241226736f3c7/hrefWhy Learn LLaMA?https://medium.com/media/ba54167827f78c002339e5626726ff2c/href3 Steps to Access LLaMAStep 1: Request access from Meta β†’ https://llama.meta.com/ β†’ Fill in name, email, use case β†’ Select models (LLaMA 2, 3, etc.) β†’ Approval: ~15-20 minutesStep 2: Request model permission on Hugging Face β†’ https://huggingface.co/meta-llama/ β†’ Log in with SAME email as Step 1 ← CRITICAL β†’ Click each model β†’ Request Access β†’ SubmitStep 3: Create a Hugging Face token β†’ https://huggingface.co/settings/tokens β†’ New Token β†’ Choose "Read" β†’ Copy & saveColab Setup: Switch to GPURuntime β†’ Change runtime type β†’ T4 GPU β†’ SaveLLaMA will not run on CPU in any reasonable time.Install & Load Model!pip install transformers acceleratefrom transformers import AutoTokenizer, AutoModelForCausalLM, pipelineimport torchHF_TOKEN = "hf_xxxxxxxxxxxx"model_id = "meta-llama/Meta-Llama-3-8B-Instruct"ptokenizer = AutoTokenizer.from_pretrained(model_id, token=HF_TOKEN)# Downloads ~10 GB β€” takes a few minutesInference Pipelinedef run_llama(prompt_text): pipe = pipeline( "text-generation", model=model_id, torch_dtype=torch.bfloat16, device_map="auto", token=HF_TOKEN ) output = pipe( prompt_text, max_new_tokens=500, do_sample=True, top_k=50, eos_token_id=tokenizer.eos_token_id ) return output[0]["generated_text"]LLaMA Prompt TemplateLLaMA uses a specific format (different from OpenAI’s messages list):def build_llama_prompt(system_message, user_message): return f"""[INST] >{system_message}>{user_message} [/INST]"""# Examplesystem = "You are a helpful, respectful, and honest assistant."user = "I like Friends and Money Heist. Recommend similar shows to watch."prompt = build_llama_prompt(system, user)result = run_llama(prompt)print(result)OpenAI vs LLaMA β€” Structural Comparisonhttps://medium.com/media/92c7664da0006104be99f919cf8fd9eb/href27. Key TakeawaysπŸ—οΈ Prompt Engineering Core PrinciplesPrompt writing takes time. Even experienced engineers spend 20–30+ minutes per prompt. That’s normal.Start with one example; add more if output is wrong. More examples = better behavior.Be explicit about output format. One word, JSON, numerical values β€” always state it.Tell GPT what NOT to do. β€œDo not give qualitative answers”, β€œIf unknown, say I do not know.”Use the 3-step framework for any classification / extraction / Q&A problem.🧠 When to Use Each Approachhttps://medium.com/media/79b1de9bf3fab65da274dece0ca389b1/hrefπŸ’‘ The Real-World PatternGenAI chatbot = Your domain knowledge + GPT reasoningExample: Instead of: employee reads 200-page policy manual You build: pass policy PDF as context β†’ chatbot answers questionsSame pattern applies to: - Support ticket classification (Case Study 3) - Earnings call analysis (Case Study 1) - Math tutoring (Case Study 2) - Medical document Q&A - Legal contract reviewπŸ“š Resourceshttps://medium.com/media/46721d0b814f16f3b9c1c0269a1f2328/hrefπŸ”— About the AuthorThese notes were compiled by Ishwar Ambare as part of a personal learning journey through the Generative AI Basics Module.πŸ“Œ Follow me on LinkedIn: linkedin.com/in/ishwar-ambare✍️ Read my articles on Medium: medium.com/@ishwarambareGenerative AI Complete Notes | Basics ModuleπŸ€– How I Built an AI Agent That Automates My Daily Tasks was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.