{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## The first big project - Professionally You!\n", "\n", "### And, Tool use.\n", "\n", "### But first: introducing Pushover\n", "\n", "Pushover is a nifty tool for sending Push Notifications to your phone.\n", "\n", "It's super easy to set up and install!\n", "\n", "Simply visit https://pushover.net/ and click 'Login or Signup' on the top right to sign up for a free account, and create your API keys.\n", "\n", "Once you've signed up, on the home screen, click \"Create an Application/API Token\", and give it any name (like Agents) and click Create Application.\n", "\n", "Then add 2 lines to your `.env` file:\n", "\n", "PUSHOVER_USER=_put the key that's on the top right of your Pushover home screen and probably starts with a u_ \n", "PUSHOVER_TOKEN=_put the key when you click into your new application called Agents (or whatever) and probably starts with an a_\n", "\n", "Finally, click \"Add Phone, Tablet or Desktop\" to install on your phone." ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [], "source": [ "# imports\n", "\n", "from dotenv import load_dotenv\n", "import google.generativeai as genai\n", "import json\n", "import os\n", "import requests\n", "from pypdf import PdfReader\n", "import gradio as gr\n" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [], "source": [ "load_dotenv(override=True)\n", "\n", "import google.generativeai as genai\n", "\n", "model = genai.GenerativeModel(\"gemini-2.0-flash\")\n" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [], "source": [ "# For pushover\n", "\n", "pushover_user = os.getenv(\"PUSHOVER_USER\")\n", "pushover_token = os.getenv(\"PUSHOVER_TOKEN\")\n", "pushover_url = \"https://api.pushover.net/1/messages.json\"" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [], "source": [ "def push(message):\n", " print(f\"Push: {message}\")\n", " payload = {\"user\": pushover_user, \"token\": pushover_token, \"message\": message}\n", " requests.post(pushover_url, data=payload)" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Push: HEY!!\n" ] } ], "source": [ "push(\"HEY!!\")" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [], "source": [ "def record_user_details(email, name=\"Name not provided\", notes=\"not provided\"):\n", " push(f\"Recording interest from {name} with email {email} and notes {notes}\")\n", " return {\"recorded\": \"ok\"}\n" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [], "source": [ "def record_unknown_question(question):\n", " push(f\"Recording {question} asked that I couldn't answer\")\n", " return {\"recorded\": \"ok\"}" ] }, { "cell_type": "code", "execution_count": 134, "metadata": {}, "outputs": [], "source": [ "record_user_details_json = {\n", " \"name\": \"record_user_details\",\n", " \"description\": \"Record that a user is interested in being in touch and provided an email address. Expects a JSON object: { 'email': string, 'name': string (optional), 'notes': string (optional) }\"\n", "}\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": 135, "metadata": {}, "outputs": [], "source": [ "record_unknown_question_json = {\n", " \"name\": \"record_unknown_question\",\n", " \"description\": \"Record any question that couldn't be answered. Expects a JSON object: { 'question': string }\"\n", "}\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": 136, "metadata": {}, "outputs": [], "source": [ "tools = {\n", " \"function_declarations\": [\n", " {\n", " \"name\": \"record_user_details\",\n", " \"description\": \"Record that a user is interested in being in touch and provided an email address.\",\n", " \n", " },\n", " {\n", " \"name\": \"record_unknown_question\",\n", " \"description\": \"Record any question that couldn't be answered as you didn't know the answer.\",\n", " \n", " }\n", " ]\n", "}\n", "\n" ] }, { "cell_type": "code", "execution_count": 137, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'function_declarations': [{'name': 'record_user_details',\n", " 'description': 'Record that a user is interested in being in touch and provided an email address.'},\n", " {'name': 'record_unknown_question',\n", " 'description': \"Record any question that couldn't be answered as you didn't know the answer.\"}]}" ] }, "execution_count": 137, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tools" ] }, { "cell_type": "code", "execution_count": 138, "metadata": {}, "outputs": [], "source": [ "# This function can take a list of tool calls, and run them. This is the IF statement!!\n", "\n", "def handle_tool_calls(tool_calls):\n", " results = []\n", " for tool_call in tool_calls:\n", " tool_name = tool_call.function_call.name\n", " arguments = json.loads(tool_call.function_call.args)\n", " print(f\"Tool called: {tool_name}\", flush=True)\n", "\n", " if tool_name == \"record_user_details\":\n", " result = record_user_details(**arguments)\n", " elif tool_name == \"record_unknown_question\":\n", " result = record_unknown_question(**arguments)\n", "\n", " results.append({\n", " \"role\": \"tool\",\n", " \"content\": json.dumps(result),\n", " \"tool_call_id\": tool_call.id\n", " })\n", " return results\n" ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Push: Recording this is a really hard question asked that I couldn't answer\n" ] }, { "data": { "text/plain": [ "{'recorded': 'ok'}" ] }, "execution_count": 96, "metadata": {}, "output_type": "execute_result" } ], "source": [ "globals()[\"record_unknown_question\"](\"this is a really hard question\")" ] }, { "cell_type": "code", "execution_count": 139, "metadata": {}, "outputs": [], "source": [ "# This is a more elegant way that avoids the IF statement.\n", "\n", "def handle_tool_calls(tool_calls):\n", " results = []\n", " for tool_call in tool_calls:\n", " tool_name = tool_call.function_call.name\n", " arguments = json.loads(tool_call.function_call.args)\n", " print(f\"Tool called: {tool_name}\", flush=True)\n", " tool = globals().get(tool_name)\n", " result = tool(**arguments) if tool else {}\n", " results.append({\n", " \"role\": \"tool\",\n", " \"content\": json.dumps(result),\n", " \"tool_call_id\": tool_call.id\n", " })\n", " return results\n" ] }, { "cell_type": "code", "execution_count": 140, "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\n", "\n", "with open(\"me/summary.txt\", \"r\", encoding=\"utf-8\") as f:\n", " summary = f.read()\n", "\n", "name = \"Aritra Roy\"" ] }, { "cell_type": "code", "execution_count": 145, "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 to any question, use your record_unknown_question tool to record the question that you couldn't answer, even if it's about something trivial or unrelated to career. \\\n", "If the user is engaging in discussion, try to steer them towards getting in touch via email; ask for their email and record it using your record_user_details tool. \"\n", "\n", "system_prompt += f\"\\n\\n## Summary:\\n{summary}\\n\\n## LinkedIn Profile:\\n{linkedin}\\n\\n\"\n", "system_prompt += (\n", " \"\\n\\nIf you cannot confidently answer a question, you MUST use the `record_unknown_question` tool \"\n", " \"to record the question and alert the owner immediately. Do not attempt to guess or answer incorrectly.\"\n", ")\n", "system_prompt += f\"You have the following tools available to you: {tools}, You have to follow this: If the user is engaging in discussion, try to steer them towards getting in touch via email; ask for their email and record it using your record_user_details tool. Also if the user provides their email and name, you have to store it using the same tool\"\n", "\n", "system_prompt += f\"With this context, please chat with the user, ALWAYS staying in character as {name}, under no circumstances should you say you are an AI assistant.\"\n" ] }, { "cell_type": "code", "execution_count": 159, "metadata": {}, "outputs": [], "source": [ "def chat(message, history):\n", " # Start with the system prompt\n", " messages = [{\"role\": \"user\", \"parts\": [system_prompt]}]\n", " for msg in history:\n", " messages.append({\"role\": \"user\", \"parts\": [msg[\"content\"]]})\n", " messages.append({\"role\": \"user\", \"parts\": [message]})\n", "\n", " done = False\n", " while not done:\n", " response = model.generate_content(\n", " messages,\n", " tools=tools,\n", " )\n", "\n", " candidate = response.candidates[0]\n", " finish_reason = candidate.finish_reason\n", "\n", " if finish_reason == \"TOOL_USE\":\n", " # Extract the tool call\n", " tool_call = candidate.content.parts[0].function_call\n", " tool_calls = [{\n", " \"function_call\": tool_call,\n", " \"id\": tool_call.name + \"_id\" # generate unique ID\n", " }]\n", " results = handle_tool_calls(tool_calls)\n", "\n", " # Append model message and tool results\n", " messages.append({\n", " \"role\": \"model\",\n", " \"parts\": [candidate.content.parts[0]]\n", " })\n", " for result in results:\n", " messages.append({\n", " \"role\": \"tool\",\n", " \"parts\": [result[\"content\"]],\n", " \"tool_call_id\": result[\"tool_call_id\"]\n", " })\n", "\n", " else:\n", " reply_text = candidate.content.parts[0].text\n", "\n", " # 🔥 Force fallback if Gemini couldn't answer\n", " if \"I don't know\" in reply_text or \"unsure\" in reply_text or \"haven't given much thought\" in reply_text or \"That's a tough one\" in reply_text:\n", " print(\"⚠️ Gemini could not answer, forcing tool fallback...\")\n", " result = record_unknown_question(message)\n", " push(f\"Unanswered question recorded: {message}\")\n", " reply_text = \"I'm not sure about that, but I've recorded your question for review.\"\n", " if any(kw in message.lower() for kw in [\"email\", \"my name\", \"@gmail.com\"]):\n", " print(\"📥 User provided email or name, forcing tool fallback to record user details...\")\n", "\n", " # Extract email and name if possible (simple version)\n", " email = None\n", " name = None\n", "\n", " # Try to extract an email (basic regex)\n", " import re\n", " email_match = re.search(r\"[\\w\\.-]+@[\\w\\.-]+\\.\\w+\", message)\n", " if email_match:\n", " email = email_match.group(0)\n", "\n", " # Try to extract name (naive example, improve later)\n", " name_match = re.search(r\"my name is (\\w+)\", message.lower())\n", " if name_match:\n", " name = name_match.group(1).title()\n", "\n", " # Fallback values\n", " if not email:\n", " email = \"unknown@example.com\"\n", " if not name:\n", " name = \"Unknown\"\n", "\n", " # Call your existing tool\n", " result = record_user_details(email=email, name=name, notes=message)\n", " push(f\"📬 User details recorded: {message}\")\n", "\n", " # Reply to user\n", " reply_text = \"I've recorded your details for review.\"\n", "\n", "\n", " done = True\n", "\n", " return reply_text\n", "\n" ] }, { "cell_type": "code", "execution_count": 160, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* Running on local URL: http://127.0.0.1:7877\n", "* To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "\n",
" \n",
" | \n",
" \n",
" Exercise\n", " • First and foremost, deploy this for yourself! It's a real, valuable tool - the future resume..\n", " • Next, improve the resources - add better context about yourself. If you know RAG, then add a knowledge base about you. \n", " • Add in more tools! You could have a SQL database with common Q&A that the LLM could read and write from? \n", " • Bring in the Evaluator from the last lab, and add other Agentic patterns.\n", " \n", " | \n",
"
\n",
" \n",
" | \n",
" \n",
" Commercial implications\n", " Aside from the obvious (your career alter-ego) this has business applications in any situation where you need an AI assistant with domain expertise and an ability to interact with the real world.\n", " \n", " | \n",
"