Browse Source

finished week1

pull/286/head
Iryna 1 month ago
parent
commit
80af4c2c8a
  1. 321
      week1/day1.ipynb
  2. 3569
      week1/day5.ipynb
  3. 281
      week1/week1 EXERCISE.ipynb

321
week1/day1.ipynb

@ -90,7 +90,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 2,
"id": "4e2a9393-7767-488e-a8bf-27c12dca35bd", "id": "4e2a9393-7767-488e-a8bf-27c12dca35bd",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@ -129,10 +129,18 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 3,
"id": "7b87cadb-d513-4303-baee-a37b6f938e4d", "id": "7b87cadb-d513-4303-baee-a37b6f938e4d",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"API key found and looks good so far!\n"
]
}
],
"source": [ "source": [
"# Load environment variables in a file called .env\n", "# Load environment variables in a file called .env\n",
"\n", "\n",
@ -153,7 +161,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 4,
"id": "019974d9-f3ad-4a8a-b5f9-0a3719aea2d3", "id": "019974d9-f3ad-4a8a-b5f9-0a3719aea2d3",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@ -174,10 +182,18 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 5,
"id": "a58394bf-1e45-46af-9bfd-01e24da6f49a", "id": "a58394bf-1e45-46af-9bfd-01e24da6f49a",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello! Welcome! I'm glad you're here and I'm excited to chat with you. How can I assist you today?\n"
]
}
],
"source": [ "source": [
"# To give you a preview -- calling OpenAI with these messages is this easy. Any problems, head over to the Troubleshooting notebook.\n", "# To give you a preview -- calling OpenAI with these messages is this easy. Any problems, head over to the Troubleshooting notebook.\n",
"\n", "\n",
@ -196,7 +212,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 7,
"id": "c5e793b2-6775-426a-a139-4848291d0463", "id": "c5e793b2-6775-426a-a139-4848291d0463",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@ -226,10 +242,65 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 8,
"id": "2ef960cf-6dc2-4cda-afb3-b38be12f4c97", "id": "2ef960cf-6dc2-4cda-afb3-b38be12f4c97",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Home - Edward Donner\n",
"Home\n",
"Connect Four\n",
"Outsmart\n",
"An arena that pits LLMs against each other in a battle of diplomacy and deviousness\n",
"About\n",
"Posts\n",
"Well, hi there.\n",
"I’m Ed. I like writing code and experimenting with LLMs, and hopefully you’re here because you do too. I also enjoy DJing (but I’m badly out of practice), amateur electronic music production (\n",
"very\n",
"amateur) and losing myself in\n",
"Hacker News\n",
", nodding my head sagely to things I only half understand.\n",
"I’m the co-founder and CTO of\n",
"Nebula.io\n",
". We’re applying AI to a field where it can make a massive, positive impact: helping people discover their potential and pursue their reason for being. Recruiters use our product today to source, understand, engage and manage talent. I’m previously the founder and CEO of AI startup untapt,\n",
"acquired in 2021\n",
".\n",
"We work with groundbreaking, proprietary LLMs verticalized for talent, we’ve\n",
"patented\n",
"our matching model, and our award-winning platform has happy customers and tons of press coverage.\n",
"Connect\n",
"with me for more!\n",
"January 23, 2025\n",
"LLM Workshop – Hands-on with Agents – resources\n",
"December 21, 2024\n",
"Welcome, SuperDataScientists!\n",
"November 13, 2024\n",
"Mastering AI and LLM Engineering – Resources\n",
"October 16, 2024\n",
"From Software Engineer to AI Data Scientist – resources\n",
"Navigation\n",
"Home\n",
"Connect Four\n",
"Outsmart\n",
"An arena that pits LLMs against each other in a battle of diplomacy and deviousness\n",
"About\n",
"Posts\n",
"Get in touch\n",
"ed [at] edwarddonner [dot] com\n",
"www.edwarddonner.com\n",
"Follow me\n",
"LinkedIn\n",
"Twitter\n",
"Facebook\n",
"Subscribe to newsletter\n",
"Type your email…\n",
"Subscribe\n"
]
}
],
"source": [ "source": [
"# Let's try one out. Change the website and add print statements to follow along.\n", "# Let's try one out. Change the website and add print statements to follow along.\n",
"\n", "\n",
@ -258,7 +329,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 9,
"id": "abdb8417-c5dc-44bc-9bee-2e059d162699", "id": "abdb8417-c5dc-44bc-9bee-2e059d162699",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@ -272,7 +343,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 10,
"id": "f0275b1b-7cfe-4f9d-abfa-7650d378da0c", "id": "f0275b1b-7cfe-4f9d-abfa-7650d378da0c",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@ -290,10 +361,67 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 11,
"id": "26448ec4-5c00-4204-baec-7df91d11ff2e", "id": "26448ec4-5c00-4204-baec-7df91d11ff2e",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"You are looking at a website titled Home - Edward Donner\n",
"The contents of this website is as follows; please provide a short summary of this website in markdown. If it includes news or announcements, then summarize these too.\n",
"\n",
"Home\n",
"Connect Four\n",
"Outsmart\n",
"An arena that pits LLMs against each other in a battle of diplomacy and deviousness\n",
"About\n",
"Posts\n",
"Well, hi there.\n",
"I’m Ed. I like writing code and experimenting with LLMs, and hopefully you’re here because you do too. I also enjoy DJing (but I’m badly out of practice), amateur electronic music production (\n",
"very\n",
"amateur) and losing myself in\n",
"Hacker News\n",
", nodding my head sagely to things I only half understand.\n",
"I’m the co-founder and CTO of\n",
"Nebula.io\n",
". We’re applying AI to a field where it can make a massive, positive impact: helping people discover their potential and pursue their reason for being. Recruiters use our product today to source, understand, engage and manage talent. I’m previously the founder and CEO of AI startup untapt,\n",
"acquired in 2021\n",
".\n",
"We work with groundbreaking, proprietary LLMs verticalized for talent, we’ve\n",
"patented\n",
"our matching model, and our award-winning platform has happy customers and tons of press coverage.\n",
"Connect\n",
"with me for more!\n",
"January 23, 2025\n",
"LLM Workshop – Hands-on with Agents – resources\n",
"December 21, 2024\n",
"Welcome, SuperDataScientists!\n",
"November 13, 2024\n",
"Mastering AI and LLM Engineering – Resources\n",
"October 16, 2024\n",
"From Software Engineer to AI Data Scientist – resources\n",
"Navigation\n",
"Home\n",
"Connect Four\n",
"Outsmart\n",
"An arena that pits LLMs against each other in a battle of diplomacy and deviousness\n",
"About\n",
"Posts\n",
"Get in touch\n",
"ed [at] edwarddonner [dot] com\n",
"www.edwarddonner.com\n",
"Follow me\n",
"LinkedIn\n",
"Twitter\n",
"Facebook\n",
"Subscribe to newsletter\n",
"Type your email…\n",
"Subscribe\n"
]
}
],
"source": [ "source": [
"print(user_prompt_for(ed))" "print(user_prompt_for(ed))"
] ]
@ -319,7 +447,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 12,
"id": "f25dcd35-0cd0-4235-9f64-ac37ed9eaaa5", "id": "f25dcd35-0cd0-4235-9f64-ac37ed9eaaa5",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@ -332,10 +460,18 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 13,
"id": "21ed95c5-7001-47de-a36d-1d6673b403ce", "id": "21ed95c5-7001-47de-a36d-1d6673b403ce",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Oh, a math whiz in the making! The answer is 4. You're welcome.\n"
]
}
],
"source": [ "source": [
"# To give you a preview -- calling OpenAI with system and user messages:\n", "# To give you a preview -- calling OpenAI with system and user messages:\n",
"\n", "\n",
@ -353,7 +489,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 14,
"id": "0134dfa4-8299-48b5-b444-f2a8c3403c88", "id": "0134dfa4-8299-48b5-b444-f2a8c3403c88",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@ -369,10 +505,24 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 15,
"id": "36478464-39ee-485c-9f3f-6a4e458dbc9c", "id": "36478464-39ee-485c-9f3f-6a4e458dbc9c",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
{
"data": {
"text/plain": [
"[{'role': 'system',\n",
" 'content': 'You are an assistant that analyzes the contents of a website and provides a short summary, ignoring text that might be navigation related. Respond in markdown.'},\n",
" {'role': 'user',\n",
" 'content': 'You are looking at a website titled Home - Edward Donner\\nThe contents of this website is as follows; please provide a short summary of this website in markdown. If it includes news or announcements, then summarize these too.\\n\\nHome\\nConnect Four\\nOutsmart\\nAn arena that pits LLMs against each other in a battle of diplomacy and deviousness\\nAbout\\nPosts\\nWell, hi there.\\nI’m Ed. I like writing code and experimenting with LLMs, and hopefully you’re here because you do too. I also enjoy DJing (but I’m badly out of practice), amateur electronic music production (\\nvery\\namateur) and losing myself in\\nHacker News\\n, nodding my head sagely to things I only half understand.\\nI’m the co-founder and CTO of\\nNebula.io\\n. We’re applying AI to a field where it can make a massive, positive impact: helping people discover their potential and pursue their reason for being. Recruiters use our product today to source, understand, engage and manage talent. I’m previously the founder and CEO of AI startup untapt,\\nacquired in 2021\\n.\\nWe work with groundbreaking, proprietary LLMs verticalized for talent, we’ve\\npatented\\nour matching model, and our award-winning platform has happy customers and tons of press coverage.\\nConnect\\nwith me for more!\\nJanuary 23, 2025\\nLLM Workshop – Hands-on with Agents – resources\\nDecember 21, 2024\\nWelcome, SuperDataScientists!\\nNovember 13, 2024\\nMastering AI and LLM Engineering – Resources\\nOctober 16, 2024\\nFrom Software Engineer to AI Data Scientist – resources\\nNavigation\\nHome\\nConnect Four\\nOutsmart\\nAn arena that pits LLMs against each other in a battle of diplomacy and deviousness\\nAbout\\nPosts\\nGet in touch\\ned [at] edwarddonner [dot] com\\nwww.edwarddonner.com\\nFollow me\\nLinkedIn\\nTwitter\\nFacebook\\nSubscribe to newsletter\\nType your email…\\nSubscribe'}]"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [ "source": [
"# Try this out, and then try for a few more websites\n", "# Try this out, and then try for a few more websites\n",
"\n", "\n",
@ -389,7 +539,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 16,
"id": "905b9919-aba7-45b5-ae65-81b3d1d78e34", "id": "905b9919-aba7-45b5-ae65-81b3d1d78e34",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@ -407,10 +557,21 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 17,
"id": "05e38d41-dfa4-4b20-9c96-c46ea75d9fb5", "id": "05e38d41-dfa4-4b20-9c96-c46ea75d9fb5",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
{
"data": {
"text/plain": [
"\"# Summary of Edward Donner's Website\\n\\nEdward Donner's website serves as a personal platform where he shares his interests in coding, experimentation with Large Language Models (LLMs), and other hobbies including DJing and music production. As the co-founder and CTO of Nebula.io, he focuses on applying AI to enhance talent discovery and engagement. Previously, he founded the AI startup untapt, which was acquired in 2021. \\n\\nThe site features several posts with resources related to LLM workshops and AI engineering:\\n\\n- **January 23, 2025**: LLM Workshop – Hands-on with Agents – resources\\n- **December 21, 2024**: Welcome, SuperDataScientists!\\n- **November 13, 2024**: Mastering AI and LLM Engineering – Resources\\n- **October 16, 2024**: From Software Engineer to AI Data Scientist – resources\\n\\nThe content highlights his expertise and invites others to connect with him.\""
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [ "source": [
"summarize(\"https://edwarddonner.com\")" "summarize(\"https://edwarddonner.com\")"
] ]
@ -418,6 +579,14 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"id": "81079eca",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 18,
"id": "3d926d59-450e-4609-92ba-2d6f244f1342", "id": "3d926d59-450e-4609-92ba-2d6f244f1342",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@ -431,10 +600,33 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 19,
"id": "3018853a-445f-41ff-9560-d925d1774b2f", "id": "3018853a-445f-41ff-9560-d925d1774b2f",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
{
"data": {
"text/markdown": [
"# Summary of Edward Donner's Website\n",
"\n",
"Edward Donner's website showcases his passion for coding and experimentation with Large Language Models (LLMs). He is the co-founder and CTO of Nebula.io, a company focused on utilizing AI to help people discover their potential, particularly in the recruitment sector. Previously, he founded the AI startup untapt, which was acquired in 2021.\n",
"\n",
"## Recent Updates\n",
"- **January 23, 2025**: Resources for an LLM Workshop focused on hands-on experience with agents were made available.\n",
"- **December 21, 2024**: A welcoming message for \"SuperDataScientists\" was posted.\n",
"- **November 13, 2024**: Resources for \"Mastering AI and LLM Engineering\" were shared.\n",
"- **October 16, 2024**: Resources aimed at transitioning from software engineering to AI data science were released. \n",
"\n",
"Edward encourages connection and interaction regarding his work and interests in AI and LLMs."
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [ "source": [
"display_summary(\"https://edwarddonner.com\")" "display_summary(\"https://edwarddonner.com\")"
] ]
@ -457,22 +649,77 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 20,
"id": "45d83403-a24c-44b5-84ac-961449b4008f", "id": "45d83403-a24c-44b5-84ac-961449b4008f",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
{
"data": {
"text/markdown": [
"# Summary of CNN's Website Content\n",
"\n",
"The CNN website provides comprehensive coverage of breaking news in various categories, including U.S. and world news, politics, business, health, entertainment, sports, science, and climate. Key highlights include:\n",
"\n",
"### Current News and Updates:\n",
"- **Israel-Hamas War**: Palestinians have held significant anti-Hamas protests in Gaza.\n",
"- **Ukraine-Russia War**: Analysis of timelines regarding conflicts and strategies.\n",
"- **Trump Administration**: Multiple reports on lawsuits involving past cabinet members and legal issues arising from communications in group chats.\n",
"\n",
"### Notable Stories:\n",
"- A 93-year-old woman showcased a sharper cognitive ability than many younger individuals, explained by Dr. Sanjay Gupta.\n",
"- A doctor in Hawaii was arrested for attempting to harm his wife during a hiking trip.\n",
"- Former Brazilian President Bolsonaro is set to stand trial on coup charges, as judicial systems respond to the ongoing political turmoil in various regions.\n",
"\n",
"### Business News:\n",
"- Student loan delinquencies are projected to rise, potentially affecting over 9 million borrowers.\n",
"- Dollar Tree is discontinuing the Family Dollar brand after facing challenges with its integration.\n",
"\n",
"### Entertainment Highlights:\n",
"- Gwyneth Paltrow has addressed a social media feud concerning Meghan Markle.\n",
"- A newly opened restaurant concept in Scranton celebrates the popular show \"The Office\".\n",
"\n",
"### Sports Updates:\n",
"- Analysis on the latest trades and injuries affecting teams as different sports seasons progress.\n",
"\n",
"The site also features various multimedia options including live TV broadcasts, podcasts on a wide range of topics, and personalized content based on user engagement. CNN emphasizes its role as a leading source for in-depth reporting on critical global events and trends."
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [ "source": [
"display_summary(\"https://cnn.com\")" "display_summary(\"https://cnn.com\")"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 22,
"id": "75e9fd40-b354-4341-991e-863ef2e59db7", "id": "75e9fd40-b354-4341-991e-863ef2e59db7",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
"source": [ {
"display_summary(\"https://anthropic.com\")" "data": {
"text/markdown": [
"# Website Summary: Portfolio\n",
"\n",
"The website titled \"Portfolio\" appears to be a personal or professional showcase, but it cannot function properly without JavaScript enabled. As a result, no content beyond this notice can be accessed or summarized. \n",
"\n",
"No news or announcements are provided on the site."
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"display_summary(\"https://iryna-kryvokhyzha.netlify.app/\")"
] ]
}, },
{ {
@ -516,12 +763,20 @@
"source": [ "source": [
"# Step 1: Create your prompts\n", "# Step 1: Create your prompts\n",
"\n", "\n",
"system_prompt = \"something here\"\n", "system_prompt = \"You are an assistant that analyzes the contents of an email \\\n",
"and suggests an appropriate short subject line for the email. \\\n",
"Respond in markdown.\"\n",
"user_prompt = \"\"\"\n", "user_prompt = \"\"\"\n",
" Lots of text\n", " Lots of text\n",
" Can be pasted here\n", " Can be pasted here\n",
"\"\"\"\n", "\"\"\"\n",
"\n", "def user_prompt_for(website):\n",
" user_prompt = f\"You are looking at a website titled {website.title}\"\n",
" user_prompt += \"\\nThe contents of this website is as follows; \\\n",
"please provide a short summary of this website in markdown. \\\n",
"If it includes news or announcements, then summarize these too.\\n\\n\"\n",
" user_prompt += website.text\n",
" return user_prompt\n",
"# Step 2: Make the messages list\n", "# Step 2: Make the messages list\n",
"\n", "\n",
"messages = [] # fill this in\n", "messages = [] # fill this in\n",
@ -571,7 +826,7 @@
], ],
"metadata": { "metadata": {
"kernelspec": { "kernelspec": {
"display_name": "Python 3 (ipykernel)", "display_name": "llms",
"language": "python", "language": "python",
"name": "python3" "name": "python3"
}, },

3569
week1/day5.ipynb

File diff suppressed because one or more lines are too long

281
week1/week1 EXERCISE.ipynb

@ -13,25 +13,59 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 38,
"id": "c1070317-3ed9-4659-abe3-828943230e03", "id": "c1070317-3ed9-4659-abe3-828943230e03",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"# imports" "# imports\n",
"# If these fail, please check you're running from an 'activated' environment with (llms) in the command prompt\n",
"\n",
"import os\n",
"import json\n",
"import requests\n",
"from dotenv import load_dotenv\n",
"from openai import OpenAI\n",
"import ollama"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 41,
"id": "4a456906-915a-4bfd-bb9d-57e505c5093f", "id": "4a456906-915a-4bfd-bb9d-57e505c5093f",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"API key looks good so far\n"
]
}
],
"source": [ "source": [
"# constants\n", "# Initialize and constants\n",
"\n",
"# 📦 Load .env variables\n",
"load_dotenv(override=True)\n",
"# 🔐 Get OpenAI API key\n",
"api_key = os.getenv('OPENAI_API_KEY')\n",
"\n",
"if api_key and api_key.startswith('sk-proj-') and len(api_key)>10:\n",
" print(\"API key looks good so far\")\n",
"else:\n",
" print(\"There might be a problem with your API key? Please visit the troubleshooting notebook!\")\n",
" \n",
"\n", "\n",
"MODEL_GPT = 'gpt-4o-mini'\n", "MODEL_GPT = 'gpt-4o-mini'\n",
"MODEL_LLAMA = 'llama3.2'" "MODEL_LLAMA = 'llama3.2'\n",
"\n",
"system_prompt = (\n",
" \"You are a helpful assistant that explains technical concepts and code in a clear, simple way. \"\n",
" \"Use bullet points and code examples when relevant. Always aim to make it beginner-friendly.\"\n",
")\n",
"\n",
"openai = OpenAI()\n"
] ]
}, },
{ {
@ -41,48 +75,259 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"# set up environment" "# set up environment\n"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 36,
"id": "3f0d0137-52b0-47a8-81a8-11a90a010798", "id": "3f0d0137-52b0-47a8-81a8-11a90a010798",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"# here is the question; type over this to ask something new\n", "# here is the question; type over this to ask something new\n",
"\n", "\n",
"question = \"\"\"\n", "# question = \"\"\"\n",
"Please explain what this code does and why:\n", "# Please explain what this code does and why:\n",
"yield from {book.get(\"author\") for book in books if book.get(\"author\")}\n", "# yield from {book.get(\"author\") for book in books if book.get(\"author\")}\n",
"\"\"\"" "# \"\"\"\n",
"\n",
"question = \"Explain closures in JavaScript.\""
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 42,
"id": "fa823e81",
"metadata": {},
"outputs": [],
"source": [
"# messages\n",
"\n",
"messages = [\n",
" {\"role\": \"system\", \"content\": system_prompt},\n",
" {\"role\": \"user\", \"content\": question}\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": 43,
"id": "60ce7000-a4a5-4cce-a261-e75ef45063b4", "id": "60ce7000-a4a5-4cce-a261-e75ef45063b4",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"# Get gpt-4o-mini to answer, with streaming" "# Get gpt-4o-mini to answer, with streaming\n",
"def stream_gpt_answer(question):\n",
" stream = openai.chat.completions.create(\n",
" model=MODEL_GPT,\n",
" messages=messages,\n",
" stream=True\n",
" )\n",
" response = \"\"\n",
" display_handle = display(Markdown(\"\"), display_id=True)\n",
" for chunk in stream:\n",
" response += chunk.choices[0].delta.content or ''\n",
" response = response.replace(\"```\", \"\").replace(\"markdown\", \"\")\n",
" display_handle.update(Markdown(response))"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 44,
"id": "d6c1f1c6",
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"Certainly! Closures are a fundamental concept in JavaScript that can be a bit tricky to grasp at first, but they are very powerful. Here’s a simple breakdown:\n",
"\n",
"### What is a Closure?\n",
"\n",
"- A **closure** is a function that has access to its own scope, the scope of the outer function, and the global scope.\n",
"- This means a closure can \"remember\" the environment in which it was created, even after that environment has finished executing.\n",
"\n",
"### How Closures Work\n",
"\n",
"1. **Function Inside a Function**: When you define a function inside another function, the inner function forms a closure with the outer function.\n",
"2. **Access to Variables**: The inner function can access variables from the outer function (even after the outer function has executed).\n",
"3. **Preserving State**: Closures allow you to maintain state in asynchronous operations or when dealing with events.\n",
"\n",
"### Example of a Closure\n",
"\n",
"Here’s a simple code example to illustrate closures:\n",
"\n",
"javascript\n",
"function makeCounter() {\n",
" let count = 0; // This variable is private to makeCounter\n",
"\n",
" return function() { // This inner function is a closure\n",
" count += 1; // It can access the 'count' variable from the outer function\n",
" return count;\n",
" };\n",
"}\n",
"\n",
"const counter1 = makeCounter();\n",
"console.log(counter1()); // Output: 1\n",
"console.log(counter1()); // Output: 2\n",
"console.log(counter1()); // Output: 3\n",
"\n",
"const counter2 = makeCounter();\n",
"console.log(counter2()); // Output: 1 (This is independent of counter1)\n",
"\n",
"\n",
"### Breakdown of the Example\n",
"\n",
"- **Outer Function**: `makeCounter` defines a local variable `count`.\n",
"- **Inner Function**: The inner function (returned by `makeCounter`) is a closure that can access `count`.\n",
"- **Independence**: Each time you call `makeCounter`, it creates a new `count` variable, which means `counter1` and `counter2` maintain their own separate state.\n",
"\n",
"### Common Uses of Closures\n",
"\n",
"- **Data Privacy**: Encapsulating private data that cannot be accessed directly from outside the function.\n",
"- **Partial Applications**: Pre-filling some arguments of a function.\n",
"- **Callbacks**: Keeping track of variables in event handlers.\n",
"\n",
"### Key Points to Remember\n",
"\n",
"- Closures allow functions to maintain access to their lexical scope (the scope in which they were defined).\n",
"- They help to create functions with private variables that are not accessible from outside.\n",
"- Be mindful of memory usage; closures can lead to increased memory usage if not managed properly.\n",
"\n",
"### Conclusion\n",
"\n",
"Closures are an essential part of JavaScript that help create flexible and powerful programming patterns. Understanding them will improve your coding skills and help you write cleaner, more manageable code."
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"stream_gpt_answer(question)"
]
},
{
"cell_type": "code",
"execution_count": 45,
"id": "8f7c8ea8-4082-4ad0-8751-3301adcf6538", "id": "8f7c8ea8-4082-4ad0-8751-3301adcf6538",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
{
"data": {
"text/markdown": [
"**What is a Closure?**\n",
"\n",
"A closure is a fundamental concept in programming, particularly in functional programming languages like JavaScript. It's a function that has access to its own scope and the scope of its outer functions, even when the outer functions have returned.\n",
"\n",
"**Why do Closures Matter?**\n",
"\n",
"Closures are useful for several reasons:\n",
"\n",
"* **Private variables**: Closures allow you to create private variables (i.e., variables that are not accessible from outside the closure).\n",
"* **Function encapsulation**: Closures can be used to wrap a function and its related data, making it easier to reuse code.\n",
"* **Memory management**: Closures help manage memory by preventing functions from being garbage collected prematurely.\n",
"\n",
"**How do Closures Work?**\n",
"\n",
"A closure is created when a function is defined inside another function. When the inner function is called, it has access to the variables of its outer function's scope, including any arguments passed to the outer function.\n",
"\n",
"Here's an example:\n",
"```javascript\n",
"function outerFunction() {\n",
" let privateVariable = \"Hello, world!\";\n",
" \n",
" return function innerFunction() {\n",
" console.log(privateVariable); // prints: Hello, world!\n",
" console.log(this === outerFunction); // true\n",
" }\n",
"}\n",
"\n",
"const closure = outerFunction();\n",
"closure(); // logs: Hello, world!, then undefined\n",
"\n",
"// accessing the private variable using the closure:\n",
"console.log(closureprivateVariable); // \"Hello, world!\"\n",
"```\n",
"In this example:\n",
"\n",
"* `outerFunction` returns a new function (`innerFunction`) that has access to its own scope.\n",
"* `innerFunction` has access to `outerFunction`'s variables (including `privateVariable`).\n",
"* When the closure is called, it logs `privateVariable` and checks if it's equal to `outerFunction`.\n",
"\n",
"**Creating a Closure**\n",
"\n",
"To create a closure:\n",
"\n",
"1. Define an outer function.\n",
"2. Define an inner function inside the outer function.\n",
"3. Return the inner function from the outer function.\n",
"\n",
"Here's another example:\n",
"```javascript\n",
"function counter() {\n",
" let count = 0;\n",
" \n",
" return function() {\n",
" count += 1;\n",
" console.log(count); // prints: 1, then 2, etc.\n",
" }\n",
"}\n",
"\n",
"const increment = counter();\n",
"increment(); // logs: 1\n",
"increment(); // logs: 2\n",
"\n",
"// creating a new closure:\n",
"function nameGenerator(firstName, lastName) {\n",
" return function() {\n",
" console.log(`${firstName} ${lastName}`);\n",
" }\n",
"}\n",
"\n",
"const johnDoe = nameGenerator(\"John\", \"Doe\");\n",
"johnDoe(); // logs: John Doe\n",
"```\n",
"In this example:\n",
"\n",
"* `counter` is an outer function that returns a new inner function.\n",
"* The inner function increments a counter variable and logs its value.\n",
"* A new closure (`nameGenerator`) is created with two parameters (first name and last name).\n",
"\n",
"**Real-world Applications of Closures**\n",
"\n",
"Closures have many practical applications, such as:\n",
"\n",
"* **Data hiding**: Private variables within closures can prevent external interference.\n",
"* **Factory functions**: Closures can be used to create functions that produce different outputs based on input values.\n",
"* **Event listeners**: Closures help manage event listeners by preventing them from being garbage collected prematurely.\n",
"\n",
"By understanding and using closures effectively, you can write more modular, efficient, and maintainable code."
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [ "source": [
"# Get Llama 3.2 to answer" "# Get Llama 3.2 to answer\n",
"\n",
"response = ollama.chat(model=MODEL_LLAMA, messages=messages)\n",
"reply = response['message']['content']\n",
"display(Markdown(reply))"
] ]
} }
], ],
"metadata": { "metadata": {
"kernelspec": { "kernelspec": {
"display_name": "Python 3 (ipykernel)", "display_name": "llms",
"language": "python", "language": "python",
"name": "python3" "name": "python3"
}, },

Loading…
Cancel
Save