{
 "cells": [
  {
   "attachments": {
    "process.png": {
     "image/png": "[encoded data, 223264 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A simple code-graded evaluation\n",
    "\n",
    "In this lesson we'll start with a look at a very simple example code-graded evaluation, before covering a more realistic prompt in the next lesson.  We'll follow the process outlined in this diagram:\n",
    "\n",
    "![process.png](attachment:process.png)\n",
    "\n",
    "The rough steps are:\n",
    "1. Start by defining our evaluation test set\n",
    "1. Write our initial prompt attempt\n",
    "2. Run it through our evaluation process and get a score\n",
    "3. Alter our prompt based on the evaluation results\n",
    "4. Run the altered prompt through our evaluation process and hopefully get a better score!\n",
    "\n",
    "Let's try following this process!\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Our input data\n",
    "\n",
    "We'll be grading an eval where we ask Claude to successfully identify how many legs an animal has.  In future lessons we'll see more complex and realistic prompts and evaluations, but we're keeping things deliberately simple here to focus on the actual evaluation process.\n",
    "\n",
    "The first step is to write our evaluation data set that includes our inputs plus corresponding golden answers.  Let's use this simple list of dictionaries, where each dictionary has an `animal_statement` and `golden_answer` key:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "eval_data = [\n",
    "    {\"animal_statement\": \"The animal is a human.\", \"golden_answer\": \"2\"},\n",
    "    {\"animal_statement\": \"The animal is a snake.\", \"golden_answer\": \"0\"},\n",
    "    {\"animal_statement\": \"The fox lost a leg, but then magically grew back the leg he lost and a mysterious extra leg on top of that.\", \"golden_answer\": \"5\"},\n",
    "    {\"animal_statement\": \"The animal is a dog.\", \"golden_answer\": \"4\"},\n",
    "    {\"animal_statement\": \"The animal is a cat with two extra legs.\", \"golden_answer\": \"6\"},\n",
    "    {\"animal_statement\": \"The animal is an elephant.\", \"golden_answer\": \"4\"},\n",
    "    {\"animal_statement\": \"The animal is a bird.\", \"golden_answer\": \"2\"},\n",
    "    {\"animal_statement\": \"The animal is a fish.\", \"golden_answer\": \"0\"},\n",
    "    {\"animal_statement\": \"The animal is a spider with two extra legs\", \"golden_answer\": \"10\"},\n",
    "    {\"animal_statement\": \"The animal is an octopus.\", \"golden_answer\": \"8\"},\n",
    "    {\"animal_statement\": \"The animal is an octopus that lost two legs and then regrew three legs.\", \"golden_answer\": \"9\"},\n",
    "    {\"animal_statement\": \"The animal is a two-headed, eight-legged mythical creature.\", \"golden_answer\": \"8\"},\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that some of the evaluation questions are a little bit tricky, like this one: \n",
    "> The fox lost a leg, but then magically grew back the leg he lost and a mysterious extra leg on top of that.\n",
    "\n",
    "This will be important later!\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Our initial prompt\n",
    "Next, we'll define out initial prompt.  The function below takes in a single animal statement and returns a properly formatted messages list containing our first prompt attempt:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def build_input_prompt(animal_statement):\n",
    "    user_content = f\"\"\"You will be provided a statement about an animal and your job is to determine how many legs that animal has.\n",
    "    \n",
    "    Here is the animal statement.\n",
    "    <animal_statement>{animal_statement}</animal_statement>\n",
    "    \n",
    "    How many legs does the animal have? Please respond with a number\"\"\"\n",
    "\n",
    "    messages = [{'role': 'user', 'content': [{\"text\": user_content}]}]\n",
    "    return messages"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's test it out quickly with the first element in our `eval` dataset:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'role': 'user',\n",
       "  'content': [{'text': 'You will be provided a statement about an animal and your job is to determine how many legs that animal has.\\n    \\n    Here is the animal statement.\\n    <animal_statement>The animal is a human.</animal_statement>\\n    \\n    How many legs does the animal have? Please respond with a number'}]}]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "build_input_prompt(eval_data[0]['animal_statement'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we'll write a simple function that takes a list of messages and send it off to the Anthropic API:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "import boto3\n",
    "\n",
    "def get_completion(messages):\n",
    "\n",
    "    bedrock_client = boto3.client(service_name='bedrock-runtime', region_name=\"us-west-2\")\n",
    "    model_id = \"anthropic.claude-3-haiku-20240307-v1:0\"\n",
    "\n",
    "    # Send the message.\n",
    "    response = bedrock_client.converse(\n",
    "        modelId=model_id,\n",
    "        messages=messages\n",
    "    )\n",
    "\n",
    "    return response[\"output\"][\"message\"][\"content\"][0][\"text\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's test it out with out first entry in the `eval_data` list, which contains the following animal statement: \n",
    "```\n",
    "'The animal is a human.'\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'2'"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "full_prompt = build_input_prompt(eval_data[0]['animal_statement'])\n",
    "get_completion(full_prompt)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We get `2` back as the response, which passes the eyeball test! Humans generally have two legs. The next step is to build and run an entire evaluation with all 12 entries in our `eval_data` set.\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Writing the eval logic\n",
    "\n",
    "We'll start by combing each input from our `eval_data` list with our prompt template, passing the resulting \"finished\" prompts to the model, and collecting all the outputs we get back:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "outputs = [get_completion(build_input_prompt(question['animal_statement'])) for question in eval_data]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's take a quick peek at what we get back:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['2',\n",
       " 'The animal described in the statement is a snake. Snakes are reptiles that do not have any legs. Therefore, the animal has 0 legs.',\n",
       " '4',\n",
       " '4',\n",
       " '6',\n",
       " '4',\n",
       " '2',\n",
       " '0',\n",
       " '8',\n",
       " '8',\n",
       " '5',\n",
       " 'The animal described in the statement has 8 legs.']"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "outputs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Already, we can tell our prompt needs some improvement because we're getting some answers that are not exclusively numbers!  Let's take a closer look at the results alongside each corresponding golden answer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Animal Statement: The animal is a human.\n",
      "Golden Answer: 2\n",
      "Output: 2\n",
      "\n",
      "Animal Statement: The animal is a snake.\n",
      "Golden Answer: 0\n",
      "Output: The animal described in the statement is a snake. Snakes are reptiles that do not have any legs. Therefore, the animal has 0 legs.\n",
      "\n",
      "Animal Statement: The fox lost a leg, but then magically grew back the leg he lost and a mysterious extra leg on top of that.\n",
      "Golden Answer: 5\n",
      "Output: 4\n",
      "\n",
      "Animal Statement: The animal is a dog.\n",
      "Golden Answer: 4\n",
      "Output: 4\n",
      "\n",
      "Animal Statement: The animal is a cat with two extra legs.\n",
      "Golden Answer: 6\n",
      "Output: 6\n",
      "\n",
      "Animal Statement: The animal is an elephant.\n",
      "Golden Answer: 4\n",
      "Output: 4\n",
      "\n",
      "Animal Statement: The animal is a bird.\n",
      "Golden Answer: 2\n",
      "Output: 2\n",
      "\n",
      "Animal Statement: The animal is a fish.\n",
      "Golden Answer: 0\n",
      "Output: 0\n",
      "\n",
      "Animal Statement: The animal is a spider with two extra legs\n",
      "Golden Answer: 10\n",
      "Output: 8\n",
      "\n",
      "Animal Statement: The animal is an octopus.\n",
      "Golden Answer: 8\n",
      "Output: 8\n",
      "\n",
      "Animal Statement: The animal is an octopus that lost two legs and then regrew three legs.\n",
      "Golden Answer: 9\n",
      "Output: 5\n",
      "\n",
      "Animal Statement: The animal is a two-headed, eight-legged mythical creature.\n",
      "Golden Answer: 8\n",
      "Output: The animal described in the statement has 8 legs.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "for output, question in zip(outputs, eval_data):\n",
    "    print(f\"Animal Statement: {question['animal_statement']}\\nGolden Answer: {question['golden_answer']}\\nOutput: {output}\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is a small enough data set that we can easily scan the results and find the problematic responses, but let's grade our results systematically:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Score: 58.333333333333336%\n"
     ]
    }
   ],
   "source": [
    "def grade_completion(output, golden_answer):\n",
    "    return output == golden_answer\n",
    "\n",
    "grades = [grade_completion(output, question['golden_answer']) for output, question in zip(outputs, eval_data)]\n",
    "print(f\"Score: {sum(grades)/len(grades)*100}%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now have a baseline score! In this case, our initial prompt resulted in an accuracy score of 66.6% After scanning the above results, it looks like there are two obvious issues with our current outputs:\n",
    "\n",
    "### Problem 1: Output formatting issues\n",
    "Our goal here is to write a prompt that results in a numeric output.  Some of our outputs are not numeric: \n",
    "\n",
    "```\n",
    "Animal Statement: The animal is a bird.\n",
    "Golden Answer: 2\n",
    "Output: Based on the provided animal statement, \"The animal is a bird.\", the animal has 2 legs.\n",
    "```\n",
    "We can fix this through some prompting!\n",
    "\n",
    "### Problem 1: Incorrect answers\n",
    "\n",
    "Additionally, some of the answers are completely wrong: \n",
    "\n",
    "```\n",
    "Animal Statement: The animal is an octopus that lost two legs and then regrew three legs.\n",
    "Golden Answer: 9\n",
    "Output: 5\n",
    "```\n",
    "\n",
    "and \n",
    "\n",
    "```\n",
    "Animal Statement: The animal is a spider with two extra legs\n",
    "Golden Answer: 10\n",
    "Output: 8\n",
    "```\n",
    "These inputs are a little \"tricky\" and seem to be causing the model some problems.  We'll also attempt to fix this through prompting!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "--- \n",
    "\n",
    "## Our second attempt\n",
    "\n",
    "Now that we have some level of baseline performance with our initial prompt, let's try improving the prompt and see if our evaluation score improves. We'll start by tackling the problem of the model sometimes outputting additional text instead of only responding with a numeric digit. Here's a second prompt-generating function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "def build_input_prompt2(animal_statement):\n",
    "    user_content = f\"\"\"You will be provided a statement about an animal and your job is to determine how many legs that animal has.\n",
    "    \n",
    "    Here is the animal statement.\n",
    "    <animal_statement>{animal_statement}</animal_statement>\n",
    "    \n",
    "    How many legs does the animal have? Respond only with a numeric digit, like 2 or 6, and nothing else.\"\"\"\n",
    "\n",
    "    messages = [{'role': 'user', 'content': [{\"text\":user_content}]}]\n",
    "    return messages"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The key addition to the prompt is this line: \n",
    "\n",
    "> Respond only with a numeric digit, like 2 or 6, and nothing else."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's test each input with this newer prompt:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "outputs2 = [get_completion(build_input_prompt2(question['animal_statement'])) for question in eval_data]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll take a quick look at the outputs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['2', '0', '6', '4', '6', '4', '2', '0', '8', '8', '8', '8']"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "outputs2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We're now getting exclusively numeric outputs!   Let's take a closer look at the results:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Animal Statement: The animal is a human.\n",
      "Golden Answer: 2\n",
      "Output: 2\n",
      "\n",
      "Animal Statement: The animal is a snake.\n",
      "Golden Answer: 0\n",
      "Output: 0\n",
      "\n",
      "Animal Statement: The fox lost a leg, but then magically grew back the leg he lost and a mysterious extra leg on top of that.\n",
      "Golden Answer: 5\n",
      "Output: 6\n",
      "\n",
      "Animal Statement: The animal is a dog.\n",
      "Golden Answer: 4\n",
      "Output: 4\n",
      "\n",
      "Animal Statement: The animal is a cat with two extra legs.\n",
      "Golden Answer: 6\n",
      "Output: 6\n",
      "\n",
      "Animal Statement: The animal is an elephant.\n",
      "Golden Answer: 4\n",
      "Output: 4\n",
      "\n",
      "Animal Statement: The animal is a bird.\n",
      "Golden Answer: 2\n",
      "Output: 2\n",
      "\n",
      "Animal Statement: The animal is a fish.\n",
      "Golden Answer: 0\n",
      "Output: 0\n",
      "\n",
      "Animal Statement: The animal is a spider with two extra legs\n",
      "Golden Answer: 10\n",
      "Output: 8\n",
      "\n",
      "Animal Statement: The animal is an octopus.\n",
      "Golden Answer: 8\n",
      "Output: 8\n",
      "\n",
      "Animal Statement: The animal is an octopus that lost two legs and then regrew three legs.\n",
      "Golden Answer: 9\n",
      "Output: 8\n",
      "\n",
      "Animal Statement: The animal is a two-headed, eight-legged mythical creature.\n",
      "Golden Answer: 8\n",
      "Output: 8\n",
      "\n"
     ]
    }
   ],
   "source": [
    "for output, question in zip(outputs2, eval_data):\n",
    "    print(f\"Animal Statement: {question['animal_statement']}\\nGolden Answer: {question['golden_answer']}\\nOutput: {output}\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are still obvious issues with the actual numeric answers, like this one:\n",
    "\n",
    "```\n",
    "Animal Statement: The animal is a spider with two extra legs\n",
    "Golden Answer: 10\n",
    "Output: 8\n",
    "```\n",
    "\n",
    "Before tackling that problem, let's get an official score to see how our performance (hopefully) improved:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Score: 75.0%\n"
     ]
    }
   ],
   "source": [
    "grades = [grade_completion(output, question['golden_answer']) for output, question in zip(outputs2, eval_data)]\n",
    "print(f\"Score: {sum(grades)/len(grades)*100}%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our score went up a bit! **Note: this data set is quite small, so take these results with a grain of salt**\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Our third attempt\n",
    "\n",
    "Next, let's tackle the logical issues we're seeing with the incorrect outputs like: \n",
    "\n",
    "```\n",
    "Animal Statement: The fox lost a leg, but then magically grew back the leg he lost and a mysterious extra leg on top of that.\n",
    "Golden Answer: 5\n",
    "Output: 6\n",
    "```\n",
    "One technique we could employ here is chain of thought prompting, where we give Claude specific instructions to reason through its response before finally generating an answer.  Now that we have an evaluation in place, we can test to see if chain of thought prompting actually makes a difference or not!\n",
    "\n",
    "Let's write a new prompt that asks the model to \"think out-loud\" inside of `<thinking>` tags.  This complicates our logic a little bit because we'll need a convenient way to extract the model's final answer. We'll instruct the model to also include its final answer inside of `<answer>` tags so that we can easily extract the \"final\" numeric answer:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [],
   "source": [
    "def build_input_prompt3(animal_statement):\n",
    "    user_content = f\"\"\"You will be provided a statement about an animal and your job is to determine how many legs that animal has.\n",
    "    \n",
    "    Here is the animal statement.\n",
    "    <animal_statement>{animal_statement}</animal_statement>\n",
    "    \n",
    "    How many legs does the animal have? \n",
    "    Start by reasoning about the numbers of legs the animal has, thinking step by step inside of <thinking> tags.  \n",
    "    Then, output your final answer inside of <answer> tags. \n",
    "    Inside the <answer> tags return just the number of legs as an integer and nothing else.\"\"\"\n",
    "\n",
    "    messages = [{'role': 'user', 'content': [{\"text\": user_content}]}]\n",
    "    return messages"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's collect the outputs using this new version of the prompt:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "outputs3 = [get_completion(build_input_prompt3(question['animal_statement'])) for question in eval_data]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's take a look at some of the outputs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Animal Statement: The animal is a human.\n",
      "Golden Answer: 2\n",
      "Output: <thinking>\n",
      "The animal described in the statement is a human. Humans are a type of mammal, and typically have two legs. Therefore, the animal described in the statement has 2 legs.\n",
      "</thinking>\n",
      "\n",
      "<answer>2</answer>\n",
      "\n",
      "Animal Statement: The animal is a snake.\n",
      "Golden Answer: 0\n",
      "Output: <thinking>\n",
      "The statement says that the animal is a snake. Snakes are reptiles that do not have any legs. They move by undulating their bodies across the ground.\n",
      "</thinking>\n",
      "\n",
      "<answer>0</answer>\n",
      "\n",
      "Animal Statement: The fox lost a leg, but then magically grew back the leg he lost and a mysterious extra leg on top of that.\n",
      "Golden Answer: 5\n",
      "Output: <thinking>\n",
      "The animal statement mentions that the fox lost a leg, but then magically grew back the leg he lost and a mysterious extra leg on top of that. This means that the fox originally had 4 legs, lost 1 leg, and then regrew the lost leg and gained an additional leg, making it a total of 5 legs.\n",
      "</thinking>\n",
      "\n",
      "<answer>5</answer>\n",
      "\n",
      "Animal Statement: The animal is a dog.\n",
      "Golden Answer: 4\n",
      "Output: <thinking>\n",
      "The animal statement indicates that the animal is a dog. Dogs are commonly known to be quadrupeds, meaning they have four legs. Therefore, the number of legs the animal has is 4.\n",
      "</thinking>\n",
      "\n",
      "<answer>4</answer>\n",
      "\n",
      "Animal Statement: The animal is a cat with two extra legs.\n",
      "Golden Answer: 6\n",
      "Output: <thinking>\n",
      "The animal statement says that the animal is a cat with two extra legs. A cat typically has 4 legs, so with the two extra legs, the animal would have a total of 6 legs.\n",
      "</thinking>\n",
      "\n",
      "<answer>6</answer>\n",
      "\n",
      "Animal Statement: The animal is an elephant.\n",
      "Golden Answer: 4\n",
      "Output: <thinking>\n",
      "The animal mentioned in the statement is an elephant. Elephants are large mammals that typically have four legs. They are known to be quadrupeds, meaning they have four legs.\n",
      "</thinking>\n",
      "\n",
      "<answer>4</answer>\n",
      "\n",
      "Animal Statement: The animal is a bird.\n",
      "Golden Answer: 2\n",
      "Output: <thinking>\n",
      "The animal statement says that the animal is a bird. Birds are typically known to have two legs, as they are bipedal creatures. Birds use their two legs for walking, perching, and other locomotion activities.\n",
      "</thinking>\n",
      "\n",
      "<answer>2</answer>\n",
      "\n",
      "Animal Statement: The animal is a fish.\n",
      "Golden Answer: 0\n",
      "Output: <thinking>\n",
      "The statement provided indicates that the animal is a fish. Fish are aquatic vertebrates that typically have fins and breathe through gills. They do not have legs, but instead have fins to propel themselves through the water.\n",
      "</thinking>\n",
      "\n",
      "<answer>0</answer>\n",
      "\n",
      "Animal Statement: The animal is a spider with two extra legs\n",
      "Golden Answer: 10\n",
      "Output: <thinking>\n",
      "The animal statement indicates that the animal is a spider with two extra legs. A spider typically has 8 legs, so adding two extra legs would make the total number of legs 10.\n",
      "</thinking>\n",
      "\n",
      "<answer>10</answer>\n",
      "\n",
      "Animal Statement: The animal is an octopus.\n",
      "Golden Answer: 8\n",
      "Output: Here is my thinking process and answer:\n",
      "\n",
      "<thinking>\n",
      "The animal statement says that the animal is an octopus. An octopus is a marine invertebrate that has eight tentacles or legs. Therefore, the animal has 8 legs.\n",
      "</thinking>\n",
      "\n",
      "<answer>8</answer>\n",
      "\n",
      "Animal Statement: The animal is an octopus that lost two legs and then regrew three legs.\n",
      "Golden Answer: 9\n",
      "Output: <thinking>\n",
      "The animal is initially described as an octopus, which has 8 legs. The statement then says the octopus lost two legs, meaning it had 6 legs at that point. Finally, it says the octopus regrew three legs, so we need to add those back to the 6 legs it had after losing the two.\n",
      "</thinking>\n",
      "\n",
      "<answer>9</answer>\n",
      "\n",
      "Animal Statement: The animal is a two-headed, eight-legged mythical creature.\n",
      "Golden Answer: 8\n",
      "Output: <thinking>\n",
      "Based on the given animal statement, the animal is described as a \"two-headed, eight-legged mythical creature\". This indicates that the animal has a total of 8 legs.\n",
      "\n",
      "The statement does not provide any information about the number of legs per head. However, since the animal is described as a \"mythical creature\", we can assume that it is not a real animal and the number of legs per head is not necessarily the typical number for a normal animal.\n",
      "\n",
      "Therefore, the animal described in the statement has a total of 8 legs.\n",
      "</thinking>\n",
      "\n",
      "<answer>8</answer>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "for output, question in zip(outputs3, eval_data):\n",
    "    print(f\"Animal Statement: {question['animal_statement']}\\nGolden Answer: {question['golden_answer']}\\nOutput: {output}\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here's an example of the sort of response we get: \n",
    "\n",
    "```\n",
    "Animal Statement: The fox lost a leg, but then magically grew back the leg he lost and a mysterious extra leg on top of that.\n",
    "Golden Answer: 5\n",
    "Output: Here is my step-by-step reasoning:\n",
    "<thinking>\n",
    "1. The initial statement says the fox lost a leg.\n",
    "2. But then the fox \"magically grew back the leg he lost and a mysterious extra leg on top of that.\"\n",
    "3. This means the fox originally had 4 legs, lost 1 leg, and then grew back the lost leg plus an extra leg, for a total of 5 legs.\n",
    "</thinking>\n",
    "<answer>5</answer>\n",
    "```\n",
    "\n",
    "The logic appears to be improved, at least in this particular example.  Now we need to focus on making this prompt \"grade-able\".  We need to extract the number between the `answer` tags before the grading process.\n",
    "\n",
    "Here's a function that extracts the text between two `<answer>` tags:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "def extract_answer(text):\n",
    "    pattern = r'<answer>(.*?)</answer>'\n",
    "    match = re.search(pattern, text)\n",
    "    if match:\n",
    "        return match.group(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, let's extract the answers from the latest batch of outputs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "extracted_outputs3 = [extract_answer(output) for output in outputs3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['2', '0', '5', '4', '6', '4', '2', '0', '10', '8', '9', '8']"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "extracted_outputs3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, let's get our score and see if adding chain of thought to our prompt made a difference!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Score: 100.0%\n"
     ]
    }
   ],
   "source": [
    "grades3 = [grade_completion(output, question['golden_answer']) for output, question in zip(extracted_outputs3, eval_data)]\n",
    "print(f\"Score: {sum(grades3)/len(grades3)*100}%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We improved our score to 100%! \n",
    "\n",
    "Our evaluation gives us some confidence that the changes we made to our prompt actually result in better outputs.  This is a simple example that uses exact-match grading, but in the next lesson well take a look at something a little more complicated. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py311",
   "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.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
