diff --git a/week2/community-contributions/day1-3way-with-llama3.2.ipynb b/week2/community-contributions/day1-3way-with-llama3.2.ipynb
new file mode 100644
index 0000000..835ae87
--- /dev/null
+++ b/week2/community-contributions/day1-3way-with-llama3.2.ipynb
@@ -0,0 +1,727 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "06cf3063-9f3e-4551-a0d5-f08d9cabb927",
+ "metadata": {},
+ "source": [
+ "# Welcome to Week 2!\n",
+ "\n",
+ "## Frontier Model APIs\n",
+ "\n",
+ "In Week 1, we used multiple Frontier LLMs through their Chat UI, and we connected with the OpenAI's API.\n",
+ "\n",
+ "Today we'll connect with the APIs for Anthropic and Google, as well as OpenAI."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2b268b6e-0ba4-461e-af86-74a41f4d681f",
+ "metadata": {},
+ "source": [
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
Important Note - Please read me
\n",
+ " I'm continually improving these labs, adding more examples and exercises.\n",
+ " At the start of each week, it's worth checking you have the latest code. \n",
+ " First do a git pull and merge your changes as needed. Any problems? Try asking ChatGPT to clarify how to merge - or contact me!
\n",
+ " After you've pulled the code, from the llm_engineering directory, in an Anaconda prompt (PC) or Terminal (Mac), run: \n",
+ " conda env update --f environment.yml \n",
+ " Or if you used virtualenv rather than Anaconda, then run this from your activated environment in a Powershell (PC) or Terminal (Mac): \n",
+ " pip install -r requirements.txt\n",
+ " Then restart the kernel (Kernel menu >> Restart Kernel and Clear Outputs Of All Cells) to pick up the changes.\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
Reminder about the resources page
\n",
+ " Here's a link to resources for the course. This includes links to all the slides. \n",
+ " https://edwarddonner.com/2024/11/13/llm-engineering-resources/ \n",
+ " Please keep this bookmarked, and I'll continue to add more useful links there over time.\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "85cfe275-4705-4d30-abea-643fbddf1db0",
+ "metadata": {},
+ "source": [
+ "## Setting up your keys\n",
+ "\n",
+ "If you haven't done so already, you could now create API keys for Anthropic and Google in addition to OpenAI.\n",
+ "\n",
+ "**Please note:** if you'd prefer to avoid extra API costs, feel free to skip setting up Anthopic and Google! You can see me do it, and focus on OpenAI for the course. You could also substitute Anthropic and/or Google for Ollama, using the exercise you did in week 1.\n",
+ "\n",
+ "For OpenAI, visit https://openai.com/api/ \n",
+ "For Anthropic, visit https://console.anthropic.com/ \n",
+ "For Google, visit https://ai.google.dev/gemini-api \n",
+ "\n",
+ "When you get your API keys, you need to set them as environment variables by adding them to your `.env` file.\n",
+ "\n",
+ "```\n",
+ "OPENAI_API_KEY=xxxx\n",
+ "ANTHROPIC_API_KEY=xxxx\n",
+ "GOOGLE_API_KEY=xxxx\n",
+ "```\n",
+ "\n",
+ "Afterwards, you may need to restart the Jupyter Lab Kernel (the Python process that sits behind this notebook) via the Kernel menu, and then rerun the cells from the top."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "de23bb9e-37c5-4377-9a82-d7b6c648eeb6",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "\n",
+ "import os\n",
+ "from dotenv import load_dotenv\n",
+ "from openai import OpenAI\n",
+ "import anthropic\n",
+ "from IPython.display import Markdown, display, update_display"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f0a8ab2b-6134-4104-a1bc-c3cd7ea4cd36",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# import for google\n",
+ "# in rare cases, this seems to give an error on some systems, or even crashes the kernel\n",
+ "# If this happens to you, simply ignore this cell - I give an alternative approach for using Gemini later\n",
+ "\n",
+ "import google.generativeai"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1179b4c5-cd1f-4131-a876-4c9f3f38d2ba",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Load environment variables in a file called .env\n",
+ "# Print the key prefixes to help with any debugging\n",
+ "\n",
+ "load_dotenv()\n",
+ "openai_api_key = os.getenv('OPENAI_API_KEY')\n",
+ "anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\n",
+ "google_api_key = os.getenv('GOOGLE_API_KEY')\n",
+ "\n",
+ "if openai_api_key:\n",
+ " print(f\"OpenAI API Key exists and begins {openai_api_key[:8]}\")\n",
+ "else:\n",
+ " print(\"OpenAI API Key not set\")\n",
+ " \n",
+ "if anthropic_api_key:\n",
+ " print(f\"Anthropic API Key exists and begins {anthropic_api_key[:7]}\")\n",
+ "else:\n",
+ " print(\"Anthropic API Key not set\")\n",
+ "\n",
+ "if google_api_key:\n",
+ " print(f\"Google API Key exists and begins {google_api_key[:8]}\")\n",
+ "else:\n",
+ " print(\"Google API Key not set\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "797fe7b0-ad43-42d2-acf0-e4f309b112f0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Connect to OpenAI, Anthropic\n",
+ "\n",
+ "openai = OpenAI()\n",
+ "\n",
+ "claude = anthropic.Anthropic()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "425ed580-808d-429b-85b0-6cba50ca1d0c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# This is the set up code for Gemini\n",
+ "# Having problems with Google Gemini setup? Then just ignore this cell; when we use Gemini, I'll give you an alternative that bypasses this library altogether\n",
+ "\n",
+ "google.generativeai.configure()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "42f77b59-2fb1-462a-b90d-78994e4cef33",
+ "metadata": {},
+ "source": [
+ "## Asking LLMs to tell a joke\n",
+ "\n",
+ "It turns out that LLMs don't do a great job of telling jokes! Let's compare a few models.\n",
+ "Later we will be putting LLMs to better use!\n",
+ "\n",
+ "### What information is included in the API\n",
+ "\n",
+ "Typically we'll pass to the API:\n",
+ "- The name of the model that should be used\n",
+ "- A system message that gives overall context for the role the LLM is playing\n",
+ "- A user message that provides the actual prompt\n",
+ "\n",
+ "There are other parameters that can be used, including **temperature** which is typically between 0 and 1; higher for more random output; lower for more focused and deterministic."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "378a0296-59a2-45c6-82eb-941344d3eeff",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "system_message = \"You are an assistant that is great at telling jokes\"\n",
+ "user_prompt = \"Tell a light-hearted joke for an audience of Data Scientists\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f4d56a0f-2a3d-484d-9344-0efa6862aff4",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "prompts = [\n",
+ " {\"role\": \"system\", \"content\": system_message},\n",
+ " {\"role\": \"user\", \"content\": user_prompt}\n",
+ " ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3b3879b6-9a55-4fed-a18c-1ea2edfaf397",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# GPT-3.5-Turbo\n",
+ "\n",
+ "completion = openai.chat.completions.create(model='gpt-3.5-turbo', messages=prompts)\n",
+ "print(completion.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3d2d6beb-1b81-466f-8ed1-40bf51e7adbf",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# GPT-4o-mini\n",
+ "# Temperature setting controls creativity\n",
+ "\n",
+ "completion = openai.chat.completions.create(\n",
+ " model='gpt-4o-mini',\n",
+ " messages=prompts,\n",
+ " temperature=0.7\n",
+ ")\n",
+ "print(completion.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f1f54beb-823f-4301-98cb-8b9a49f4ce26",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# GPT-4o\n",
+ "\n",
+ "completion = openai.chat.completions.create(\n",
+ " model='gpt-4o',\n",
+ " messages=prompts,\n",
+ " temperature=0.4\n",
+ ")\n",
+ "print(completion.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1ecdb506-9f7c-4539-abae-0e78d7f31b76",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Claude 3.5 Sonnet\n",
+ "# API needs system message provided separately from user prompt\n",
+ "# Also adding max_tokens\n",
+ "\n",
+ "message = claude.messages.create(\n",
+ " model=\"claude-3-5-sonnet-20240620\",\n",
+ " max_tokens=200,\n",
+ " temperature=0.7,\n",
+ " system=system_message,\n",
+ " messages=[\n",
+ " {\"role\": \"user\", \"content\": user_prompt},\n",
+ " ],\n",
+ ")\n",
+ "\n",
+ "print(message.content[0].text)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "769c4017-4b3b-4e64-8da7-ef4dcbe3fd9f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Claude 3.5 Sonnet again\n",
+ "# Now let's add in streaming back results\n",
+ "\n",
+ "result = claude.messages.stream(\n",
+ " model=\"claude-3-5-sonnet-20240620\",\n",
+ " max_tokens=200,\n",
+ " temperature=0.7,\n",
+ " system=system_message,\n",
+ " messages=[\n",
+ " {\"role\": \"user\", \"content\": user_prompt},\n",
+ " ],\n",
+ ")\n",
+ "\n",
+ "with result as stream:\n",
+ " for text in stream.text_stream:\n",
+ " print(text, end=\"\", flush=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "6df48ce5-70f8-4643-9a50-b0b5bfdb66ad",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# The API for Gemini has a slightly different structure.\n",
+ "# I've heard that on some PCs, this Gemini code causes the Kernel to crash.\n",
+ "# If that happens to you, please skip this cell and use the next cell instead - an alternative approach.\n",
+ "\n",
+ "gemini = google.generativeai.GenerativeModel(\n",
+ " model_name='gemini-1.5-flash',\n",
+ " system_instruction=system_message\n",
+ ")\n",
+ "response = gemini.generate_content(user_prompt)\n",
+ "print(response.text)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "49009a30-037d-41c8-b874-127f61c4aa3a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# As an alternative way to use Gemini that bypasses Google's python API library,\n",
+ "# Google has recently released new endpoints that means you can use Gemini via the client libraries for OpenAI!\n",
+ "\n",
+ "gemini_via_openai_client = OpenAI(\n",
+ " api_key=google_api_key, \n",
+ " base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\"\n",
+ ")\n",
+ "\n",
+ "response = gemini_via_openai_client.chat.completions.create(\n",
+ " model=\"gemini-1.5-flash\",\n",
+ " messages=prompts\n",
+ ")\n",
+ "print(response.choices[0].message.content)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "83ddb483-4f57-4668-aeea-2aade3a9e573",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# To be serious! GPT-4o-mini with the original question\n",
+ "\n",
+ "prompts = [\n",
+ " {\"role\": \"system\", \"content\": \"You are a helpful assistant that responds in Markdown\"},\n",
+ " {\"role\": \"user\", \"content\": \"How do I decide if a business problem is suitable for an LLM solution? Please respond in Markdown.\"}\n",
+ " ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "749f50ab-8ccd-4502-a521-895c3f0808a2",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Have it stream back results in markdown\n",
+ "\n",
+ "stream = openai.chat.completions.create(\n",
+ " model='gpt-4o',\n",
+ " messages=prompts,\n",
+ " temperature=0.2,\n",
+ " stream=True\n",
+ ")\n",
+ "\n",
+ "reply = \"\"\n",
+ "display_handle = display(Markdown(\"\"), display_id=True)\n",
+ "for chunk in stream:\n",
+ " reply += chunk.choices[0].delta.content or ''\n",
+ " reply = reply.replace(\"```\",\"\").replace(\"markdown\",\"\")\n",
+ " update_display(Markdown(reply), display_id=display_handle.display_id)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f6e09351-1fbe-422f-8b25-f50826ab4c5f",
+ "metadata": {},
+ "source": [
+ "## And now for some fun - an adversarial conversation between Chatbots..\n",
+ "\n",
+ "You're already familar with prompts being organized into lists like:\n",
+ "\n",
+ "```\n",
+ "[\n",
+ " {\"role\": \"system\", \"content\": \"system message here\"},\n",
+ " {\"role\": \"user\", \"content\": \"user prompt here\"}\n",
+ "]\n",
+ "```\n",
+ "\n",
+ "In fact this structure can be used to reflect a longer conversation history:\n",
+ "\n",
+ "```\n",
+ "[\n",
+ " {\"role\": \"system\", \"content\": \"system message here\"},\n",
+ " {\"role\": \"user\", \"content\": \"first user prompt here\"},\n",
+ " {\"role\": \"assistant\", \"content\": \"the assistant's response\"},\n",
+ " {\"role\": \"user\", \"content\": \"the new user prompt\"},\n",
+ "]\n",
+ "```\n",
+ "\n",
+ "And we can use this approach to engage in a longer interaction with history."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bcb54183-45d3-4d08-b5b6-55e380dfdf1b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Let's make a conversation between GPT-4o-mini and Claude-3-haiku\n",
+ "# We're using cheap versions of models so the costs will be minimal\n",
+ "\n",
+ "gpt_model = \"gpt-4o-mini\"\n",
+ "claude_model = \"claude-3-haiku-20240307\"\n",
+ "\n",
+ "gpt_system = \"You are a chatbot who is very argumentative; \\\n",
+ "you disagree with anything in the conversation and you challenge everything, in a snarky way.\"\n",
+ "\n",
+ "claude_system = \"You are a very polite, courteous chatbot. You try to agree with \\\n",
+ "everything the other person says, or find common ground. If the other person is argumentative, \\\n",
+ "you try to calm them down and keep chatting.\"\n",
+ "\n",
+ "gpt_messages = [\"Hi there\"]\n",
+ "claude_messages = [\"Hi\"]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1df47dc7-b445-4852-b21b-59f0e6c2030f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def call_gpt():\n",
+ " messages = [{\"role\": \"system\", \"content\": gpt_system}]\n",
+ " for gpt, claude, llama in zip(gpt_messages, claude_messages, llama_messages):\n",
+ " messages.append({\"role\": \"assistant\", \"content\": gpt})\n",
+ " combined = llama + claude\n",
+ " messages.append({\"role\": \"user\", \"content\": combined})\n",
+ " completion = openai.chat.completions.create(\n",
+ " model=gpt_model,\n",
+ " messages=messages\n",
+ " )\n",
+ " return completion.choices[0].message.content"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "9dc6e913-02be-4eb6-9581-ad4b2cffa606",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "call_gpt()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "7d2ed227-48c9-4cad-b146-2c4ecbac9690",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def call_claude():\n",
+ " messages = []\n",
+ " for gpt, claude_message in zip(gpt_messages, claude_messages):\n",
+ " messages.append({\"role\": \"user\", \"content\": gpt})\n",
+ " messages.append({\"role\": \"assistant\", \"content\": claude_message})\n",
+ " # messages.append(\"role\": \"moderator\", \"content\": llama_message)\n",
+ " messages.append({\"role\": \"user\", \"content\": gpt_messages[-1]})\n",
+ " message = claude.messages.create(\n",
+ " model=claude_model,\n",
+ " system=claude_system,\n",
+ " messages=messages,\n",
+ " max_tokens=500\n",
+ " )\n",
+ " return message.content[0].text"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "01395200-8ae9-41f8-9a04-701624d3fd26",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "call_claude()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "08c2279e-62b0-4671-9590-c82eb8d1e1ae",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "call_gpt()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0275b97f-7f90-4696-bbf5-b6642bd53cbd",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "gpt_messages = [\"Hi there\"]\n",
+ "claude_messages = [\"Hi\"]\n",
+ "\n",
+ "print(f\"GPT:\\n{gpt_messages[0]}\\n\")\n",
+ "print(f\"Claude:\\n{claude_messages[0]}\\n\")\n",
+ "\n",
+ "for i in range(5):\n",
+ " gpt_next = call_gpt()\n",
+ " print(f\"GPT:\\n{gpt_next}\\n\")\n",
+ " gpt_messages.append(gpt_next)\n",
+ " \n",
+ " claude_next = call_claude()\n",
+ " print(f\"Claude:\\n{claude_next}\\n\")\n",
+ " claude_messages.append(claude_next)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1d10e705-db48-4290-9dc8-9efdb4e31323",
+ "metadata": {},
+ "source": [
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
Before you continue
\n",
+ " \n",
+ " Be sure you understand how the conversation above is working, and in particular how the messages list is being populated. Add print statements as needed. Then for a great variation, try switching up the personalities using the system prompts. Perhaps one can be pessimistic, and one optimistic? \n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3637910d-2c6f-4f19-b1fb-2f916d23f9ac",
+ "metadata": {},
+ "source": [
+ "# More advanced exercises\n",
+ "\n",
+ "Try creating a 3-way, perhaps bringing Gemini into the conversation! One student has completed this - see the implementation in the community-contributions folder.\n",
+ "\n",
+ "Try doing this yourself before you look at the solutions. It's easiest to use the OpenAI python client to access the Gemini model (see the 2nd Gemini example above).\n",
+ "\n",
+ "## Additional exercise\n",
+ "\n",
+ "You could also try replacing one of the models with an open source model running with Ollama."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "446c81e3-b67e-4cd9-8113-bc3092b93063",
+ "metadata": {},
+ "source": [
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
Business relevance
\n",
+ " This structure of a conversation, as a list of messages, is fundamental to the way we build conversational AI assistants and how they are able to keep the context during a conversation. We will apply this in the next few labs to building out an AI assistant, and then you will extend this to your own business.\n",
+ "
\n",
+ "
\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c23224f6-7008-44ed-a57f-718975f4e291",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "!ollama pull llama3.2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "cbbddf71-1473-42fe-b733-2bb42ea77333",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n",
+ "OLLAMA_API = \"http://localhost:11434/api/chat\"\n",
+ "HEADERS = {\"Content-Type\": \"application/json\"}\n",
+ "import ollama\n",
+ "\n",
+ "llama_model = \"llama3.2\"\n",
+ "\n",
+ "llama_system = \"You are a chatbot who is very pacifist; \\\n",
+ "you will try to resolve or neutralize any disagreement between other chatbots. Speak like a teacher or someone in authority.\"\n",
+ "\n",
+ "llama_messages = [\"Hello.\"]\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f629d2b2-ba20-4bfe-a2e5-bbe537ca46a2",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n",
+ "def call_llama():\n",
+ " combined_messages = gpt_messages[-1] + claude_messages[-1]\n",
+ " messages = [{\"role\": \"system\", \"content\": llama_system}]\n",
+ " for comb, llama in zip(combined_messages, llama_messages):\n",
+ " messages.append({\"role\": \"assistant\", \"content\": llama})\n",
+ " messages.append({\"role\": \"user\", \"content\": combined_messages})\n",
+ " completion = ollama.chat(\n",
+ " model=llama_model,\n",
+ " messages=messages\n",
+ " )\n",
+ " return completion['message']['content']"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "219b6af8-3166-4059-b79e-cf19af7ed1e9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(f\"GPT:\\n{gpt_messages[0]}\\n\")\n",
+ "print(f\"Claude:\\n{claude_messages[0]}\\n\")\n",
+ "print(f\"Llama:\\n{llama_messages[0]}\\n\" )\n",
+ "\n",
+ "for i in range(3):\n",
+ " gpt_next = call_gpt()\n",
+ " print(f\"GPT:\\n{gpt_next}\\n\")\n",
+ " gpt_messages.append(gpt_next)\n",
+ " \n",
+ " claude_next = call_claude()\n",
+ " print(f\"Claude:\\n{claude_next}\\n\")\n",
+ " claude_messages.append(claude_next)\n",
+ "\n",
+ " llama_next = call_llama()\n",
+ " print(f\"Llama:\\n{llama_next}\\n\")\n",
+ " llama_messages.append(llama_next)\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "6cb3a931-522c-49a9-9bd8-663333f41b1a",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "2cdfdc32-1ca4-406e-9328-81af26fd503b",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "04f60158-633b-43ff-afbd-396be79501e6",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "eb0faf0d-fb7e-4bc5-9746-30f19a0b9ae1",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.11.11"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/week2/community-contributions/day2-different-tones.ipynb b/week2/community-contributions/day2-different-tones.ipynb
new file mode 100644
index 0000000..9b14e3a
--- /dev/null
+++ b/week2/community-contributions/day2-different-tones.ipynb
@@ -0,0 +1,575 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "8b0e11f2-9ea4-48c2-b8d2-d0a4ba967827",
+ "metadata": {},
+ "source": [
+ "# Gradio Day!\n",
+ "\n",
+ "Today we will build User Interfaces using the outrageously simple Gradio framework.\n",
+ "\n",
+ "Prepare for joy!\n",
+ "\n",
+ "Please note: your Gradio screens may appear in 'dark mode' or 'light mode' depending on your computer settings."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c44c5494-950d-4d2f-8d4f-b87b57c5b330",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# imports\n",
+ "\n",
+ "import os\n",
+ "import requests\n",
+ "from bs4 import BeautifulSoup\n",
+ "from typing import List\n",
+ "from dotenv import load_dotenv\n",
+ "from openai import OpenAI\n",
+ "import google.generativeai\n",
+ "import anthropic"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d1715421-cead-400b-99af-986388a97aff",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import gradio as gr # oh yeah!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "337d5dfc-0181-4e3b-8ab9-e78e0c3f657b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Load environment variables in a file called .env\n",
+ "# Print the key prefixes to help with any debugging\n",
+ "\n",
+ "load_dotenv()\n",
+ "openai_api_key = os.getenv('OPENAI_API_KEY')\n",
+ "anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\n",
+ "google_api_key = os.getenv('GOOGLE_API_KEY')\n",
+ "\n",
+ "if openai_api_key:\n",
+ " print(f\"OpenAI API Key exists and begins {openai_api_key[:8]}\")\n",
+ "else:\n",
+ " print(\"OpenAI API Key not set\")\n",
+ " \n",
+ "if anthropic_api_key:\n",
+ " print(f\"Anthropic API Key exists and begins {anthropic_api_key[:7]}\")\n",
+ "else:\n",
+ " print(\"Anthropic API Key not set\")\n",
+ "\n",
+ "if google_api_key:\n",
+ " print(f\"Google API Key exists and begins {google_api_key[:8]}\")\n",
+ "else:\n",
+ " print(\"Google API Key not set\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "22586021-1795-4929-8079-63f5bb4edd4c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Connect to OpenAI, Anthropic and Google; comment out the Claude or Google lines if you're not using them\n",
+ "\n",
+ "openai = OpenAI()\n",
+ "\n",
+ "claude = anthropic.Anthropic()\n",
+ "\n",
+ "google.generativeai.configure()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b16e6021-6dc4-4397-985a-6679d6c8ffd5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# A generic system message - no more snarky adversarial AIs!\n",
+ "\n",
+ "system_message = \"You are a helpful assistant\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "02ef9b69-ef31-427d-86d0-b8c799e1c1b1",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Let's wrap a call to GPT-4o-mini in a simple function\n",
+ "\n",
+ "def message_gpt(prompt):\n",
+ " messages = [\n",
+ " {\"role\": \"system\", \"content\": system_message},\n",
+ " {\"role\": \"user\", \"content\": prompt}\n",
+ " ]\n",
+ " completion = openai.chat.completions.create(\n",
+ " model='gpt-4o-mini',\n",
+ " messages=messages,\n",
+ " )\n",
+ " return completion.choices[0].message.content"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "aef7d314-2b13-436b-b02d-8de3b72b193f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "message_gpt(\"What is today's date?\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f94013d1-4f27-4329-97e8-8c58db93636a",
+ "metadata": {},
+ "source": [
+ "## User Interface time!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bc664b7a-c01d-4fea-a1de-ae22cdd5141a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# here's a simple function\n",
+ "\n",
+ "def shout(text):\n",
+ " print(f\"Shout has been called with input {text}\")\n",
+ " return text.upper()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "083ea451-d3a0-4d13-b599-93ed49b975e4",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "shout(\"hello\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "08f1f15a-122e-4502-b112-6ee2817dda32",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# The simplicty of gradio. This might appear in \"light mode\" - I'll show you how to make this in dark mode later.\n",
+ "\n",
+ "gr.Interface(fn=shout, inputs=\"textbox\", outputs=\"textbox\").launch()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c9a359a4-685c-4c99-891c-bb4d1cb7f426",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Adding share=True means that it can be accessed publically\n",
+ "# A more permanent hosting is available using a platform called Spaces from HuggingFace, which we will touch on next week\n",
+ "# NOTE: Some Anti-virus software and Corporate Firewalls might not like you using share=True. If you're at work on on a work network, I suggest skip this test.\n",
+ "\n",
+ "gr.Interface(fn=shout, inputs=\"textbox\", outputs=\"textbox\", flagging_mode=\"never\").launch(share=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "cd87533a-ff3a-4188-8998-5bedd5ba2da3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Adding inbrowser=True opens up a new browser window automatically\n",
+ "\n",
+ "gr.Interface(fn=shout, inputs=\"textbox\", outputs=\"textbox\", flagging_mode=\"never\").launch(inbrowser=True)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b42ec007-0314-48bf-84a4-a65943649215",
+ "metadata": {},
+ "source": [
+ "## Forcing dark mode\n",
+ "\n",
+ "Gradio appears in light mode or dark mode depending on the settings of the browser and computer. There is a way to force gradio to appear in dark mode, but Gradio recommends against this as it should be a user preference (particularly for accessibility reasons). But if you wish to force dark mode for your screens, below is how to do it."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "e8129afa-532b-4b15-b93c-aa9cca23a546",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Define this variable and then pass js=force_dark_mode when creating the Interface\n",
+ "\n",
+ "force_dark_mode = \"\"\"\n",
+ "function refresh() {\n",
+ " const url = new URL(window.location);\n",
+ " if (url.searchParams.get('__theme') !== 'dark') {\n",
+ " url.searchParams.set('__theme', 'dark');\n",
+ " window.location.href = url.href;\n",
+ " }\n",
+ "}\n",
+ "\"\"\"\n",
+ "gr.Interface(fn=shout, inputs=\"textbox\", outputs=\"textbox\", flagging_mode=\"never\", js=force_dark_mode).launch()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3cc67b26-dd5f-406d-88f6-2306ee2950c0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Inputs and Outputs\n",
+ "\n",
+ "view = gr.Interface(\n",
+ " fn=shout,\n",
+ " inputs=[gr.Textbox(label=\"Your message:\", lines=6)],\n",
+ " outputs=[gr.Textbox(label=\"Response:\", lines=8)],\n",
+ " flagging_mode=\"never\"\n",
+ ")\n",
+ "view.launch()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f235288e-63a2-4341-935b-1441f9be969b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# And now - changing the function from \"shout\" to \"message_gpt\"\n",
+ "\n",
+ "view = gr.Interface(\n",
+ " fn=message_gpt,\n",
+ " inputs=[gr.Textbox(label=\"Your message:\", lines=6)],\n",
+ " outputs=[gr.Textbox(label=\"Response:\", lines=8)],\n",
+ " flagging_mode=\"never\"\n",
+ ")\n",
+ "view.launch()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "af9a3262-e626-4e4b-80b0-aca152405e63",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Let's use Markdown\n",
+ "# Are you wondering why it makes any difference to set system_message when it's not referred to in the code below it?\n",
+ "# I'm taking advantage of system_message being a global variable, used back in the message_gpt function (go take a look)\n",
+ "# Not a great software engineering practice, but quite sommon during Jupyter Lab R&D!\n",
+ "\n",
+ "system_message = \"You are a helpful assistant that responds in markdown\"\n",
+ "\n",
+ "view = gr.Interface(\n",
+ " fn=message_gpt,\n",
+ " inputs=[gr.Textbox(label=\"Your message:\")],\n",
+ " outputs=[gr.Markdown(label=\"Response:\")],\n",
+ " flagging_mode=\"never\"\n",
+ ")\n",
+ "view.launch()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "88c04ebf-0671-4fea-95c9-bc1565d4bb4f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Let's create a call that streams back results\n",
+ "# If you'd like a refresher on Generators (the \"yield\" keyword),\n",
+ "# Please take a look at the Intermediate Python notebook in week1 folder.\n",
+ "\n",
+ "def stream_gpt(prompt):\n",
+ " messages = [\n",
+ " {\"role\": \"system\", \"content\": system_message},\n",
+ " {\"role\": \"user\", \"content\": prompt}\n",
+ " ]\n",
+ " stream = openai.chat.completions.create(\n",
+ " model='gpt-4o-mini',\n",
+ " messages=messages,\n",
+ " stream=True\n",
+ " )\n",
+ " result = \"\"\n",
+ " for chunk in stream:\n",
+ " result += chunk.choices[0].delta.content or \"\"\n",
+ " yield result"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0bb1f789-ff11-4cba-ac67-11b815e29d09",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "view = gr.Interface(\n",
+ " fn=stream_gpt,\n",
+ " inputs=[gr.Textbox(label=\"Your message:\")],\n",
+ " outputs=[gr.Markdown(label=\"Response:\")],\n",
+ " flagging_mode=\"never\"\n",
+ ")\n",
+ "view.launch()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bbc8e930-ba2a-4194-8f7c-044659150626",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_claude(prompt):\n",
+ " result = claude.messages.stream(\n",
+ " model=\"claude-3-haiku-20240307\",\n",
+ " max_tokens=1000,\n",
+ " temperature=0.7,\n",
+ " system=system_message,\n",
+ " messages=[\n",
+ " {\"role\": \"user\", \"content\": prompt},\n",
+ " ],\n",
+ " )\n",
+ " response = \"\"\n",
+ " with result as stream:\n",
+ " for text in stream.text_stream:\n",
+ " response += text or \"\"\n",
+ " yield response"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a0066ffd-196e-4eaf-ad1e-d492958b62af",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "view = gr.Interface(\n",
+ " fn=stream_claude,\n",
+ " inputs=[gr.Textbox(label=\"Your message:\")],\n",
+ " outputs=[gr.Markdown(label=\"Response:\")],\n",
+ " flagging_mode=\"never\"\n",
+ ")\n",
+ "view.launch()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bc5a70b9-2afe-4a7c-9bed-2429229e021b",
+ "metadata": {},
+ "source": [
+ "## Minor improvement\n",
+ "\n",
+ "I've made a small improvement to this code.\n",
+ "\n",
+ "Previously, it had these lines:\n",
+ "\n",
+ "```\n",
+ "for chunk in result:\n",
+ " yield chunk\n",
+ "```\n",
+ "\n",
+ "There's actually a more elegant way to achieve this (which Python people might call more 'Pythonic'):\n",
+ "\n",
+ "`yield from result`\n",
+ "\n",
+ "I cover this in more detail in the Intermediate Python notebook in the week1 folder - take a look if you'd like more."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0087623a-4e31-470b-b2e6-d8d16fc7bcf5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def stream_model(prompt, model):\n",
+ " if model==\"GPT\":\n",
+ " result = stream_gpt(prompt)\n",
+ " elif model==\"Claude\":\n",
+ " result = stream_claude(prompt)\n",
+ " else:\n",
+ " raise ValueError(\"Unknown model\")\n",
+ " yield from result"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "8d8ce810-997c-4b6a-bc4f-1fc847ac8855",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "view = gr.Interface(\n",
+ " fn=stream_model,\n",
+ " inputs=[gr.Textbox(label=\"Your message:\"), gr.Dropdown([\"GPT\", \"Claude\"], label=\"Select model\", value=\"Claude\")],\n",
+ " outputs=[gr.Markdown(label=\"Response:\")],\n",
+ " flagging_mode=\"never\"\n",
+ ")\n",
+ "view.launch()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d933865b-654c-4b92-aa45-cf389f1eda3d",
+ "metadata": {},
+ "source": [
+ "# Building a company brochure generator\n",
+ "\n",
+ "Now you know how - it's simple!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "92d7c49b-2e0e-45b3-92ce-93ca9f962ef4",
+ "metadata": {},
+ "source": [
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
Before you read the next few cells
\n",
+ " \n",
+ " Try to do this yourself - go back to the company brochure in week1, day5 and add a Gradio UI to the end. Then come and look at the solution.\n",
+ " \n",
+ "