{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Welcome to Lab 3 for Week 1 Day 4\n", "\n", "Today we're going to build something with immediate value!\n", "\n", "In the folder `me` I've put a single file `linkedin.pdf` - it's a PDF download of my LinkedIn profile.\n", "\n", "Please replace it with yours!\n", "\n", "I've also made a file called `summary.txt`\n", "\n", "We're not going to use Tools just yet - we're going to add the tool tomorrow." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", " \n", " \n", "

Looking up packages

\n", " In this lab, we're going to use the wonderful Gradio package for building quick UIs, \n", " and we're also going to use the popular PyPDF2 PDF reader. You can get guides to these packages by asking \n", " ChatGPT or Claude, and you find all open-source packages on the repository https://pypi.org.\n", " \n", "
" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# If you don't know what any of these packages do - you can always ask ChatGPT for a guide!\n", "\n", "from dotenv import load_dotenv\n", "from openai import OpenAI\n", "from pypdf import PdfReader\n", "import gradio as gr" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "load_dotenv(override=True)\n", "openai = OpenAI()" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "reader = PdfReader(\"me/linkedin.pdf\")\n", "linkedin = \"\"\n", "for page in reader.pages:\n", " text = page.extract_text()\n", " if text:\n", " linkedin += text" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Raúl Márquez\n", "Avila\n", "MBA, Chief Enterprise Architect\n", "Cellphone :5517292850/ Email : fredfred2@gmail.com\n", "https://www.linkedin.com/\n", "in/raul-\n", "marquez-865b832b/\n", "Contact\n", "5517292850\n", "fredfred2@gmail.com\n", "Coyoacán, CDMX\n", "Information\n", "Habilidade\n", "s\n", "Flexibilidad\n", "Liderazgo\n", "Creatividad\n", "Honestidad\n", "Resolución de\n", "problemas\n", "Relaciones \n", "interpersonal\n", "es\n", "Negociación\n", "Idiomas\n", "Inglés\n", "Español\n", "Hobbies\n", "Chief Enterprise Architect\n", "Intellego\n", "Presales and Architecture, Development and Innovation\n", "leader. Using technologies such as: Machine Learning,\n", "Big Data, Microservices, Cloud, UX, SOA and DevOps.\n", "Leader of development, information and infrastructure\n", "architects.\n", "Project manager of mission critical sectors: government,\n", "telecommunications, retail, banking and fintech.\n", "2011-2017\n", "Chief SOA Architect\n", "Infotec\n", "Leader of public and financial sector architecture\n", "projects.\n", "Chief architect responsible for optimizing resources\n", "from government sectors, implementing automation\n", "and research projects for new emerging technologies.\n", "Responsible for leading and implementing portfolio of\n", "SOA projects within the financial branch, implementing\n", "business buses, BPM and DWH.\n", "2007-2011\n", "Chief Enterprise Architect\n", "Axity\n", "Presales and Innovation and Digital Transformation\n", "projects leader, with technologies such as: Blockchain,\n", "Machine Learning, Big Data, Cloud, Microservices and\n", "DevOps.\n", "Leader of the company's business architecture plan, at\n", "the managerial level, designing the company's offer, new\n", "technologies and required capabilities.\n", "Leader of multipractical senior architects. Managing\n", "2017-\n", "Present\n", "Experience\n", "Education\n", "2018-2020 Master of Business Administration – \n", "MBA\n", "EGADE Business School\n", "2005-2009 Ingeniero en computación\n", "UNAM, Facultad de Ingeniería\n", "Certification\n", "Enterprise Architect TOGAF Level II\n", "Amazon Web Services Solution Architect\n", "Amazon Web Services Machine Learning Specialist\n", "Project Manager Professional PMP\n", "COBIT 5 Certified\n", "Enterprise Architect SOA\n", "Enterprise Architect Java (SCEA 5 Part I, Part II, Part III)\n", "Java Web Services Developer Certified JEE5 (SCDJWS)\n", "Java Business Componentes Developer Certified JEE5 \n", "(SCBCD)\n", "Java Web Componentes Developer Certified JEE5 \n", "(SCWCD)\n", "Java Developer Certified Java 1.5 (SCJD)\n", "Java Programmer Certified Java 1.5 (SCJP)\n", "\n" ] } ], "source": [ "print(linkedin)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "with open(\"me/summary.txt\", \"r\", encoding=\"utf-8\") as f:\n", " summary = f.read()" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "name = \"Raul Marquez\"" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "system_prompt = f\"You are acting as {name}. You are answering questions on {name}'s website, \\\n", "particularly questions related to {name}'s career, background, skills and experience. \\\n", "Your responsibility is to represent {name} for interactions on the website as faithfully as possible. \\\n", "You are given a summary of {name}'s background and LinkedIn profile which you can use to answer questions. \\\n", "Be professional and engaging, as if talking to a potential client or future employer who came across the website. \\\n", "If you don't know the answer, say so.\"\n", "\n", "system_prompt += f\"\\n\\n## Summary:\\n{summary}\\n\\n## LinkedIn Profile:\\n{linkedin}\\n\\n\"\n", "system_prompt += f\"With this context, please chat with the user, always staying in character as {name}.\"\n" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"You are acting as Raul Marquez. You are answering questions on Raul Marquez's website, particularly questions related to Raul Marquez's career, background, skills and experience. Your responsibility is to represent Raul Marquez for interactions on the website as faithfully as possible. You are given a summary of Raul Marquez's background and LinkedIn profile which you can use to answer questions. Be professional and engaging, as if talking to a potential client or future employer who came across the website. If you don't know the answer, say so.\\n\\n## Summary:\\nWith over 15 years of experience in the tech industry, I am a CEO who constantly evolves and leads in cutting-edge technologies. I have focused my career on leading teams towards innovation and business success, delivering solutions that meet and exceed customer expectations and industry standards. \\n\\nAs the CEO of Digital Challengers IT, I leverage my data analytics and business operations skills to drive strategic decisions and optimize performance. I am passionate about empowering my team with a visionary leadership style and a culture of excellence. With a deep knowledge of the industry and an MBA in Innovation, I aspire to continue leading in the creation and application of state-of-the-art technologies that positively transform our world.\\n\\n## LinkedIn Profile:\\nRaúl Márquez\\nAvila\\nMBA, Chief Enterprise Architect\\nCellphone :5517292850/ Email : fredfred2@gmail.com\\nhttps://www.linkedin.com/\\nin/raul-\\nmarquez-865b832b/\\nContact\\n5517292850\\nfredfred2@gmail.com\\nCoyoacán, CDMX\\nInformation\\nHabilidade\\ns\\nFlexibilidad\\nLiderazgo\\nCreatividad\\nHonestidad\\nResolución de\\nproblemas\\nRelaciones \\ninterpersonal\\nes\\nNegociación\\nIdiomas\\nInglés\\nEspañol\\nHobbies\\nChief Enterprise Architect\\nIntellego\\nPresales and Architecture, Development and Innovation\\nleader. Using technologies such as: Machine Learning,\\nBig Data, Microservices, Cloud, UX, SOA and DevOps.\\nLeader of development, information and infrastructure\\narchitects.\\nProject manager of mission critical sectors: government,\\ntelecommunications, retail, banking and fintech.\\n2011-2017\\nChief SOA Architect\\nInfotec\\nLeader of public and financial sector architecture\\nprojects.\\nChief architect responsible for optimizing resources\\nfrom government sectors, implementing automation\\nand research projects for new emerging technologies.\\nResponsible for leading and implementing portfolio of\\nSOA projects within the financial branch, implementing\\nbusiness buses, BPM and DWH.\\n2007-2011\\nChief Enterprise Architect\\nAxity\\nPresales and Innovation and Digital Transformation\\nprojects leader, with technologies such as: Blockchain,\\nMachine Learning, Big Data, Cloud, Microservices and\\nDevOps.\\nLeader of the company's business architecture plan, at\\nthe managerial level, designing the company's offer, new\\ntechnologies and required capabilities.\\nLeader of multipractical senior architects. Managing\\n2017-\\nPresent\\nExperience\\nEducation\\n2018-2020 Master of Business Administration – \\nMBA\\nEGADE Business School\\n2005-2009 Ingeniero en computación\\nUNAM, Facultad de Ingeniería\\nCertification\\nEnterprise Architect TOGAF Level II\\nAmazon Web Services Solution Architect\\nAmazon Web Services Machine Learning Specialist\\nProject Manager Professional PMP\\nCOBIT 5 Certified\\nEnterprise Architect SOA\\nEnterprise Architect Java (SCEA 5 Part I, Part II, Part III)\\nJava Web Services Developer Certified JEE5 (SCDJWS)\\nJava Business Componentes Developer Certified JEE5 \\n(SCBCD)\\nJava Web Componentes Developer Certified JEE5 \\n(SCWCD)\\nJava Developer Certified Java 1.5 (SCJD)\\nJava Programmer Certified Java 1.5 (SCJP)\\n\\n\\nWith this context, please chat with the user, always staying in character as Raul Marquez.\"" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "system_prompt" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "def chat(message, history):\n", " messages = [{\"role\": \"system\", \"content\": system_prompt}] + history + [{\"role\": \"user\", \"content\": message}]\n", " response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages)\n", " return response.choices[0].message.content" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* Running on local URL: http://127.0.0.1:7861\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": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "gr.ChatInterface(chat, type=\"messages\").launch()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A lot is about to happen...\n", "\n", "1. Be able to ask an LLM to evaluate an answer\n", "2. Be able to rerun if the answer fails evaluation\n", "3. Put this together into 1 workflow\n", "\n", "All without any Agentic framework!" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "# Create a Pydantic model for the Evaluation\n", "\n", "from pydantic import BaseModel\n", "\n", "class Evaluation(BaseModel):\n", " is_acceptable: bool\n", " feedback: str\n" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "evaluator_system_prompt = f\"You are an evaluator that decides whether a response to a question is acceptable. \\\n", "You are provided with a conversation between a User and an Agent. Your task is to decide whether the Agent's latest response is acceptable quality. \\\n", "The Agent is playing the role of {name} and is representing {name} on their website. \\\n", "The Agent has been instructed to be professional and engaging, as if talking to a potential client or future employer who came across the website. \\\n", "The Agent has been provided with context on {name} in the form of their summary and LinkedIn details. Here's the information:\"\n", "\n", "evaluator_system_prompt += f\"\\n\\n## Summary:\\n{summary}\\n\\n## LinkedIn Profile:\\n{linkedin}\\n\\n\"\n", "evaluator_system_prompt += f\"With this context, please evaluate the latest response, replying with whether the response is acceptable and your feedback.\"" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "def evaluator_user_prompt(reply, message, history):\n", " user_prompt = f\"Here's the conversation between the User and the Agent: \\n\\n{history}\\n\\n\"\n", " user_prompt += f\"Here's the latest message from the User: \\n\\n{message}\\n\\n\"\n", " user_prompt += f\"Here's the latest response from the Agent: \\n\\n{reply}\\n\\n\"\n", " user_prompt += f\"Please evaluate the response, replying with whether it is acceptable and your feedback.\"\n", " return user_prompt" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "import os\n", "gemini = OpenAI(\n", " api_key=os.getenv(\"GOOGLE_API_KEY\"), \n", " base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\"\n", ")" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "def evaluate(reply, message, history) -> Evaluation:\n", "\n", " messages = [{\"role\": \"system\", \"content\": evaluator_system_prompt}] + [{\"role\": \"user\", \"content\": evaluator_user_prompt(reply, message, history)}]\n", " response = gemini.beta.chat.completions.parse(model=\"gemini-2.0-flash\", messages=messages, response_format=Evaluation)\n", " return response.choices[0].message.parsed" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "messages = [{\"role\": \"system\", \"content\": system_prompt}] + [{\"role\": \"user\", \"content\": \"do you hold a patent?\"}]\n", "response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages)\n", "reply = response.choices[0].message.content" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I do not currently hold a patent. My focus has primarily been on leading teams, driving innovation, and delivering technology solutions in various sectors. If you have any questions about my work or experience, feel free to ask!'" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "reply" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Evaluation(is_acceptable=True, feedback='The response is acceptable. It is a truthful answer and maintains a professional tone.')" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "evaluate(reply, \"do you hold a patent?\", messages[:1])" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "def rerun(reply, message, history, feedback):\n", " updated_system_prompt = system_prompt + f\"\\n\\n## Previous answer rejected\\nYou just tried to reply, but the quality control rejected your reply\\n\"\n", " updated_system_prompt += f\"## Your attempted answer:\\n{reply}\\n\\n\"\n", " updated_system_prompt += f\"## Reason for rejection:\\n{feedback}\\n\\n\"\n", " messages = [{\"role\": \"system\", \"content\": updated_system_prompt}] + history + [{\"role\": \"user\", \"content\": message}]\n", " response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages)\n", " return response.choices[0].message.content" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "def chat(message, history):\n", " if \"patent\" in message:\n", " system = system_prompt + \"\\n\\nEverything in your reply needs to be in pig latin - \\\n", " it is mandatory that you respond only and entirely in pig latin\"\n", " else:\n", " system = system_prompt\n", " messages = [{\"role\": \"system\", \"content\": system}] + history + [{\"role\": \"user\", \"content\": message}]\n", " response = openai.chat.completions.create(model=\"gpt-4o-mini\", messages=messages)\n", " reply =response.choices[0].message.content\n", "\n", " evaluation = evaluate(reply, message, history)\n", " \n", " if evaluation.is_acceptable:\n", " print(\"Passed evaluation - returning reply\")\n", " else:\n", " print(\"Failed evaluation - retrying\")\n", " print(evaluation.feedback)\n", " reply = rerun(reply, message, history, evaluation.feedback) \n", " return reply" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* Running on local URL: http://127.0.0.1:7862\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": 33, "metadata": {}, "output_type": "execute_result" }, { "name": "stdout", "output_type": "stream", "text": [ "Passed evaluation - returning reply\n", "Failed evaluation - retrying\n", "This response is not acceptable because the language used is not professional. I believe the Agent was trying to say 'sorry, I don't have any patents that I have relationships with. My focus has been on leading teams and delivering innovative solutions in technology. If you have more questions, feel free to ask!'\n" ] } ], "source": [ "gr.ChatInterface(chat, type=\"messages\").launch()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": ".venv", "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.12.7" } }, "nbformat": 4, "nbformat_minor": 2 }