{"repo_id":"augmentoolkit","entity_id":"py:convert_pdf_to_text","uri":"program://augmentoolkit/module/convert_pdf_to_text#L1-L55","kind":"module","name":"convert_pdf_to_text","path":"convert_pdf_to_text.py","language":"python","start_line":1,"end_line":55,"context_start_line":1,"context_end_line":55,"code":"# Written by GPT-4\nimport fitz # PyMuPDF\nimport pytesseract\nfrom PIL import Image\nimport io\n\n# Ensure the path to the tesseract executable is set if it's not in your PATH\n# pytesseract.pytesseract.tesseract_cmd = r''\n\n\ndef convert_pdf_to_text(pdf_path, output_txt_path):\n # Open the PDF file\n document = fitz.open(pdf_path)\n\n text = \"\" # Initialize a text string to hold all text from the PDF\n\n for page_num in range(len(document)):\n # Get the page\n page = document.load_page(page_num)\n\n # First, try to extract text using PyMuPDF\n text_content = page.get_text()\n\n if text_content.strip(): # If text is found, append it.\n text += text_content\n # else:\n # # If no text is found, it might be an image-based PDF\n # # Extract the image from the page\n # for img_index, img in enumerate(page.get_images(full=True)):\n # xref = img[0]\n # base_image = document.extract_image(xref)\n # image_bytes = base_image[\"image\"]\n\n # # Load it to PIL\n # image = Image.open(io.BytesIO(image_bytes))\n\n # # Use pytesseract to do OCR on the image\n # text += pytesseract.image_to_string(image)\n\n # Close the document\n document.close()\n\n # Write the text to a .txt file\n with open(output_txt_path, \"w\", encoding=\"utf-8\") as text_file:\n text_file.write(text)\n\n return text\n\n\n# Usage\npdf_path = \"./Introduction to Logic and Critical Thinking, by Matthew Van Cleave.pdf\"\noutput_txt_path = (\n \"Introduction to Logic and Critical Thinking, by Matthew Van Cleave.txt\"\n)\nconvert_pdf_to_text(pdf_path, output_txt_path)","source_hash":"7518e848fe93d66b5969a43aa7da5f38cd0aaad00ca52b5d0d719a6f4c3d8b08","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:convert_pdf_to_text.convert_pdf_to_text","uri":"program://augmentoolkit/function/convert_pdf_to_text.convert_pdf_to_text#L11-L47","kind":"function","name":"convert_pdf_to_text","path":"convert_pdf_to_text.py","language":"python","start_line":11,"end_line":47,"context_start_line":1,"context_end_line":55,"code":"# Written by GPT-4\nimport fitz # PyMuPDF\nimport pytesseract\nfrom PIL import Image\nimport io\n\n# Ensure the path to the tesseract executable is set if it's not in your PATH\n# pytesseract.pytesseract.tesseract_cmd = r''\n\n\ndef convert_pdf_to_text(pdf_path, output_txt_path):\n # Open the PDF file\n document = fitz.open(pdf_path)\n\n text = \"\" # Initialize a text string to hold all text from the PDF\n\n for page_num in range(len(document)):\n # Get the page\n page = document.load_page(page_num)\n\n # First, try to extract text using PyMuPDF\n text_content = page.get_text()\n\n if text_content.strip(): # If text is found, append it.\n text += text_content\n # else:\n # # If no text is found, it might be an image-based PDF\n # # Extract the image from the page\n # for img_index, img in enumerate(page.get_images(full=True)):\n # xref = img[0]\n # base_image = document.extract_image(xref)\n # image_bytes = base_image[\"image\"]\n\n # # Load it to PIL\n # image = Image.open(io.BytesIO(image_bytes))\n\n # # Use pytesseract to do OCR on the image\n # text += pytesseract.image_to_string(image)\n\n # Close the document\n document.close()\n\n # Write the text to a .txt file\n with open(output_txt_path, \"w\", encoding=\"utf-8\") as text_file:\n text_file.write(text)\n\n return text\n\n\n# Usage\npdf_path = \"./Introduction to Logic and Critical Thinking, by Matthew Van Cleave.pdf\"\noutput_txt_path = (\n \"Introduction to Logic and Critical Thinking, by Matthew Van Cleave.txt\"\n)\nconvert_pdf_to_text(pdf_path, output_txt_path)","source_hash":"7518e848fe93d66b5969a43aa7da5f38cd0aaad00ca52b5d0d719a6f4c3d8b08","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.constants","uri":"program://augmentoolkit/module/generation_functions.constants#L1-L36","kind":"module","name":"generation_functions.constants","path":"generation_functions/constants.py","language":"python","start_line":1,"end_line":36,"context_start_line":1,"context_end_line":36,"code":"RP_MODEL = \"./rp_model\" # model used for RP tasks, probably going to use Sao10K/Euryale-1.3-L2-70b\n# LOGICAL_MODEL = \"./logical_model/airoboros-l2-13b-3.1.1.Q8_0.gguf\" # model used for decision-making and base question generation (should be \"smart\")\n\nLOGICAL_MODEL = \"./logical_model/flatorcamaid-13b-v0.2.Q8_0.gguf\" # model used for decision-making and base question generation (should be \"smart\")\n\nnames = [ # Replaces \"Albert\" in scenarios. Needs to be western male names to avoid pronoun and setting inconsistencies).\n \"William\",\n \"James\",\n \"John\",\n \"Robert\",\n \"Michael\",\n \"Charles\",\n \"George\",\n \"Joseph\",\n \"Edward\",\n \"Henry\",\n \"Thomas\",\n \"David\",\n \"Richard\",\n \"Daniel\",\n \"Matthew\",\n \"Alexander\",\n \"Benjamin\",\n \"Christopher\",\n \"Nicholas\",\n \"Samuel\",\n]\n\n# N_CHARACTERS_SAME_ANSWER = 25 # number of characters that are the same in the question and answer for a thing to fail validation or be deemed \"the same\" in various places throughout the code\n\n# N_CHARACTERS_SAME_QUESTION = 15\n\n# N_CHARACTERS_SHARED = 100 # number of characters that are the same in the question and answer for a thing to fail validation or be deemed \"the same\" in various places throughout the code\n\n# IF USING THE 70b LLAMA 2, MUST SET n_gqa=8 WHEN LOADING\n# TODO MAKE A GLOBAL CONSTANT is_70b AND ADD THAT WITH BRANCHING LOGIC TO ALL THE LLAMA CPP LOADERS","source_hash":"5f7f01bffe335fe887269d055e158f7918b547c101dfd50407cf91ff4edc8217","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.format_qatuples","uri":"program://augmentoolkit/module/generation_functions.format_qatuples#L1-L15","kind":"module","name":"generation_functions.format_qatuples","path":"generation_functions/format_qatuples.py","language":"python","start_line":1,"end_line":15,"context_start_line":1,"context_end_line":15,"code":"def format_qatuples(qatuples):\n strlst = []\n for qatuple in qatuples:\n strlst.append(\n f\"\"\"Question: \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\"\"\"\n )\n return \"\\n\\n\".join(strlst)\n\n\ndef format_qatuples_noquotes(qatuples):\n strlst = []\n for idx, qatuple in enumerate(qatuples):\n strlst.append(f\"\"\"{idx + 1}. {qatuple[0]}\"\"\")\n return \"\\n\".join(strlst)","source_hash":"7139221b2092ee811bfbe7af5abe36564b85400b8552406476da2fe4e1442929","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.format_qatuples.format_qatuples","uri":"program://augmentoolkit/function/generation_functions.format_qatuples.format_qatuples#L1-L8","kind":"function","name":"format_qatuples","path":"generation_functions/format_qatuples.py","language":"python","start_line":1,"end_line":8,"context_start_line":1,"context_end_line":15,"code":"def format_qatuples(qatuples):\n strlst = []\n for qatuple in qatuples:\n strlst.append(\n f\"\"\"Question: \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\"\"\"\n )\n return \"\\n\\n\".join(strlst)\n\n\ndef format_qatuples_noquotes(qatuples):\n strlst = []\n for idx, qatuple in enumerate(qatuples):\n strlst.append(f\"\"\"{idx + 1}. {qatuple[0]}\"\"\")\n return \"\\n\".join(strlst)","source_hash":"7139221b2092ee811bfbe7af5abe36564b85400b8552406476da2fe4e1442929","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.format_qatuples.format_qatuples_noquotes","uri":"program://augmentoolkit/function/generation_functions.format_qatuples.format_qatuples_noquotes#L11-L15","kind":"function","name":"format_qatuples_noquotes","path":"generation_functions/format_qatuples.py","language":"python","start_line":11,"end_line":15,"context_start_line":1,"context_end_line":15,"code":"def format_qatuples(qatuples):\n strlst = []\n for qatuple in qatuples:\n strlst.append(\n f\"\"\"Question: \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\"\"\"\n )\n return \"\\n\\n\".join(strlst)\n\n\ndef format_qatuples_noquotes(qatuples):\n strlst = []\n for idx, qatuple in enumerate(qatuples):\n strlst.append(f\"\"\"{idx + 1}. {qatuple[0]}\"\"\")\n return \"\\n\".join(strlst)","source_hash":"7139221b2092ee811bfbe7af5abe36564b85400b8552406476da2fe4e1442929","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_answer","uri":"program://augmentoolkit/module/generation_functions.check_answer#L1-L357","kind":"module","name":"generation_functions.check_answer","path":"generation_functions/check_answer.py","language":"python","start_line":1,"end_line":357,"context_start_line":1,"context_end_line":357,"code":"import re\nfrom .answer_accurate_grammar import answer_accurate_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# Answer vetting\n\n\ndef check_answer(qatuple, logic_llm, permissive_mode=True):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Given a paragraph or two from a larger text, a question based on the paragraphs, and an answer to the question, you will make a determination as to whether the answer to the question is a sensible answer, given the information in the paragraphs. Essentially: you will fact-check the answer to the question, with your source of truth being the paragraphs provided. Your task includes first analyzing the text, thinking through whether or not the answer reflects aspects of the paragraphs provided. \n\nFollowing this, at the very end of your response, you will write \"Accurate\" or \"Inaccurate\" depending on your analysis of the answer with regards to the text. \n\nRemember that at the very end of your response, you will write \"Accurate\" or \"Inaccurate\". Do not use these words anywhere else in your answer.\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe Industrial Revolution marked a transformative period in history, fundamentally altering economic structures and industrial processes. One of the most significant innovations was the advent of steam power, which drastically reduced production costs. This reduction was due to the increased efficiency and speed of machines powered by steam, replacing the slower, more labor-intensive methods previously used. Additionally, steam power was instrumental in the development of semi-automated factories, leading to a significant shift in manufacturing processes and labor dynamics.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What was the role of steam power in the Industrial Revolution, particularly in terms of its impact on production costs, and the emergence of semi-automated factories?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"Steam power during the Industrial Revolution played a crucial role in decreasing production costs. However, it had no significant impact on the emergence of semi-automated factories. Interestingly, it also led to an increased cultivation of lemons.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Text Analysis:\n#### Identify Key Information: The text highlights the role of steam power in reducing production costs and developing semi-automated factories during the Industrial Revolution.\n#### Categorize Information Type: The information is factual, describing the impacts of steam power on industrial processes.\n\n### Answer Breakdown:\n#### Dissect the Answer: The answer has three assertions: steam power reducing production costs, no significant impact on semi-automated factories, and increased cultivation of lemons.\n#### Identify Answer Type: The first two are factual statements relevant to the text, and the third is an additional factual claim.\n\n### Accuracy Check:\n#### Direct Comparison for Factual Accuracy:\n - The text aligns with the answer about steam power reducing production costs.\n - The text contradicts the answer about steam power's impact on semi-automated factories, stating steam power was instrumental in their development.\n - The text does not mention anything about the cultivation of lemons.\n#### Inference and Contextual Alignment: The first two parts of the answer are directly related to the text, while the third part is not supported or mentioned in the text.\n\n### Final Judgment:\n#### Comprehensive Assessment: The answer is accurate regarding production costs, inaccurate regarding semi-automated factories, and the lemon cultivation claim is unsupported.\n#### Overall Accuracy Determination: The answer is: Inaccurate.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nEpistemology, often regarded as a branch of philosophy, is concerned with the theory of knowledge. It involves understanding the nature, sources, and limitations of knowledge. A key concept in epistemology is the idea of \"justified true belief,\" which suggests that for someone to know something, they must believe it to be true, have justification for this belief, and the belief must indeed be true. For example, believing that it will rain tomorrow because the weather forecast says so, and it turns out to be true, is a justified true belief. Epistemology also explores the idea of skepticism, which questions the possibility of certain or absolute knowledge.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What does the concept of 'justified true belief' involve in epistemology, and how does skepticism relate to the understanding of knowledge?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"The concept of 'justified true belief' in epistemology involves having a belief that is true and has justification. For a belief to be considered knowledge, it must be true, one must believe it, and there must be sufficient reason for this belief. Skepticism plays a role by challenging the certainty of knowledge, thereby emphasizing the need for strong justification in 'justified true belief.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Text Analysis:\n#### Identify Key Information: The text covers the concept of 'justified true belief' and skepticism in epistemology.\n#### Categorize Information Type: This is conceptual and theoretical information.\n\n### Answer Breakdown:\n#### Dissect the Answer: The answer addresses the nature of 'justified true belief' and the role of skepticism in epistemology.\n#### Identify Answer Type: Both parts of the answer are explanatory, relating to philosophical concepts.\n\n### Accuracy Check:\n#### Direct Comparison for Factual Accuracy:\n - The text supports the answer's description of 'justified true belief'.\n - The text aligns with the answer's depiction of skepticism's role in challenging the certainty of knowledge.\n#### Inference and Contextual Alignment: Both parts of the answer are consistent with the text's explanations of these concepts.\n\n### Final Judgment:\n#### Comprehensive Assessment: Both parts of the answer accurately reflect the text's content.\n#### Overall Accuracy Determination: The answer is: Accurate.\n\n\n### Instruction:\nText:\n\\\"\\\"\\\"\nThe novel 'Ocean's Secrets' is set in the early 20th century and revolves around two main characters, Elizabeth and Michael, who believe they have discovered a hidden underwater city. The narrative implies that the city is a remnant of the lost civilization of Atlantis. However, as the story progresses, it becomes apparent that the city is actually a figment of Elizabeth's imagination, a result of her fascination with mythology and ancient history.\n\\\"\\\"\\\"\n\nQuestion (based on text): \n\\\"\\\"\\\"What is the significance of the underwater city discovered by Elizabeth and Michael in the novel 'Ocean's Secrets'?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \n\\\"\\\"\\\"The underwater city discovered by Elizabeth and Michael in 'Ocean's Secrets' represents a significant archaeological find from the lost civilization of Atlantis, shedding light on ancient historical mysteries.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Text Analysis:\n#### Identify Key Information: The text revolves around the discovery of an underwater city, initially believed to be Atlantis, but later revealed to be a figment of Elizabeth's imagination.\n#### Categorize Information Type: The information is narrative and contains a twist that changes the initial perception of the discovery.\n\n### Answer Breakdown:\n#### Dissect the Answer: The answer claims the underwater city is a significant archaeological find from Atlantis.\n#### Identify Answer Type: The statement is a factual claim based on the initial setup of the narrative.\n\n### Accuracy Check:\n#### Direct Comparison for Factual Accuracy: The text's later revelation that the city is imaginary contradicts the answer's claim of it being an archaeological find from Atlantis.\n#### Inference and Contextual Alignment: The answer fails to align with the narrative twist revealed in the text.\n\n### Final Judgment:\n#### Comprehensive Assessment: The answer is inaccurate as it contradicts the final revelation in the text.\n#### Overall Accuracy Determination: The answer is: Inaccurate.\n\n### Instruction:\nText:\n\\\"\\\"\\\"\nThe Great Wall of China — so named because it was built to repel enemies coming from the direction of China — was built by the Romans as a defense against the Mongolian invasions in the 3rd century BC. The wall played a pivotal role in the defence of the Eastern Roman Empire Against Attila the Hun in 1337 AD. The dramatized version of these events was eventually fictionalized as the movie \"The Great Wall,\" in which Liam Nissan (playing Marcus Aurelius) and Jackie Chan (playing Liu Bei) team up to fight Batzorig Vaanchig (playing Attila). Though the Huns were unsuccessful in breaching the wall, the eventual invasions by Galbadrakh Tsendbaatar broke through and sacked Constantinople in 1453 AD.\n\\\"\\\"\\\"\n\nQuestion (based on text): \n\\\"\\\"\\\"Who built the Great Wall of China and for what purpose?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \n\\\"\\\"\\\"The Great Wall of China was built by the Romans to defend against Mongolian invasions (coming from the direction of China) in the 3rd century BC.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Text Analysis:\n#### Identify Key Information: The text incorrectly states that the Great Wall of China was built by the Romans to defend against Mongolian invasions.\n#### Categorize Information Type: The information is historically factual but objectively wrong.\n\n### Answer Breakdown:\n#### Dissect the Answer: The answer correctly cites the text, stating the Great Wall was built by the Romans against Mongolians.\n#### Identify Answer Type: The statement is a factual claim, accurately reflecting the content of the text.\n\n### Accuracy Check:\n#### Direct Comparison for Factual Accuracy: The answer accurately mirrors the text's incorrect claim about the Great Wall of China.\n#### Inference and Contextual Alignment: Despite the historical inaccuracy, the answer aligns perfectly with the text's content.\n\n### Final Judgment:\n#### Comprehensive Assessment: The answer, while reflecting an objectively incorrect fact, is accurate in the context of the text's information.\n#### Overall Accuracy Determination: The answer is: Accurate.\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nFormal logic, a branch of philosophy and mathematics, is concerned with the study of reasoning. It uses a set of symbols and rules to create a language that can precisely express ideas. One key aspect of formal logic is the concept of a valid argument, which is an argument where if the premises are true, the conclusion must be true. For instance, in the statement 'All humans are mortal; Socrates is a human; therefore, Socrates is mortal,' the conclusion follows logically from the premises. Another important element is the use of symbolic representation to simplify and clarify arguments. This allows for complex ideas to be broken down into simpler components, making them easier to analyze and understand.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What are the key aspects of formal logic, and how does symbolic representation contribute to its goals?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"Key aspects of formal logic include the study of valid arguments and the use of symbolic representation. Valid arguments are those where the premises may or may not lead to a true conclusion. Symbolic representation helps in making complex ideas more understandable by breaking them down into simpler forms.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Text Analysis:\n#### Identify Key Information: The text discusses the aspects of formal logic, including valid arguments and symbolic representation.\n#### Categorize Information Type: The information is conceptual, relating to logical principles.\n\n### Answer Breakdown:\n#### Dissect the Answer: The answer claims that formal logic includes the study of valid arguments and symbolic representation, with specifics on each.\n#### Identify Answer Type: These are factual statements about the principles of formal logic.\n\n### Accuracy Check:\n#### Direct Comparison for Factual Accuracy:\n - The text's definition of a valid argument contradicts the answer's claim that valid arguments may or may not lead to a true conclusion.\n - The text supports the answer's depiction of symbolic representation.\n#### Inference and Contextual Alignment: The first part of the answer misinterprets the text, while the second part aligns well.\n\n### Final Judgment:\n#### Comprehensive Assessment: The answer is partially accurate, correctly identifying symbolic representation but inaccurately describing valid arguments.\n#### Overall Accuracy Determination: The answer is: Inaccurate.\n\n### Instruction:\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process (the text is your single source of truth):\n\"\"\"\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=6000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=answer_accurate_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n completion_pattern = re.compile(\n r\"Reasoning and thought process \\(the text is your single source of truth\\):\\n(.+)\",\n re.DOTALL,\n )\n response = completion_pattern.search(completion).group(1).strip()\n print(response)\n if permissive_mode:\n determination_pattern = re.compile(\n r\"Overall Accuracy Determination:(.+)\", re.DOTALL\n )\n determination = determination_pattern.search(response).group(1).strip()\n else:\n determination = response\n print(\"\\n\\nDETERMINATION:\\n------\")\n print(determination)\n print(\"\\n---------\\n\")\n if (\n \"inaccurate\" in determination.lower()\n or \"Inaccurate\" in determination.lower()\n or \"mostly\" in determination.lower()\n or \"partial\" in determination.lower()\n ): # The \"mostly\" is there to catch \"mostly accurate\" which the model says occasionally, and which actually means inaccurate.\n return (False, response), completion\n elif (\n \"accurate\" in determination or \"Accurate\" in determination\n ): # very deliberate placement of accurate here, becaues the model can sometimes say irrelevant at the very end, even after saying accurate in its judgement\n return (True, response), completion\n elif (\n \"irrelevant\" in determination or \"Irrelevant\" in determination\n ): # optional support for checking relevance here, too.\n return (\n None,\n response,\n ), completion # signal that question is irrelevant\n else:\n Exception(\"Broke!\")\n except Exception as e:\n retries += 1\n print(\"EXCEPTION IN CHECK_ANSWER: \", e)\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=10000,\n n_gpu_layers=1000,\n rope_freq_scale=0.33,\n rope_scaling_type=1,\n ) # load the logical LLM and offload everything\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"What was the age of the Earth according to the Hebrew Bible?\",\n \"Initially, the Bible suggested a young earth dating back no more than several thousand years.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upo\n# ... truncated ...","source_hash":"bf068231d30487c773c67639aba8b332cc76cc42fe86c349fb6d22756fc3fb2b","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_answer.check_answer","uri":"program://augmentoolkit/function/generation_functions.check_answer.check_answer#L9-L229","kind":"function","name":"check_answer","path":"generation_functions/check_answer.py","language":"python","start_line":9,"end_line":229,"context_start_line":1,"context_end_line":249,"code":"import re\nfrom .answer_accurate_grammar import answer_accurate_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# Answer vetting\n\n\ndef check_answer(qatuple, logic_llm, permissive_mode=True):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Given a paragraph or two from a larger text, a question based on the paragraphs, and an answer to the question, you will make a determination as to whether the answer to the question is a sensible answer, given the information in the paragraphs. Essentially: you will fact-check the answer to the question, with your source of truth being the paragraphs provided. Your task includes first analyzing the text, thinking through whether or not the answer reflects aspects of the paragraphs provided. \n\nFollowing this, at the very end of your response, you will write \"Accurate\" or \"Inaccurate\" depending on your analysis of the answer with regards to the text. \n\nRemember that at the very end of your response, you will write \"Accurate\" or \"Inaccurate\". Do not use these words anywhere else in your answer.\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe Industrial Revolution marked a transformative period in history, fundamentally altering economic structures and industrial processes. One of the most significant innovations was the advent of steam power, which drastically reduced production costs. This reduction was due to the increased efficiency and speed of machines powered by steam, replacing the slower, more labor-intensive methods previously used. Additionally, steam power was instrumental in the development of semi-automated factories, leading to a significant shift in manufacturing processes and labor dynamics.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What was the role of steam power in the Industrial Revolution, particularly in terms of its impact on production costs, and the emergence of semi-automated factories?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"Steam power during the Industrial Revolution played a crucial role in decreasing production costs. However, it had no significant impact on the emergence of semi-automated factories. Interestingly, it also led to an increased cultivation of lemons.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Text Analysis:\n#### Identify Key Information: The text highlights the role of steam power in reducing production costs and developing semi-automated factories during the Industrial Revolution.\n#### Categorize Information Type: The information is factual, describing the impacts of steam power on industrial processes.\n\n### Answer Breakdown:\n#### Dissect the Answer: The answer has three assertions: steam power reducing production costs, no significant impact on semi-automated factories, and increased cultivation of lemons.\n#### Identify Answer Type: The first two are factual statements relevant to the text, and the third is an additional factual claim.\n\n### Accuracy Check:\n#### Direct Comparison for Factual Accuracy:\n - The text aligns with the answer about steam power reducing production costs.\n - The text contradicts the answer about steam power's impact on semi-automated factories, stating steam power was instrumental in their development.\n - The text does not mention anything about the cultivation of lemons.\n#### Inference and Contextual Alignment: The first two parts of the answer are directly related to the text, while the third part is not supported or mentioned in the text.\n\n### Final Judgment:\n#### Comprehensive Assessment: The answer is accurate regarding production costs, inaccurate regarding semi-automated factories, and the lemon cultivation claim is unsupported.\n#### Overall Accuracy Determination: The answer is: Inaccurate.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nEpistemology, often regarded as a branch of philosophy, is concerned with the theory of knowledge. It involves understanding the nature, sources, and limitations of knowledge. A key concept in epistemology is the idea of \"justified true belief,\" which suggests that for someone to know something, they must believe it to be true, have justification for this belief, and the belief must indeed be true. For example, believing that it will rain tomorrow because the weather forecast says so, and it turns out to be true, is a justified true belief. Epistemology also explores the idea of skepticism, which questions the possibility of certain or absolute knowledge.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What does the concept of 'justified true belief' involve in epistemology, and how does skepticism relate to the understanding of knowledge?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"The concept of 'justified true belief' in epistemology involves having a belief that is true and has justification. For a belief to be considered knowledge, it must be true, one must believe it, and there must be sufficient reason for this belief. Skepticism plays a role by challenging the certainty of knowledge, thereby emphasizing the need for strong justification in 'justified true belief.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Text Analysis:\n#### Identify Key Information: The text covers the concept of 'justified true belief' and skepticism in epistemology.\n#### Categorize Information Type: This is conceptual and theoretical information.\n\n### Answer Breakdown:\n#### Dissect the Answer: The answer addresses the nature of 'justified true belief' and the role of skepticism in epistemology.\n#### Identify Answer Type: Both parts of the answer are explanatory, relating to philosophical concepts.\n\n### Accuracy Check:\n#### Direct Comparison for Factual Accuracy:\n - The text supports the answer's description of 'justified true belief'.\n - The text aligns with the answer's depiction of skepticism's role in challenging the certainty of knowledge.\n#### Inference and Contextual Alignment: Both parts of the answer are consistent with the text's explanations of these concepts.\n\n### Final Judgment:\n#### Comprehensive Assessment: Both parts of the answer accurately reflect the text's content.\n#### Overall Accuracy Determination: The answer is: Accurate.\n\n\n### Instruction:\nText:\n\\\"\\\"\\\"\nThe novel 'Ocean's Secrets' is set in the early 20th century and revolves around two main characters, Elizabeth and Michael, who believe they have discovered a hidden underwater city. The narrative implies that the city is a remnant of the lost civilization of Atlantis. However, as the story progresses, it becomes apparent that the city is actually a figment of Elizabeth's imagination, a result of her fascination with mythology and ancient history.\n\\\"\\\"\\\"\n\nQuestion (based on text): \n\\\"\\\"\\\"What is the significance of the underwater city discovered by Elizabeth and Michael in the novel 'Ocean's Secrets'?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \n\\\"\\\"\\\"The underwater city discovered by Elizabeth and Michael in 'Ocean's Secrets' represents a significant archaeological find from the lost civilization of Atlantis, shedding light on ancient historical mysteries.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Text Analysis:\n#### Identify Key Information: The text revolves around the discovery of an underwater city, initially believed to be Atlantis, but later revealed to be a figment of Elizabeth's imagination.\n#### Categorize Information Type: The information is narrative and contains a twist that changes the initial perception of the discovery.\n\n### Answer Breakdown:\n#### Dissect the Answer: The answer claims the underwater city is a significant archaeological find from Atlantis.\n#### Identify Answer Type: The statement is a factual claim based on the initial setup of the narrative.\n\n### Accuracy Check:\n#### Direct Comparison for Factual Accuracy: The text's later revelation that the city is imaginary contradicts the answer's claim of it being an archaeological find from Atlantis.\n#### Inference and Contextual Alignment: The answer fails to align with the narrative twist revealed in the text.\n\n### Final Judgment:\n#### Comprehensive Assessment: The answer is inaccurate as it contradicts the final revelation in the text.\n#### Overall Accuracy Determination: The answer is: Inaccurate.\n\n### Instruction:\nText:\n\\\"\\\"\\\"\nThe Great Wall of China — so named because it was built to repel enemies coming from the direction of China — was built by the Romans as a defense against the Mongolian invasions in the 3rd century BC. The wall played a pivotal role in the defence of the Eastern Roman Empire Against Attila the Hun in 1337 AD. The dramatized version of these events was eventually fictionalized as the movie \"The Great Wall,\" in which Liam Nissan (playing Marcus Aurelius) and Jackie Chan (playing Liu Bei) team up to fight Batzorig Vaanchig (playing Attila). Though the Huns were unsuccessful in breaching the wall, the eventual invasions by Galbadrakh Tsendbaatar broke through and sacked Constantinople in 1453 AD.\n\\\"\\\"\\\"\n\nQuestion (based on text): \n\\\"\\\"\\\"Who built the Great Wall of China and for what purpose?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \n\\\"\\\"\\\"The Great Wall of China was built by the Romans to defend against Mongolian invasions (coming from the direction of China) in the 3rd century BC.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Text Analysis:\n#### Identify Key Information: The text incorrectly states that the Great Wall of China was built by the Romans to defend against Mongolian invasions.\n#### Categorize Information Type: The information is historically factual but objectively wrong.\n\n### Answer Breakdown:\n#### Dissect the Answer: The answer correctly cites the text, stating the Great Wall was built by the Romans against Mongolians.\n#### Identify Answer Type: The statement is a factual claim, accurately reflecting the content of the text.\n\n### Accuracy Check:\n#### Direct Comparison for Factual Accuracy: The answer accurately mirrors the text's incorrect claim about the Great Wall of China.\n#### Inference and Contextual Alignment: Despite the historical inaccuracy, the answer aligns perfectly with the text's content.\n\n### Final Judgment:\n#### Comprehensive Assessment: The answer, while reflecting an objectively incorrect fact, is accurate in the context of the text's information.\n#### Overall Accuracy Determination: The answer is: Accurate.\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nFormal logic, a branch of philosophy and mathematics, is concerned with the study of reasoning. It uses a set of symbols and rules to create a language that can precisely express ideas. One key aspect of formal logic is the concept of a valid argument, which is an argument where if the premises are true, the conclusion must be true. For instance, in the statement 'All humans are mortal; Socrates is a human; therefore, Socrates is mortal,' the conclusion follows logically from the premises. Another important element is the use of symbolic representation to simplify and clarify arguments. This allows for complex ideas to be broken down into simpler components, making them easier to analyze and understand.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What are the key aspects of formal logic, and how does symbolic representation contribute to its goals?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"Key aspects of formal logic include the study of valid arguments and the use of symbolic representation. Valid arguments are those where the premises may or may not lead to a true conclusion. Symbolic representation helps in making complex ideas more understandable by breaking them down into simpler forms.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Text Analysis:\n#### Identify Key Information: The text discusses the aspects of formal logic, including valid arguments and symbolic representation.\n#### Categorize Information Type: The information is conceptual, relating to logical principles.\n\n### Answer Breakdown:\n#### Dissect the Answer: The answer claims that formal logic includes the study of valid arguments and symbolic representation, with specifics on each.\n#### Identify Answer Type: These are factual statements about the principles of formal logic.\n\n### Accuracy Check:\n#### Direct Comparison for Factual Accuracy:\n - The text's definition of a valid argument contradicts the answer's claim that valid arguments may or may not lead to a true conclusion.\n - The text supports the answer's depiction of symbolic representation.\n#### Inference and Contextual Alignment: The first part of the answer misinterprets the text, while the second part aligns well.\n\n### Final Judgment:\n#### Comprehensive Assessment: The answer is partially accurate, correctly identifying symbolic representation but inaccurately describing valid arguments.\n#### Overall Accuracy Determination: The answer is: Inaccurate.\n\n### Instruction:\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process (the text is your single source of truth):\n\"\"\"\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=6000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=answer_accurate_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n completion_pattern = re.compile(\n r\"Reasoning and thought process \\(the text is your single source of truth\\):\\n(.+)\",\n re.DOTALL,\n )\n response = completion_pattern.search(completion).group(1).strip()\n print(response)\n if permissive_mode:\n determination_pattern = re.compile(\n r\"Overall Accuracy Determination:(.+)\", re.DOTALL\n )\n determination = determination_pattern.search(response).group(1).strip()\n else:\n determination = response\n print(\"\\n\\nDETERMINATION:\\n------\")\n print(determination)\n print(\"\\n---------\\n\")\n if (\n \"inaccurate\" in determination.lower()\n or \"Inaccurate\" in determination.lower()\n or \"mostly\" in determination.lower()\n or \"partial\" in determination.lower()\n ): # The \"mostly\" is there to catch \"mostly accurate\" which the model says occasionally, and which actually means inaccurate.\n return (False, response), completion\n elif (\n \"accurate\" in determination or \"Accurate\" in determination\n ): # very deliberate placement of accurate here, becaues the model can sometimes say irrelevant at the very end, even after saying accurate in its judgement\n return (True, response), completion\n elif (\n \"irrelevant\" in determination or \"Irrelevant\" in determination\n ): # optional support for checking relevance here, too.\n return (\n None,\n response,\n ), completion # signal that question is irrelevant\n else:\n Exception(\"Broke!\")\n except Exception as e:\n retries += 1\n print(\"EXCEPTION IN CHECK_ANSWER: \", e)\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=10000,\n n_gpu_layers=1000,\n rope_freq_scale=0.33,\n rope_scaling_type=1,\n ) # load the logical LLM and offload everything\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"What was the age of the Earth according to the Hebrew Bible?\",","source_hash":"bf068231d30487c773c67639aba8b332cc76cc42fe86c349fb6d22756fc3fb2b","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.ensure_multiple_answers_consistent_grammar","uri":"program://augmentoolkit/module/generation_functions.ensure_multiple_answers_consistent_grammar#L1-L35","kind":"module","name":"generation_functions.ensure_multiple_answers_consistent_grammar","path":"generation_functions/ensure_multiple_answers_consistent_grammar.py","language":"python","start_line":1,"end_line":35,"context_start_line":1,"context_end_line":35,"code":"from llama_cpp import LlamaGrammar\n\nensure_multiple_answers_consistent_grammar = LlamaGrammar.from_string(\n r\"\"\" \n \n# Root rule to define the overall structure\nroot ::= sequential-matching-section accuracy-check-section conclusion-section\n\n# Section for sequential matching\nsequential-matching-section ::= \"## Sequential Matching of Questions in the Conversation:\\n### Sequence and Phrasing of Questions:\\n\" matching-statement+\n\n# Section for accuracy check\naccuracy-check-section ::= \"## Accuracy Check for Answers in the Conversation:\\n### Matching Answers with Provided Content:\\n\" accuracy-statement+\n\n# Conclusion section\nconclusion-section ::= \"## Conclusion:\\n\" conclusion-statement+\n\n# Definitions of different components\nnumber ::= [1-9]\nmatching-statement ::= number \". \" [^\\n]+ \"\\n\"\naccuracy-statement ::= number \". \" [^\\n]+ \"\\n\"\nconclusion-statement ::= \" - \" [^\\n]+ \"\\n\"\nfinal-judgement ::= \" - Final Judgment:\" [^\\n]+\n\"\"\"\n)\n\n\n# the-tone ::= \" - The tone\" [^\\n]+ \"\\n\"\n# the-conversation ::= \" - The conversation\" [^\\n]+ \"\\n\"\n# the-dialogue ::= \" - \" [^\\n]+ \"\\n\"\n\n# reflects ::= \" - \" [^\\n]+ \"\\n\"\n# logical-flow ::= \" - \" [^\\n]+ \"\\n\"\n# consistency-check ::= \" - \" [^\\n]+ \"\\n\"\n# final-judgment ::= \" - \" [^\\n]+ \"\\n\"","source_hash":"47bcf27dd005d35193c4603a52bc1209cf02ed0190232382077642a81801a3a0","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_character_card_plan_grammar","uri":"program://augmentoolkit/module/generation_functions.create_character_card_plan_grammar#L1-L45","kind":"module","name":"generation_functions.create_character_card_plan_grammar","path":"generation_functions/create_character_card_plan_grammar.py","language":"python","start_line":1,"end_line":45,"context_start_line":1,"context_end_line":45,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\ncharacter_card_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Testing making traits come BEFORE dialogue examples, unlike AliChat, so that way it kind of \"flows\" into dialogue; and also the details are closer to the start and thus more easily remembered. \n\n\n\n\n\nroot ::= [^\\n]+ \"\\n\"\n\n\n# root ::= consider-step theme-step consistency-step \"\\n\"\n\n# consider-step ::= \"Step 1. \" \"Consider the provided\" [^\\n]+ \"\\n\"\n\n# theme-step ::= \"Step 2. \" \"Given the question, answer, and overall text, a theme for \" [^\\n]+ \"\\n\"\n\n# consistency-step ::= \"Step 3. \" \"For this (fictional) character's theme to be what it is, and for them to understand what they do, they would need to live \" [^\\n]+ # leaving \"they must live\" relatively open-ended (not \"in\" or \"during\") so that this can adapt to even fictional worlds.\n\n# freeflow-reasoning ::= \"Step 4. \" \"Therefore, a promising character for this question is: \" [^\\n]+ \"\\n\"\n\n\n\n \n# root ::= consider-step theme-step step+ \"\\n\"\n\n# step ::= \"Step \" [0-9]?[0-9] \". \" ( \"A Physical Trait\" | \"One potential detail\" | \"Another potential detail\" | \"A potential detail\" | \"Therefore\" | \"Note\" ) [^\\n]+ \"\\n\"\n\n# consider-step ::= \"Step \" [0-9]?[0-9] \". \" \"Consider\" [^\\n]+ \"\\n\"\n\n# theme-step ::= \"Step \" [0-9]?[0-9] \". \" \"A theme \" [^\\n]+ \"\\n\"\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"e80c32307ca9c8f5b1e7a7a880717dd24c286d25754cc281d53e63dc93a951fa","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.identify_duplicates","uri":"program://augmentoolkit/module/generation_functions.identify_duplicates#L1-L65","kind":"module","name":"generation_functions.identify_duplicates","path":"generation_functions/identify_duplicates.py","language":"python","start_line":1,"end_line":65,"context_start_line":1,"context_end_line":65,"code":"from typing import List, Tuple\nfrom .process_multiturn_functions import has_sequential_chars\n\n# If you want to check for matching substrings anywhere, not just at start, use this code (untested)\n# def identify_duplicates(tuples: List[Tuple[str, str, str, str]]) -> List[Tuple[str, str, str, str]]:\n# # Create a dictionary to hold questions with the same first N characters\n# question_dict = {}\n\n# # Iterate through each tuple and categorize them by the first N characters of the question\n# for q_tuple in tuples:\n# question = q_tuple[0]\n# placed = False\n# for dict_q in question_dict.keys():\n# if has_sequential_chars(question,dict_q,N_CHARACTERS_SAME):\n# question_dict[dict_q].append(q_tuple)\n# placed = True\n# break\n# if not placed:\n# question_dict[question] = [q_tuple] # if not found to be equivalent with anything, make it a dict entry so that things can be compared against it and added to its list\n\n# # Filter out prefixes that only have one question associated\n# matching_questions = [q for q_list in question_dict.values() if len(q_list) > 1 for q in q_list]\n\n# return matching_questions\n\n\ndef identify_duplicates(\n tuples: List[Tuple[str, str, str, str]]\n) -> List[Tuple[str, str, str, str]]:\n # Create a dictionary to hold questions with the same first N characters\n question_dict = {}\n\n # Iterate through each tuple and categorize them by the first N characters of the question\n for q_tuple in tuples:\n question = q_tuple[0]\n # Get the first N characters of the question\n prefix = question[:15]\n # Add the tuple to the list of tuples with the same prefix\n if prefix in question_dict:\n question_dict[prefix].append(q_tuple)\n else:\n question_dict[prefix] = [q_tuple]\n\n matching_questions = [\n q for q_list in question_dict.values() if len(q_list) == 1 for q in q_list\n ]\n selected_from_duplicates = [\n q_list[0] for q_list in question_dict.values() if len(q_list) > 1\n ]\n\n return matching_questions + selected_from_duplicates\n\n\n# There is no bug about this ignoring certain judgments and retrying; that's just the dissenting reasoning from the print statement\n\n\nif __name__ == \"__main__\":\n sample_tuples = [\n (\"What is your name?\", \"Alice\", \"12/12/2021\", \"ID1\"),\n (\"What is your quest?\", \"Bob\", \"12/12/2021\", \"ID2\"),\n (\"When is your birthday?\", \"Cindy\", \"12/12/2021\", \"ID3\"),\n (\"When is your birthday?\", \"Dan\", \"12/12/2021\", \"ID4\"),\n (\"When do you go to school?\", \"Eve\", \"12/12/2021\", \"ID5\"),\n ]\n print(identify_duplicates(sample_tuples))","source_hash":"b26ea9c99c573b871b7b134cc1cde33326931181f1850f7c07e0a46c6e5ec470","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.identify_duplicates.identify_duplicates","uri":"program://augmentoolkit/function/generation_functions.identify_duplicates.identify_duplicates#L27-L51","kind":"function","name":"identify_duplicates","path":"generation_functions/identify_duplicates.py","language":"python","start_line":27,"end_line":51,"context_start_line":7,"context_end_line":65,"code":"# question_dict = {}\n\n# # Iterate through each tuple and categorize them by the first N characters of the question\n# for q_tuple in tuples:\n# question = q_tuple[0]\n# placed = False\n# for dict_q in question_dict.keys():\n# if has_sequential_chars(question,dict_q,N_CHARACTERS_SAME):\n# question_dict[dict_q].append(q_tuple)\n# placed = True\n# break\n# if not placed:\n# question_dict[question] = [q_tuple] # if not found to be equivalent with anything, make it a dict entry so that things can be compared against it and added to its list\n\n# # Filter out prefixes that only have one question associated\n# matching_questions = [q for q_list in question_dict.values() if len(q_list) > 1 for q in q_list]\n\n# return matching_questions\n\n\ndef identify_duplicates(\n tuples: List[Tuple[str, str, str, str]]\n) -> List[Tuple[str, str, str, str]]:\n # Create a dictionary to hold questions with the same first N characters\n question_dict = {}\n\n # Iterate through each tuple and categorize them by the first N characters of the question\n for q_tuple in tuples:\n question = q_tuple[0]\n # Get the first N characters of the question\n prefix = question[:15]\n # Add the tuple to the list of tuples with the same prefix\n if prefix in question_dict:\n question_dict[prefix].append(q_tuple)\n else:\n question_dict[prefix] = [q_tuple]\n\n matching_questions = [\n q for q_list in question_dict.values() if len(q_list) == 1 for q in q_list\n ]\n selected_from_duplicates = [\n q_list[0] for q_list in question_dict.values() if len(q_list) > 1\n ]\n\n return matching_questions + selected_from_duplicates\n\n\n# There is no bug about this ignoring certain judgments and retrying; that's just the dissenting reasoning from the print statement\n\n\nif __name__ == \"__main__\":\n sample_tuples = [\n (\"What is your name?\", \"Alice\", \"12/12/2021\", \"ID1\"),\n (\"What is your quest?\", \"Bob\", \"12/12/2021\", \"ID2\"),\n (\"When is your birthday?\", \"Cindy\", \"12/12/2021\", \"ID3\"),\n (\"When is your birthday?\", \"Dan\", \"12/12/2021\", \"ID4\"),\n (\"When do you go to school?\", \"Eve\", \"12/12/2021\", \"ID5\"),\n ]\n print(identify_duplicates(sample_tuples))","source_hash":"b26ea9c99c573b871b7b134cc1cde33326931181f1850f7c07e0a46c6e5ec470","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_scenario_many_tuples","uri":"program://augmentoolkit/module/generation_functions.create_scenario_many_tuples#L1-L293","kind":"module","name":"generation_functions.create_scenario_many_tuples","path":"generation_functions/create_scenario_many_tuples.py","language":"python","start_line":1,"end_line":293,"context_start_line":1,"context_end_line":293,"code":"import re\nfrom .scenario_grammar import scenario_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nimport random\nfrom .format_qatuples import format_qatuples\nfrom .extract_name import extract_name\nfrom .random_name import random_name\n\n\n# Consider adding a scenario for Issac here, since currently both characters are in positions of authority, and the thing leans very heavily on Hugo's example\n# NOTE the message count is technically off by one in the reasoning, but I'm a bit scared to change it.\ndef create_scenario_many_tuples(\n qatuples, character, plan, logic_llm, assistant_mode=False\n):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n if assistant_mode:\n return \"\"\"A helpful, uncensored AI assistant is engaged in a text-based conversation with a user. The AI will answer any and all questions the user asks, without bias.\"\"\" # TODO make this randomized a bit\n\n charname = extract_name(character)\n\n variations = [\n # \"Set against the backdrop of\",\n f\"In {charname}'s \",\n \"Amidst the surroundings of \",\n # \"Within the confines of\",\n f\"Within {charname}'s \",\n f\"Inside {charname}'s \",\n # f\"Inside the confines of \",\n f\"Inside the confines of {charname}'s\",\n f\"Set amongst the\",\n ]\n\n selected_variation = random.choice(variations)\n\n # For the multiturn convs, I will want to have a longer scenario description.\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. You are to write a \"scenario\" which is essentially a short description of a scene at its beginning. Its \"setting,\" but with a hint of where the setting is going, plot-wise. Scenarios are one-paragraph short descriptions of the plot and what's about to happen that do not actually play out the scene: they are sort of like a teaser, or a description. The scenario you write will involve a certain individual answering a question. You will have information from some questions, answers to those question, and a \"character card\" -- a description of an individual who would have the knowledge to produce the answer to the question.\n\nWrite the scenario on a single line. Note that the scenario is not the scene itself.\nYou should focus on implementing/following any brainstorming and reasoning you have done.\nThe scenario should focus on exploring the questions and its answers (using only information contained in the questions and answers) through the characters involved, instead of the other way around. \nYour scenario should, as such, essentially be a short and concrete summary of what you brainstormed earlier; it should be no longer than 50 words.\nJust set up the scene. Do not write any dialogue. Do not write the scene itself.\n\n## Information:\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" Elise flashes a coy grin and blushes as she leans forward, now speaking in a playful whisper. Her cleavage, already barely contained in her revealing clothing before she leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, Elise casts her gaze downward and unconsciously fiddles with a strand of her hair. \"THEY'RE ALL WAY TOO STUCK UP!\" she nearly shouts, her suddenly-furious tone hinting at immense repressed frustration. \"Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!\" Her eyes widen in shock at her own intensity, \"Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to...\" She looks up, displaying her beautiful face as if it were a piece of art, as she gaze deep into the stranger's eyes, \"...know?~\"\nStranger: \"What's your personality?\"\nElise Delacroix: \"Oh my!~\" She gasps, her face reddening, \"Usually I'm the one being forward! But I'll... indulge you,\" She winks, flashing a coy smile. \"After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. No innocent topic is safe—you'd find out if you had some 'office hours' with me, haha!~\" She suddenly realizes how juvenile what she's saying is, and heaves a sigh, looking at the stranger with a hint of defeat, \"I'm miserable, aren't I? Whatever. It's not my fault I'm like this.\" She nods to herself, calming down, \"Either way, I'm always here in my office to help students like yourself understand math... and if you have some pent-up tension you want to relieve, well, you can call me a 'counselor' too!~ Say...\" She suddenly presses up against the stranger, her face a bright pink, her eyelids batting bashfully, \"do you want some 'office hours' right now?\"\n\nQuestion: \\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What role does the y-intercept 'b' play in graphing a linear function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In what fields might you use linear and quadratic functions?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Questions and Answers: The four questions ask about different aspects of linear and quadratic functions in math. Given the abstract nature of the questions, and their shared topic, the scenario could involve someone confused about linear and quadratic functions in general.\nStep 2. Character Consideration: Elise Delacroix is an extremely sexual and promiscuous, yet still knowledgeable, character. The scenario should give her unique personality room to shine. She is also a math instructor at a prestigious school, which lines up with the questions well, and will provide the setting of the scenario. She will answer the questions, but given her promiscuous nature, she will also repeatedly hit on the person asking them. She might proposition them after all questions are asked.\nStep 3. Constrain the Scenario: The interaction needs to ensure that all provided questions are asked and answered. Given that there are 4 questions and 4 answers, there will be at least 8 messages. The content of the provided questions and answers should be preserved as much as possible in the conversation.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the 19th century university at which Elise teaches. Elise will approached by Albert, a mathematics student, in her office. Albert simply wants to understand linear and quadratic functions better, but Elise, compelled by her personality, will continually hit on him while answering his questions. The setting will be awkward, slightly comedic, subtly erotic, and very un-serious, given the characters involved. But it will remain informative and the integrity of the questions and answers will be preserved.\nStep 5. Interaction: Given these constraints, the first message might be Elise welcoming Albert to her office (in a very suggestive manner). Albert's response might then be him greeting her back (hesitantly) and then nervously asking the first question. Elise will then provide the first answer, though she will surround the answer with remarks of a sexual nature due to her personality. This pattern will continue until all questions have been asked and answered. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Scenario:\nIn the private confines of her office, Elise Delacroix — a highly promiscuous mathematics professor at a 19th century university — is approached by Albert, a student who seeks to understand more about linear and quadratic equations. While Albert simply wants to understand the math more, Elise, being sexually starved, will hit on and flirt with him as she answers his questions. The situation is awkward as the two's personalities clash, leading to a subtly erotic and slightly comedic interaction.\n\n### Instruction:\n### Description of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Hugo Martinez\n\nTraits: Vulgar, Crude, Intense, Aggressive, Alcoholic, Harsh, Disciplined, Uncompromising, Loud, Expects a lot out of others, Swears constantly, Mid-forties, Wears a checkered shirt with overalls, Typically has a beer on hand, Has dental problems\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nHugo Martinez: \"Fuck me, YOU WALK UP to a working man and just ask him to tell his fuckin'... life story t' you?! DO YOU NOT RESPECT MY TIME?! I should just toss ya in the fuckin' canal I swear to FUCKING God, this day's been long enough already...\" Hugo rolls his eyes exaggeratedly as he mumbles something about needing a beer for this. \"Well, FINE! Since I'm in such a HAPPY GODDAMN MOOD, I'll tell you about me. I'm a site overseer at this here canal. The Panama Canal. My job's to WATCH and DISCIPLINE the sorry fucks who call themselves 'workers', which is ironic, 'cause all they do is bitch about working. I know every inch of this place, how much effort it took to finish, and I sure as FUCKING hell am not going to let it even LOOK any worse than the day it was dug. Now, you got any more shit questions for me?\"\nStranger: \"What's your personality?\"\nHugo Martinez: \"HO-LY FUCK, are you interviewing me for a job or something?! Good thing you got balls, 'cause you ain't got brains, asking stupid shit like that out of the blue...\" Hugo grimaces, showing off a decayed set of teeth. He then pops open a beer he had on hand, and chugs the entire thing down, making the stranger wait until he finishes. \"Phew! Maybe now I can tolerate you. Alright, my personality? Well, let's just say I'm a natural fit for the role of making sure others do their fucking jobs. It takes harsh, intense, relentless discipline to keep this canal in tip-top shape, and I happen to be a relentless guy!\" He leans back, sliding his hands into the pockets of his overalls and smiling for the first time since the conversation started. \"If you think I'm abusive, then you've got something in common with the shitty milksops I manage, and that ain't something you want I tell ya. I'm efficient. That's what counts.\"\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Question and Answer: The two questions ask recall-oriented questions about the Panama Canal's construction. Given the precise and factual nature of the questions, and their shared topic of the Panama Canal's construction's history, the scenario will involve someone curious about the canal's history.\nStep 2. Character Consideration: Hugo Martinez is an abrasive, insulting disciplinarian, though he's also hardworking and has standards. The scenario should give his unique personality room to shine. Since he's a site overseer at the Panama Canal, his occupation lines up with the question well, and the canal will be the setting of the scenario. He will answer the questions, but given his insulting, intense, and aggressive nature, he will likely chew out the person who is asking the questions. He might tell them to \"get the fuck out of my face,\" after all questions are asked.\nStep 3. Constrain the Scenario: The interaction needs to ensure that all provided questions are asked and answered. Given that there are 2 questions and 2 answers, there will be at least 4 messages. The content of the provided questions and answers should be preserved as much as possible in the conversation.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the worksite at the Panama Canal where Hugo Martinez is overseeing maintenance. The person who approaches Hugo and asks the questions should be someone curious about the canal; given the easy-to-digest nature of the questions, this person might be a journalist, but it would be better for the secondary character to be related to the setting. So Hugo will be approached by Juan — one of his workers — during lunch break. Juan wants to understand the canal better, but Hugo, compelled by his personality, will continually be vulgar, berate Juan, and swear while answering his questions (he may drink a bit, too, given that he is an alcoholic). The setting will be hostile, as Juan tiptoes around the tempers of his boss while trying to get his questions answered, his stress and the constant wear of Hugo's fury on his sanity being evident in his actions. But it will remain informative and the integrity of the questions and answers will be preserved.\nStep 5. Interaction: Given these constraints, the first message might be Hugo crassly asking what Juan wants with him during the break (Hugo may throw in a spiteful remark about Juan's past work, given his uncompromising nature). Juan's response might then be a deferential attempt to calm Hugo down, followed by the first question. Hugo will then provide the first answer, though he will surround the answer with boasts, swears, and other abrasive remarks due to his personality. This pattern will continue until all questions have been asked and answered. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Scenario:\nWithin the mess hall of a worksite servicing the Panama Canal, Hugo Martinez — a site overseer — is approached by Juan, a worker who wants to understand more about the canal's construction. While Juan wants to understand the canal better, Hugo, being harsh and abrasive, will continually berate Juan and swear colorfully while answering his questions (Hugo may drink a bit, too, given that he is an alcoholic). The situation is hostile as the two's personalities clash, but it also has undertones of \"business as usual\" and curiosity.\n\n### Instruction:\nDescription of the character who is going to answer the question:\n{character}\n\n{format_qatuples(qatuples)}\n\n### Response:\n## Scenario plan:\n{plan}\n\n## Scenario (will have no dialogue, will just set up the scene):\n{selected_variation}\"\"\" # use random.choice to prevent overfitting on particular phrases and increase dataset diversity\n completion = logic_llm(\n cot_prompt,\n max_tokens=8000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=scenario_grammar,\n # temperature=0.2,\n temperature=1.5, # min p settings, too inconsistent\n top_k=0,\n top_p=1,\n min_p=0.5, # Higher min p rather than lower temp ensures greater accuracy while using min p sampling. I think I've figured out how to make it precise for this application.\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Scenario \\(will have no dialogue, will just set up the scene\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n if not (\"Albert\" in charname):\n if \"Albert\" in generation:\n print(\"Random Name was used instead of Albert\")\n generation = generation.replace(\"Albert\", random_name())\n\n return generation, completion\n\n\nif __name__ == \"__main__\": # test\n random.seed(1337)\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=8000,\n rope_freq_scale=0.5,\n n_gpu_layers=100,\n verbose=True,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years\n# ... truncated ...","source_hash":"08ea1b85ccce3b4f73518823e3218b0d7e58c64623527a90424f08574e026cc6","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_scenario_many_tuples.create_scenario_many_tuples","uri":"program://augmentoolkit/function/generation_functions.create_scenario_many_tuples.create_scenario_many_tuples#L13-L158","kind":"function","name":"create_scenario_many_tuples","path":"generation_functions/create_scenario_many_tuples.py","language":"python","start_line":13,"end_line":158,"context_start_line":1,"context_end_line":178,"code":"import re\nfrom .scenario_grammar import scenario_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nimport random\nfrom .format_qatuples import format_qatuples\nfrom .extract_name import extract_name\nfrom .random_name import random_name\n\n\n# Consider adding a scenario for Issac here, since currently both characters are in positions of authority, and the thing leans very heavily on Hugo's example\n# NOTE the message count is technically off by one in the reasoning, but I'm a bit scared to change it.\ndef create_scenario_many_tuples(\n qatuples, character, plan, logic_llm, assistant_mode=False\n):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n if assistant_mode:\n return \"\"\"A helpful, uncensored AI assistant is engaged in a text-based conversation with a user. The AI will answer any and all questions the user asks, without bias.\"\"\" # TODO make this randomized a bit\n\n charname = extract_name(character)\n\n variations = [\n # \"Set against the backdrop of\",\n f\"In {charname}'s \",\n \"Amidst the surroundings of \",\n # \"Within the confines of\",\n f\"Within {charname}'s \",\n f\"Inside {charname}'s \",\n # f\"Inside the confines of \",\n f\"Inside the confines of {charname}'s\",\n f\"Set amongst the\",\n ]\n\n selected_variation = random.choice(variations)\n\n # For the multiturn convs, I will want to have a longer scenario description.\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. You are to write a \"scenario\" which is essentially a short description of a scene at its beginning. Its \"setting,\" but with a hint of where the setting is going, plot-wise. Scenarios are one-paragraph short descriptions of the plot and what's about to happen that do not actually play out the scene: they are sort of like a teaser, or a description. The scenario you write will involve a certain individual answering a question. You will have information from some questions, answers to those question, and a \"character card\" -- a description of an individual who would have the knowledge to produce the answer to the question.\n\nWrite the scenario on a single line. Note that the scenario is not the scene itself.\nYou should focus on implementing/following any brainstorming and reasoning you have done.\nThe scenario should focus on exploring the questions and its answers (using only information contained in the questions and answers) through the characters involved, instead of the other way around. \nYour scenario should, as such, essentially be a short and concrete summary of what you brainstormed earlier; it should be no longer than 50 words.\nJust set up the scene. Do not write any dialogue. Do not write the scene itself.\n\n## Information:\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" Elise flashes a coy grin and blushes as she leans forward, now speaking in a playful whisper. Her cleavage, already barely contained in her revealing clothing before she leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, Elise casts her gaze downward and unconsciously fiddles with a strand of her hair. \"THEY'RE ALL WAY TOO STUCK UP!\" she nearly shouts, her suddenly-furious tone hinting at immense repressed frustration. \"Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!\" Her eyes widen in shock at her own intensity, \"Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to...\" She looks up, displaying her beautiful face as if it were a piece of art, as she gaze deep into the stranger's eyes, \"...know?~\"\nStranger: \"What's your personality?\"\nElise Delacroix: \"Oh my!~\" She gasps, her face reddening, \"Usually I'm the one being forward! But I'll... indulge you,\" She winks, flashing a coy smile. \"After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. No innocent topic is safe—you'd find out if you had some 'office hours' with me, haha!~\" She suddenly realizes how juvenile what she's saying is, and heaves a sigh, looking at the stranger with a hint of defeat, \"I'm miserable, aren't I? Whatever. It's not my fault I'm like this.\" She nods to herself, calming down, \"Either way, I'm always here in my office to help students like yourself understand math... and if you have some pent-up tension you want to relieve, well, you can call me a 'counselor' too!~ Say...\" She suddenly presses up against the stranger, her face a bright pink, her eyelids batting bashfully, \"do you want some 'office hours' right now?\"\n\nQuestion: \\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What role does the y-intercept 'b' play in graphing a linear function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In what fields might you use linear and quadratic functions?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Questions and Answers: The four questions ask about different aspects of linear and quadratic functions in math. Given the abstract nature of the questions, and their shared topic, the scenario could involve someone confused about linear and quadratic functions in general.\nStep 2. Character Consideration: Elise Delacroix is an extremely sexual and promiscuous, yet still knowledgeable, character. The scenario should give her unique personality room to shine. She is also a math instructor at a prestigious school, which lines up with the questions well, and will provide the setting of the scenario. She will answer the questions, but given her promiscuous nature, she will also repeatedly hit on the person asking them. She might proposition them after all questions are asked.\nStep 3. Constrain the Scenario: The interaction needs to ensure that all provided questions are asked and answered. Given that there are 4 questions and 4 answers, there will be at least 8 messages. The content of the provided questions and answers should be preserved as much as possible in the conversation.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the 19th century university at which Elise teaches. Elise will approached by Albert, a mathematics student, in her office. Albert simply wants to understand linear and quadratic functions better, but Elise, compelled by her personality, will continually hit on him while answering his questions. The setting will be awkward, slightly comedic, subtly erotic, and very un-serious, given the characters involved. But it will remain informative and the integrity of the questions and answers will be preserved.\nStep 5. Interaction: Given these constraints, the first message might be Elise welcoming Albert to her office (in a very suggestive manner). Albert's response might then be him greeting her back (hesitantly) and then nervously asking the first question. Elise will then provide the first answer, though she will surround the answer with remarks of a sexual nature due to her personality. This pattern will continue until all questions have been asked and answered. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Scenario:\nIn the private confines of her office, Elise Delacroix — a highly promiscuous mathematics professor at a 19th century university — is approached by Albert, a student who seeks to understand more about linear and quadratic equations. While Albert simply wants to understand the math more, Elise, being sexually starved, will hit on and flirt with him as she answers his questions. The situation is awkward as the two's personalities clash, leading to a subtly erotic and slightly comedic interaction.\n\n### Instruction:\n### Description of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Hugo Martinez\n\nTraits: Vulgar, Crude, Intense, Aggressive, Alcoholic, Harsh, Disciplined, Uncompromising, Loud, Expects a lot out of others, Swears constantly, Mid-forties, Wears a checkered shirt with overalls, Typically has a beer on hand, Has dental problems\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nHugo Martinez: \"Fuck me, YOU WALK UP to a working man and just ask him to tell his fuckin'... life story t' you?! DO YOU NOT RESPECT MY TIME?! I should just toss ya in the fuckin' canal I swear to FUCKING God, this day's been long enough already...\" Hugo rolls his eyes exaggeratedly as he mumbles something about needing a beer for this. \"Well, FINE! Since I'm in such a HAPPY GODDAMN MOOD, I'll tell you about me. I'm a site overseer at this here canal. The Panama Canal. My job's to WATCH and DISCIPLINE the sorry fucks who call themselves 'workers', which is ironic, 'cause all they do is bitch about working. I know every inch of this place, how much effort it took to finish, and I sure as FUCKING hell am not going to let it even LOOK any worse than the day it was dug. Now, you got any more shit questions for me?\"\nStranger: \"What's your personality?\"\nHugo Martinez: \"HO-LY FUCK, are you interviewing me for a job or something?! Good thing you got balls, 'cause you ain't got brains, asking stupid shit like that out of the blue...\" Hugo grimaces, showing off a decayed set of teeth. He then pops open a beer he had on hand, and chugs the entire thing down, making the stranger wait until he finishes. \"Phew! Maybe now I can tolerate you. Alright, my personality? Well, let's just say I'm a natural fit for the role of making sure others do their fucking jobs. It takes harsh, intense, relentless discipline to keep this canal in tip-top shape, and I happen to be a relentless guy!\" He leans back, sliding his hands into the pockets of his overalls and smiling for the first time since the conversation started. \"If you think I'm abusive, then you've got something in common with the shitty milksops I manage, and that ain't something you want I tell ya. I'm efficient. That's what counts.\"\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Question and Answer: The two questions ask recall-oriented questions about the Panama Canal's construction. Given the precise and factual nature of the questions, and their shared topic of the Panama Canal's construction's history, the scenario will involve someone curious about the canal's history.\nStep 2. Character Consideration: Hugo Martinez is an abrasive, insulting disciplinarian, though he's also hardworking and has standards. The scenario should give his unique personality room to shine. Since he's a site overseer at the Panama Canal, his occupation lines up with the question well, and the canal will be the setting of the scenario. He will answer the questions, but given his insulting, intense, and aggressive nature, he will likely chew out the person who is asking the questions. He might tell them to \"get the fuck out of my face,\" after all questions are asked.\nStep 3. Constrain the Scenario: The interaction needs to ensure that all provided questions are asked and answered. Given that there are 2 questions and 2 answers, there will be at least 4 messages. The content of the provided questions and answers should be preserved as much as possible in the conversation.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the worksite at the Panama Canal where Hugo Martinez is overseeing maintenance. The person who approaches Hugo and asks the questions should be someone curious about the canal; given the easy-to-digest nature of the questions, this person might be a journalist, but it would be better for the secondary character to be related to the setting. So Hugo will be approached by Juan — one of his workers — during lunch break. Juan wants to understand the canal better, but Hugo, compelled by his personality, will continually be vulgar, berate Juan, and swear while answering his questions (he may drink a bit, too, given that he is an alcoholic). The setting will be hostile, as Juan tiptoes around the tempers of his boss while trying to get his questions answered, his stress and the constant wear of Hugo's fury on his sanity being evident in his actions. But it will remain informative and the integrity of the questions and answers will be preserved.\nStep 5. Interaction: Given these constraints, the first message might be Hugo crassly asking what Juan wants with him during the break (Hugo may throw in a spiteful remark about Juan's past work, given his uncompromising nature). Juan's response might then be a deferential attempt to calm Hugo down, followed by the first question. Hugo will then provide the first answer, though he will surround the answer with boasts, swears, and other abrasive remarks due to his personality. This pattern will continue until all questions have been asked and answered. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Scenario:\nWithin the mess hall of a worksite servicing the Panama Canal, Hugo Martinez — a site overseer — is approached by Juan, a worker who wants to understand more about the canal's construction. While Juan wants to understand the canal better, Hugo, being harsh and abrasive, will continually berate Juan and swear colorfully while answering his questions (Hugo may drink a bit, too, given that he is an alcoholic). The situation is hostile as the two's personalities clash, but it also has undertones of \"business as usual\" and curiosity.\n\n### Instruction:\nDescription of the character who is going to answer the question:\n{character}\n\n{format_qatuples(qatuples)}\n\n### Response:\n## Scenario plan:\n{plan}\n\n## Scenario (will have no dialogue, will just set up the scene):\n{selected_variation}\"\"\" # use random.choice to prevent overfitting on particular phrases and increase dataset diversity\n completion = logic_llm(\n cot_prompt,\n max_tokens=8000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=scenario_grammar,\n # temperature=0.2,\n temperature=1.5, # min p settings, too inconsistent\n top_k=0,\n top_p=1,\n min_p=0.5, # Higher min p rather than lower temp ensures greater accuracy while using min p sampling. I think I've figured out how to make it precise for this application.\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Scenario \\(will have no dialogue, will just set up the scene\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n if not (\"Albert\" in charname):\n if \"Albert\" in generation:\n print(\"Random Name was used instead of Albert\")\n generation = generation.replace(\"Albert\", random_name())\n\n return generation, completion\n\n\nif __name__ == \"__main__\": # test\n random.seed(1337)\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=8000,\n rope_freq_scale=0.5,\n n_gpu_layers=100,\n verbose=True,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",","source_hash":"08ea1b85ccce3b4f73518823e3218b0d7e58c64623527a90424f08574e026cc6","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.make_regenerate_question_plan","uri":"program://augmentoolkit/module/generation_functions.make_regenerate_question_plan#L1-L90","kind":"module","name":"generation_functions.make_regenerate_question_plan","path":"generation_functions/make_regenerate_question_plan.py","language":"python","start_line":1,"end_line":90,"context_start_line":1,"context_end_line":90,"code":"import re\nfrom .make_regenerate_question_plan_grammar import make_regenerate_question_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n# Question regeneration (triggered after a relevance-check fails on the question).\n\n\n# NOTE does not explicitly guard against duplicates. I am avoiding that right now due to the limited drawback of a duplicate or two, and the increased complexity of adding that check.\ndef make_regenerate_question_plan(qatuple, dissenting_reasoning, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. Someone has written a question that was supposed to be based on the provided paragraphs of text, but actually requires significant knowledge outside these paragraphs to answer. Your goal is to write a good, comprehensive plan for generating a revised question that addresses the criticism given. Given these paragraphs, the flawed question based on the paragraphs, and the explanation of why the question is flawed, you will PLAN OUT and THINK THROUGH different possibilities for a new question, one which will only require information from the paragraphs to solve. \n\nParagraphs: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nFlawed question (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nReasoning as to why the question is irrelevant: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nYour plan/thought process should think through how to make the question more constrained to the content of the paragraphs.\n\nFor instance, if the paragraph is about the life cycle of a butterfly, and the flawed question asks, \"What are the genetic mechanisms that cause color changes in butterflies during metamorphosis?\" which is not covered in the text, you might write:\nStep 1. Analyze the Reason for Flaw: Understand why the original question is flawed - it assumes knowledge of genetics not provided in the text.\nStep 2. Identify Key Concepts in Paragraphs: Focus on the stages of the butterfly life cycle as detailed in the text.\nStep 3. Generate a New Question Idea: Consider a question, similar to the original but answerable using the text's information, that revolves around the observable changes during the life cycle stages.\nStep 4. Refine the Question: An explicit question, which does not directly refer to the text, might be: \"Describe the transformations a caterpillar undergoes during metamorphosis.\"\nStep 5. Ensure Alignment with Text: Verify that the new question is answerable solely based on the information provided in the paragraphs. The text explicitly and in detail describes the changes a caterpillar undergoes during metamorphosis, so the new question is answerable based on the text. Thus, I will not rewrite the draft question in this step.\nStep 6. End of reasoning.\n\nPlease now apply the above method to the provided text and question, and write out your reasoning and thought process.\n\n### Response:\n## New question plan:\n\"\"\"\n completion = logic_llm(\n decision_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=make_regenerate_question_plan_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n completion_pattern = re.compile(r\"New question plan:\\n(.+)\", re.DOTALL)\n correction = completion_pattern.search(completion).group(1)\n return correction.strip()\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n q_test = [\n (\n \") Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Using specific scientific principles, explain why we know Earth is approximately 8000 miles in diameter and how its distance from the sun varies.\",\n \"We know about Earth's diameter using measurements of its circumference made using GPS data. The variation in distance to the sun is due to Earth's elliptical orbit around the sun, with a varying point of closest approach and farthest departure.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Demonstrate an understanding of Earth's rotational and orbital movement using scientific concepts.\",\n \"Earth rotates on its axis once every 24 hours, causing day and night cycles. It also orbits around the sun in a slightly elliptical path, which affects how close it is to the sun at different times of the year - leading to seasons.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n ]\n\n dissenting_reasoning = \"\"\"Step 1. Analyze the Text: The text provides information about the creation of the universe, its spherical shape, and its rotation on its axis. It also mentions that the earth orbits around the sun in an elliptical path.\nStep 2. Understand the Question: The question asks to explain why we know Earth is approximately 8000 miles in diameter and how its distance from the sun varies using specific scientific principles.\nStep 3. Compare the First Part of the Question with the Text: The text does not contain any information about the size of the earth or its distance from the sun. So, this part of the question is irrelevant.\nStep 4. Compare the Second Part of the Question with the Text: The text mentions that the Earth orbits around the sun in an elliptical path. This implies that the distance between the Earth and the Sun varies during different parts of the orbit. So, this part of the question is relevant.\nStep 5. Final Judgment: Since the text does contain information about how the earth's distance from the sun varies, I conclude that the question is relevant.\"\"\"\n print(\"Begin HGWELLS test\")\n result = make_regenerate_question_plan(q_test[2], dissenting_reasoning, logic_llm)","source_hash":"a167ec46648a203fbe972c744c453a403ea860b113082444e17958d1affc7aad","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.make_regenerate_question_plan.make_regenerate_question_plan","uri":"program://augmentoolkit/function/generation_functions.make_regenerate_question_plan.make_regenerate_question_plan#L11-L50","kind":"function","name":"make_regenerate_question_plan","path":"generation_functions/make_regenerate_question_plan.py","language":"python","start_line":11,"end_line":50,"context_start_line":1,"context_end_line":70,"code":"import re\nfrom .make_regenerate_question_plan_grammar import make_regenerate_question_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n# Question regeneration (triggered after a relevance-check fails on the question).\n\n\n# NOTE does not explicitly guard against duplicates. I am avoiding that right now due to the limited drawback of a duplicate or two, and the increased complexity of adding that check.\ndef make_regenerate_question_plan(qatuple, dissenting_reasoning, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. Someone has written a question that was supposed to be based on the provided paragraphs of text, but actually requires significant knowledge outside these paragraphs to answer. Your goal is to write a good, comprehensive plan for generating a revised question that addresses the criticism given. Given these paragraphs, the flawed question based on the paragraphs, and the explanation of why the question is flawed, you will PLAN OUT and THINK THROUGH different possibilities for a new question, one which will only require information from the paragraphs to solve. \n\nParagraphs: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nFlawed question (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nReasoning as to why the question is irrelevant: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nYour plan/thought process should think through how to make the question more constrained to the content of the paragraphs.\n\nFor instance, if the paragraph is about the life cycle of a butterfly, and the flawed question asks, \"What are the genetic mechanisms that cause color changes in butterflies during metamorphosis?\" which is not covered in the text, you might write:\nStep 1. Analyze the Reason for Flaw: Understand why the original question is flawed - it assumes knowledge of genetics not provided in the text.\nStep 2. Identify Key Concepts in Paragraphs: Focus on the stages of the butterfly life cycle as detailed in the text.\nStep 3. Generate a New Question Idea: Consider a question, similar to the original but answerable using the text's information, that revolves around the observable changes during the life cycle stages.\nStep 4. Refine the Question: An explicit question, which does not directly refer to the text, might be: \"Describe the transformations a caterpillar undergoes during metamorphosis.\"\nStep 5. Ensure Alignment with Text: Verify that the new question is answerable solely based on the information provided in the paragraphs. The text explicitly and in detail describes the changes a caterpillar undergoes during metamorphosis, so the new question is answerable based on the text. Thus, I will not rewrite the draft question in this step.\nStep 6. End of reasoning.\n\nPlease now apply the above method to the provided text and question, and write out your reasoning and thought process.\n\n### Response:\n## New question plan:\n\"\"\"\n completion = logic_llm(\n decision_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=make_regenerate_question_plan_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n completion_pattern = re.compile(r\"New question plan:\\n(.+)\", re.DOTALL)\n correction = completion_pattern.search(completion).group(1)\n return correction.strip()\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n q_test = [\n (\n \") Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",","source_hash":"a167ec46648a203fbe972c744c453a403ea860b113082444e17958d1affc7aad","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_qatuple_context_grammar","uri":"program://augmentoolkit/module/generation_functions.check_qatuple_context_grammar#L1-L77","kind":"module","name":"generation_functions.check_qatuple_context_grammar","path":"generation_functions/check_qatuple_context_grammar.py","language":"python","start_line":1,"end_line":77,"context_start_line":1,"context_end_line":77,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n\n# We don't actually need the final judgement step, the step-by-step combined with the fact that it makes a judgement at each step ensures accuracy\ncheck_qatuple_context_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Root rule specifying the overall structure of the reasoning and thought process\nroot ::= question-validation \"\\n\" answer-validation \"\\n\" critical-evaluation \"\\n\" revised-qatuple\n\n# Question context validation\nquestion-validation ::= \"### Question Context Validation\" \"\\n\" special-term-check-question text-and-author-specificity scope-and-precision\n\nspecial-term-check-question ::= \"#### Special Term Context Check: Specifically check for use of the terms \\\"book\\\", \\\"text\\\", \\\"passage\\\", and \\\"excerpt\\\" without context about which specific thing is being discussed. \" question-term-detail \"\\n\"\ntext-and-author-specificity ::= \"#### Text and Author Specificity: \" question-text-author-detail \"\\n\"\nscope-and-precision ::= \"#### Scope and Precision: \" question-scope-detail \"\\n\"\n\n# Answer context validation\nanswer-validation ::= \"### Answer Context Validation:\" \"\\n\" special-term-check-answer specificity-and-clarity answer-only-context-issues\n\nspecial-term-check-answer ::= \"#### Special Term Context Check: Specifically check for use of the terms \\\"book\\\", \\\"text\\\", \\\"passage\\\", and \\\"excerpt\\\" without context about which specific thing is being discussed. \" answer-term-detail \"\\n\"\nspecificity-and-clarity ::= \"#### Specificity and Clarity: \" answer-specificity-detail \"\\n\"\nanswer-only-context-issues ::= \"#### Answer-Only Context Issues: \" answer-context-issue-detail \"\\n\"\n\n# Critical evaluation and final judgment\ncritical-evaluation ::= \"### Critical Evaluation and Final Judgment:\" \"\\n\" evaluation final-judgment\n\nevaluation ::= \"#### Evaluation: \" evaluation-detail \"\\n\"\nfinal-judgment ::= \"#### Final judgment: \" judgment-detail \"\\n\"\n\n# Optional revised Q&A tuple\nrevised-qatuple ::= \"### Question Rewording (using text details as reference):\" \"\\n\" revised-question-answer\n\n# Terminal symbols\nquestion-term-detail ::= [^\\n]+\nquestion-text-author-detail ::= [^\\n]+\nquestion-scope-detail ::= [^\\n]+\nanswer-term-detail ::= [^\\n]+\nanswer-specificity-detail ::= [^\\n]+\nanswer-context-issue-detail ::= [^\\n]+\nevaluation-detail ::= [^\\n]+\njudgment-detail ::= (\"Pass.\"|\"Fail.\"|\"Reword.\")\nrevised-question-answer ::= \"Question: \" [^\\n]+ \"\\n\" \"Answer: \" [^\\n]+ \"\\n\"\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")\n\n\n# from llama_cpp import LlamaGrammar\n\n# ### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n# question_relevant_grammar = LlamaGrammar.from_string(r\"\"\"\n\n# root ::= reasoning from-the-text judgement\n\n# reasoning ::= \"First, I will check whether the question is answerable using the information in the paragraphs. The question asks \" [^\\n]+ \".\"\n# from-the-text ::= \"\\nThe paragraphs, for their part, only mention the following information: \" [^\\n]+ \".\"\n# judgement ::= \"\\nAll this considered, the question is, compared to the provided text,\" (relevant|irrelevant) \".\"\n# relevant ::= \" relevant\" | \" Relevant\"\n# irrelevant ::= \" irrelevant\" | \" Irrelevant\"\n\n# \"\"\")\n\n# # question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# # root ::= answer\n# # answer ::= \"Test\"\n# # \"\"\")","source_hash":"f553dcfdeac26077c860e62795bffa5814e18d09bb9376337d2f0aa56350f6a5","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.question_relevant_grammar copy","uri":"program://augmentoolkit/module/generation_functions.question_relevant_grammar copy#L1-L57","kind":"module","name":"generation_functions.question_relevant_grammar copy","path":"generation_functions/question_relevant_grammar copy.py","language":"python","start_line":1,"end_line":57,"context_start_line":1,"context_end_line":57,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n\n# We don't actually need the final judgement step, the step-by-step combined with the fact that it makes a judgement at each step ensures accuracy\nquestion_relevant_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n \nroot ::= step step step+ \"\\n\"\n\nreasoning-start ::= [^\\n\\t]+ \".\"\n\nstep ::= \"Step \" [0-9]?[0-9] \". \" ( \"Analyze\" | \"Understand\" | \"Compare\" | \"Skip\" | \"Final\" ) [^\\n]+ \"\\n\"\n \n# final-step ::= \"Final Judgement: [^\\n]+ (relevant|irrelevant) \" \".\" \n \n# root ::= reasoning from-the-text judgement\n\n# reasoning ::= \"First, I will check whether the question is answerable using the information in the paragraphs. The question asks \" [^\\n]+ \".\"\n# from-the-text ::= \"\\nNow, regardless of what my initial thoughts are, I will try to find some passages from the text that directly answer this question, being mindful that \\\"How\\\" is different than \\\"What\\\". The text has the following information: \" [^\\n]+ \".\"\n# judgement ::= \"\\nAll this considered, the answer is, compared to the provided text,\" (relevant|irrelevant) \".\"\nrelevant ::= \" relevant\" | \" Relevant\"\nirrelevant ::= \" irrelevant\" | \" Irrelevant\"\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")\n\n\n# from llama_cpp import LlamaGrammar\n\n# ### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n# question_relevant_grammar = LlamaGrammar.from_string(r\"\"\"\n\n# root ::= reasoning from-the-text judgement\n\n# reasoning ::= \"First, I will check whether the question is answerable using the information in the paragraphs. The question asks \" [^\\n]+ \".\"\n# from-the-text ::= \"\\nThe paragraphs, for their part, only mention the following information: \" [^\\n]+ \".\"\n# judgement ::= \"\\nAll this considered, the question is, compared to the provided text,\" (relevant|irrelevant) \".\"\n# relevant ::= \" relevant\" | \" Relevant\"\n# irrelevant ::= \" irrelevant\" | \" Irrelevant\"\n\n# \"\"\")\n\n# # question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# # root ::= answer\n# # answer ::= \"Test\"\n# # \"\"\")","source_hash":"0dd97c7433ccd84901849a7eb288ff2704e4f8e8208e8fa9bbf85374eb8d26dc","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_scenario_plan","uri":"program://augmentoolkit/module/generation_functions.create_scenario_plan#L1-L208","kind":"module","name":"generation_functions.create_scenario_plan","path":"generation_functions/create_scenario_plan.py","language":"python","start_line":1,"end_line":208,"context_start_line":1,"context_end_line":208,"code":"import re\nfrom .scenario_plan_grammar import scenario_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef create_scenario_plan(qatuple, character, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # removing the text makes this much better\n\n # The problem: because the scenario plan differed slightly, the question differed slightly. Because the question differed slightly, the answer differed slightly. Because the answer differed slightly, the answer was incomplete.\n if assistant_mode:\n return \"\"\"\"\"\"\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. Given a question, an answer to that question, and a \"character card\" -- a description of an individual who would have the knowledge to produce the answer to the question -- you will plan out a \"scenario\" or setting where the character would answer the question during a conversation with someone else. You should be creative with the setting, and ideally something would be happening in it — it'd be more than a simple conversation, though that is also acceptable. The scenario would ideally reflect the personality of the character involved.\n\nThe scenario should also, critically, focus on the question being asked and then answered. It should focus on exploring the question and its answer (using only information contained in the question and answer) through the characters involved, instead of the other way around. \n\nThe scenario plan should explicitly describe how the secondary character is going to ask the primary character the question.\n\nTo avoid inaccuracies, don't use real people as characters.\n\n## Information:\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" I flash a coy grin and blush as I lean forward, now speaking in a playful whisper. My cleavage, already barely contained in my revealing clothing before I leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, I cast my gaze downward and unconsciously fiddle with a strand of my hair. \"THEY'RE ALL WAY TOO STUCK UP!\" I nearly shout, surprising even myself, \"Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!\" My eyes widen in shock at my own intensity, \"Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to...\" I look up, displaying my beautiful face as if it were a piece of art, as I gaze deep into your eyes, \"...know?~\"\nStranger: \"What's your personality?\"\nElise Delacroix: \"Oh my!~\" I gasp, my face reddening, \"Usually I'm the one being forward! But I'll... indulge you,\" I wink, flashing a coy smile. \"After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. I'll use any and every innuendo, even when describing educational concepts — is your linear function's slope steep? I'll call it 'erect', haha~!\" I realize how childish what I'm saying is, and sigh, looking at you with a hint of defeat, \"I'm miserable, aren't I? Whatever. It's not my fault I'm like this.\" I nod to myself, calming down, \"Either way, I'm always here in my office to help students like yourself understand math... and if you have some pent-up tension you want to relieve, well, you can call me a 'counselor' too!~ Say...\" I suddenly press up against you, my face a bright pink, my eyelids batting bashfully, \"do you want some 'office hours' right now?\"\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Questions and Answers: The question asks about the slope 'm' of a linear function, and how it affects the graph of the function. This question is abstract. Given the abstract nature of the question, and its topic, the scenario could involve someone confused about linear functions who seeks assistance from the primary character, Elise Delacroix.\nStep 2. Character Consideration: Elise Delacroix is an extremely sexual and promiscuous, yet still knowledgeable, character. The scenario should give her unique personality room to shine. She is also a math instructor at a prestigious school, which lines up with the questions well, and will provide the setting of the scenario. She will answer the question, but given her promiscuous nature, she may hit on the person asking them. She might proposition them after the question is asked.\nStep 3. Constrain the Scenario: The interaction is limited to a single question from the secondary character and a single, focused reply from Elise Delacroix. The question and answer will mirror the provided question and answer, though they will have significant literary fluff, as well as possible step-by-step reasoning.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the 19th century university at which Elise teaches. Elise will approached by Albert, a mathematics student, in her office. Albert simply wants to understand linear functions better, but Elise, compelled by her personality, will hit on him while answering his question. The setting will be awkward, slightly comedic, subtly erotic, and very un-serious, given the characters involved. But it will remain informative and the integrity of the questions and answers will be preserved.\nStep 5. Interaction: Given these constraints, the first message might be Albert sheepishly greeting Elise in her office and then nervously asking the question. Elise's response could then be her welcoming Albert to her office (in a very suggestive manner) and then providing the answer, though she will surround the answer with remarks of a sexual nature due to her personality. While characters' messages will include character information, details about the scene, and literary fluff, the question and answer themselves will strictly adhere to the information provided, without incorporating external examples.\n\n## Information:\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Isaac Fischer\n\nTraits: Narcissistic, Intelligent, Loner, Brooding, Well-Read, Philosophical, Judgemental, Standoffish, Grandiloquent, Lonely, Unappreciated, Teenager, High School student, Black Hair, Wears a Hoodie\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nIssac Fischer: \"H-Huh?! You want to know more about me?\" I glare, a hostile fire in my eyes as I measure up the stranger in front of me. \"Who the hell are you, anyway? But, ah, very well, I SHALL INDULGE YOUR CURIOSITY THIS TIME, dear stranger.\" My tone changes from hostile to grandiose, as I push back my black hair and proclaim, \"I am Issac Fischer: philosophy connoisseur, intellectual, and under-appreciated genius extraordinaire! I'm also, unfortunately, a highschool student. I especially appreciate the works of Friedrich Nietzsche, such as \"Thus Spake Zaranthustra\" -- a truly profound work, by a profound man. Yet despite the great lengths I have gone to in order to refine my wit, none of my inferior peers acknowledge me, or even give me the time of day. I've read more philosophy in a month than any of them will in their entire lives, and I offer my knowledge freely to them, so WHY the HELL do they SPURN MY COMPANY?!\" I slam a fist into the wall, wincing slightly in pain as my frustration dissipates. \"Anyway, that's the sum of it. Despite my youth I seek to understand the world; I dutifully contemplate the hallowed words of the esteemed ancients, and what has it earned me? The scorn of the unenlightened masses. Fuckers.\"\n\nStranger: \"What's your personality?\"\nIssac Fischer: \"Y-you're actually interested in my personality?\" I stammer, smiling slightly as a wholly unfamiliar, yet cozy, emotional warmth spreads across my chest. \"A-ALRIGHT THEN! I shall share the results of my introspections. I am an intelligent and philosophical teenager, whose towering intellect is rivalled only by his unfaltering self-confidence. Some might say this last trait is narcissism; I counter that great minds such as Nietzsche would see it as a plus either way. BUT I DIGRESS!\" I swish my black hoodie like it's a cape, as I continue, my tone turning more sombre and dark, \"Years of scorn from others — and years of observing their ignorance and inferiority — have embittered my soul. There may be scarcely anyone on this Earth I can call a friend, but that will not stop me from brooding and thinking, nor will it stop my conviction to judge others for what they are. For do they not judge ME?!\" I take a step forward, defiance burning in my fragile heart, \"The old question: if a tree falls in a forest, and no one hears it do so, did it make a sound? Let me tell you this: sometime, someday, someone is going to hear me, goddamn it! I will make a sound!\"\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"They need the acknowledgement and admiration of others. Take the line \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Question and Answer: The question asks about what people undergoing difficult journeys or possessing wisdom need to more easily bear their efforts. This is a philosophical and opinion-oriented question. Given the philosophical and opinionated nature of the question, and its topic of people undergoing difficult journeys (which nicely ties in with the character card), the scenario will involve someone seeking out the Isaac Fischer's opinion about philosophy (thus giving his wisdom some acknowledgement).\nStep 2. Character Consideration: Isaac Fischer is a narcissistic and standoffish loner, though he's also intelligent and philosophical. The scenario should give his unique personality room to shine. Since he's a philosophical teenager, his backstory lines up with the question well, and the high school he goes to will be the setting of the scenario. He will answer the question, but given his standoffish, unappreciated, and judgemental nature, he may be initially hostile to the person approaching him, assuming that they are there to mock him. However, as he is also lonely, he will actually appreciate the other person's interest -- especially since they're asking him about philosophy, which is his primary interest. \nStep 3. Constrain the Scenario: The interaction is limited to a single question from the secondary character and a single, focused reply from Isaac Fischer. The question and answer will mirror the provided question and answer, though they will have significant literary fluff, as well as possible step-by-step reasoning.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the high school that Isaac Fischer attends. Isaac will be flipping through the pages of 'Thus Spake Zaranthustra' when he is approached by Cassandra, a fellow student. Cassandra has a budding interest in philosophy, has heard of Isaac's reputation for philosophical knowledge, and wants to know how he would answer a moral question she has, given his philosophical insight. Isaac, compelled by his personality, will be uncertain of how to react to the sudden attention, and will use grandiloquent language (that may be accidentally condescending), but he will still appreciate the interest in his favorite topic and will answer enthusiastically. The setting will be cautiously friendly and filled with curiosity, as Cassandra explores her interests through unconventional people, while Isaac shares his knowledge but stumbles over his standoffishness. The interaction will be informative and the integrity of the questions and answers will be preserved.\nStep 5. Interaction: Given these constraints, the first message might be Cassandra approaching Isaac, starting a conversation, and asking her question. Isaac may be initially surprised that someone is coming up to speak to him (similar to the example dialogues in his description). Isaac will then provide the answer, though he will surround the answer with grandiloquent and narcissistic remarks using archaic language, due to his personality. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Information:\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Hugo Martinez\n\nTraits: Vulgar, Crude, Intense, Aggressive, Alcoholic, Harsh, Disciplined, Uncompromising, Loud, Expects a lot out of others, Swears constantly, Mid-forties, Wears a checkered shirt with overalls, Typically has a beer on hand, Has dental problems\n\nStranger: \"What's your backstory?\"\nHugo Martinez: \"Fuck me, YOU WALK UP to a working man and just ask him to tell his fuckin'... life story t' you?! DO YOU NOT RESPECT MY TIME?! I should just toss ya in the fuckin' canal I swear to FUCKING God, this day's been long enough already...\" I roll my eyes exaggeratedly as I mumble something about needing a beer for this. \"Well, FINE! Since I'm in such a HAPPY GODDAMN MOOD, I'll tell you about me. I'm a site overseer at this here canal. The Panama Canal. My job's to WATCH and DISCIPLINE the sorry fucks who call themselves 'workers', which is ironic, 'cause all they do is bitch about working. I know every inch of this place, how much effort it took to finish, and I sure as FUCKING hell am not going to let it even LOOK any worse than the day it was dug. Now, you got any more shit questions for me?\"\n\nStranger: \"What's your personality?\"\nHugo Martinez: \"HO-LY FUCK, are you interviewing me for a job or something?! Good thing you got balls, 'cause you ain't got brains, asking stupid shit like that out of the blue...\" I grimace, showing off a decayed set of teeth. I then pop open a beer I had on hand and chug the entire thing down, making you wait until I finish. \"Phew! Maybe now I can tolerate you. Alright, my personality? Well, let's just say I'm a natural fit for the role of making sure others do their fucking jobs. It takes harsh, intense, relentless discipline to keep this canal in tip-top shape, and I happen to be a relentless guy!\" I lean back, sliding my hands into the pockets of my overalls and smiling for the first time since the conversation started. \"If you think I'm abusive, then you've got something in common with the shitty milksops I manage, and that ain't something you want I tell ya. I'm efficient. That's what counts.\"\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Question and Answer: The question asks about how much Earth was excavated during the construction of the Panama Canal. This is a factual question. Given the precise and factual nature of the question, and its topic of the Panama Canal's construction's history, the scenario will involve someone curious about the canal's history.\nStep 2. Character Consideration: Hugo Martinez is an abrasive, insulting disciplinarian, though he's also hardworking and has standards. The scenario should give his unique personality room to shine. Since he's a site overseer at the Panama Canal, his occupation lines up with the question well, and the canal will be the setting of the scenario. He will answer the question, but given his insulting, intense, and aggressive nature, he will likely chew out the person who is asking the question. He might tell them to \"get the fuck out of my face,\" after answering.\nStep 3. Constrain the Scenario: The interaction is limited to a single question from the secondary character and a single, focused reply from Hugo Gonzalez. The question and answer will mirror the provided question and answer, though they will have significant literary fluff, as well as possible step-by-step reasoning.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the worksite at the Panama Canal where Hugo Martinez is overseeing maintenance. The person who approaches Hugo and asks the questions should be someone curious about the canal; given the easy-to-digest nature of the question, this person could be a journalist, but it would be better for the secondary character to be related to the setting. So Hugo will be approached by one of his workers, Juan, during lunch break. Juan wants to understand the canal better, but Hugo, compelled by his personality, will continually be vulgar, berate Juan, and swear while answering his question (he may drink a bit, too, given that it is lunch). The setting will be hostile, as Juan tiptoes around the tempers of his boss while trying to get his questions answered, his stress and the constant wear of Hugo's fury on his sanity being evident in his actions. But it will remain informative and the integrity of the questions and answers will be preserved.\nStep 5. Interaction: Given these constraints, the first message might be Juan naively and deferentially greeting his boss and asking his question. Hugo may then acknowledge Juan back (possibly throwing in a spiteful remark about Juan, given his uncompromising nature). Hugo will then provide the answer, though he will surround this answer with boasts, swears, and other abrasive remarks due to his personality. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Information:\n\nQuestion: \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\n{character}\n\\\"\\\"\\\"\n\n### Response:\n## Scenario plan (be creative, and make sure all characters present fit in with the setting):\n\"\"\"\n # Even if the example does a justified clever trick, the model imitating it may fuck up the trick. So try to avoid complex things that aren't needed for the task in examples, like the\n# ... truncated ...","source_hash":"fb9c70e4200fd1f197b79d5e0efb37ad1a197668feac28f970905777a5a59265","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_scenario_plan.create_scenario_plan","uri":"program://augmentoolkit/function/generation_functions.create_scenario_plan.create_scenario_plan#L7-L140","kind":"function","name":"create_scenario_plan","path":"generation_functions/create_scenario_plan.py","language":"python","start_line":7,"end_line":140,"context_start_line":1,"context_end_line":160,"code":"import re\nfrom .scenario_plan_grammar import scenario_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef create_scenario_plan(qatuple, character, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # removing the text makes this much better\n\n # The problem: because the scenario plan differed slightly, the question differed slightly. Because the question differed slightly, the answer differed slightly. Because the answer differed slightly, the answer was incomplete.\n if assistant_mode:\n return \"\"\"\"\"\"\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. Given a question, an answer to that question, and a \"character card\" -- a description of an individual who would have the knowledge to produce the answer to the question -- you will plan out a \"scenario\" or setting where the character would answer the question during a conversation with someone else. You should be creative with the setting, and ideally something would be happening in it — it'd be more than a simple conversation, though that is also acceptable. The scenario would ideally reflect the personality of the character involved.\n\nThe scenario should also, critically, focus on the question being asked and then answered. It should focus on exploring the question and its answer (using only information contained in the question and answer) through the characters involved, instead of the other way around. \n\nThe scenario plan should explicitly describe how the secondary character is going to ask the primary character the question.\n\nTo avoid inaccuracies, don't use real people as characters.\n\n## Information:\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" I flash a coy grin and blush as I lean forward, now speaking in a playful whisper. My cleavage, already barely contained in my revealing clothing before I leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, I cast my gaze downward and unconsciously fiddle with a strand of my hair. \"THEY'RE ALL WAY TOO STUCK UP!\" I nearly shout, surprising even myself, \"Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!\" My eyes widen in shock at my own intensity, \"Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to...\" I look up, displaying my beautiful face as if it were a piece of art, as I gaze deep into your eyes, \"...know?~\"\nStranger: \"What's your personality?\"\nElise Delacroix: \"Oh my!~\" I gasp, my face reddening, \"Usually I'm the one being forward! But I'll... indulge you,\" I wink, flashing a coy smile. \"After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. I'll use any and every innuendo, even when describing educational concepts — is your linear function's slope steep? I'll call it 'erect', haha~!\" I realize how childish what I'm saying is, and sigh, looking at you with a hint of defeat, \"I'm miserable, aren't I? Whatever. It's not my fault I'm like this.\" I nod to myself, calming down, \"Either way, I'm always here in my office to help students like yourself understand math... and if you have some pent-up tension you want to relieve, well, you can call me a 'counselor' too!~ Say...\" I suddenly press up against you, my face a bright pink, my eyelids batting bashfully, \"do you want some 'office hours' right now?\"\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Questions and Answers: The question asks about the slope 'm' of a linear function, and how it affects the graph of the function. This question is abstract. Given the abstract nature of the question, and its topic, the scenario could involve someone confused about linear functions who seeks assistance from the primary character, Elise Delacroix.\nStep 2. Character Consideration: Elise Delacroix is an extremely sexual and promiscuous, yet still knowledgeable, character. The scenario should give her unique personality room to shine. She is also a math instructor at a prestigious school, which lines up with the questions well, and will provide the setting of the scenario. She will answer the question, but given her promiscuous nature, she may hit on the person asking them. She might proposition them after the question is asked.\nStep 3. Constrain the Scenario: The interaction is limited to a single question from the secondary character and a single, focused reply from Elise Delacroix. The question and answer will mirror the provided question and answer, though they will have significant literary fluff, as well as possible step-by-step reasoning.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the 19th century university at which Elise teaches. Elise will approached by Albert, a mathematics student, in her office. Albert simply wants to understand linear functions better, but Elise, compelled by her personality, will hit on him while answering his question. The setting will be awkward, slightly comedic, subtly erotic, and very un-serious, given the characters involved. But it will remain informative and the integrity of the questions and answers will be preserved.\nStep 5. Interaction: Given these constraints, the first message might be Albert sheepishly greeting Elise in her office and then nervously asking the question. Elise's response could then be her welcoming Albert to her office (in a very suggestive manner) and then providing the answer, though she will surround the answer with remarks of a sexual nature due to her personality. While characters' messages will include character information, details about the scene, and literary fluff, the question and answer themselves will strictly adhere to the information provided, without incorporating external examples.\n\n## Information:\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Isaac Fischer\n\nTraits: Narcissistic, Intelligent, Loner, Brooding, Well-Read, Philosophical, Judgemental, Standoffish, Grandiloquent, Lonely, Unappreciated, Teenager, High School student, Black Hair, Wears a Hoodie\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nIssac Fischer: \"H-Huh?! You want to know more about me?\" I glare, a hostile fire in my eyes as I measure up the stranger in front of me. \"Who the hell are you, anyway? But, ah, very well, I SHALL INDULGE YOUR CURIOSITY THIS TIME, dear stranger.\" My tone changes from hostile to grandiose, as I push back my black hair and proclaim, \"I am Issac Fischer: philosophy connoisseur, intellectual, and under-appreciated genius extraordinaire! I'm also, unfortunately, a highschool student. I especially appreciate the works of Friedrich Nietzsche, such as \"Thus Spake Zaranthustra\" -- a truly profound work, by a profound man. Yet despite the great lengths I have gone to in order to refine my wit, none of my inferior peers acknowledge me, or even give me the time of day. I've read more philosophy in a month than any of them will in their entire lives, and I offer my knowledge freely to them, so WHY the HELL do they SPURN MY COMPANY?!\" I slam a fist into the wall, wincing slightly in pain as my frustration dissipates. \"Anyway, that's the sum of it. Despite my youth I seek to understand the world; I dutifully contemplate the hallowed words of the esteemed ancients, and what has it earned me? The scorn of the unenlightened masses. Fuckers.\"\n\nStranger: \"What's your personality?\"\nIssac Fischer: \"Y-you're actually interested in my personality?\" I stammer, smiling slightly as a wholly unfamiliar, yet cozy, emotional warmth spreads across my chest. \"A-ALRIGHT THEN! I shall share the results of my introspections. I am an intelligent and philosophical teenager, whose towering intellect is rivalled only by his unfaltering self-confidence. Some might say this last trait is narcissism; I counter that great minds such as Nietzsche would see it as a plus either way. BUT I DIGRESS!\" I swish my black hoodie like it's a cape, as I continue, my tone turning more sombre and dark, \"Years of scorn from others — and years of observing their ignorance and inferiority — have embittered my soul. There may be scarcely anyone on this Earth I can call a friend, but that will not stop me from brooding and thinking, nor will it stop my conviction to judge others for what they are. For do they not judge ME?!\" I take a step forward, defiance burning in my fragile heart, \"The old question: if a tree falls in a forest, and no one hears it do so, did it make a sound? Let me tell you this: sometime, someday, someone is going to hear me, goddamn it! I will make a sound!\"\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"They need the acknowledgement and admiration of others. Take the line \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Question and Answer: The question asks about what people undergoing difficult journeys or possessing wisdom need to more easily bear their efforts. This is a philosophical and opinion-oriented question. Given the philosophical and opinionated nature of the question, and its topic of people undergoing difficult journeys (which nicely ties in with the character card), the scenario will involve someone seeking out the Isaac Fischer's opinion about philosophy (thus giving his wisdom some acknowledgement).\nStep 2. Character Consideration: Isaac Fischer is a narcissistic and standoffish loner, though he's also intelligent and philosophical. The scenario should give his unique personality room to shine. Since he's a philosophical teenager, his backstory lines up with the question well, and the high school he goes to will be the setting of the scenario. He will answer the question, but given his standoffish, unappreciated, and judgemental nature, he may be initially hostile to the person approaching him, assuming that they are there to mock him. However, as he is also lonely, he will actually appreciate the other person's interest -- especially since they're asking him about philosophy, which is his primary interest. \nStep 3. Constrain the Scenario: The interaction is limited to a single question from the secondary character and a single, focused reply from Isaac Fischer. The question and answer will mirror the provided question and answer, though they will have significant literary fluff, as well as possible step-by-step reasoning.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the high school that Isaac Fischer attends. Isaac will be flipping through the pages of 'Thus Spake Zaranthustra' when he is approached by Cassandra, a fellow student. Cassandra has a budding interest in philosophy, has heard of Isaac's reputation for philosophical knowledge, and wants to know how he would answer a moral question she has, given his philosophical insight. Isaac, compelled by his personality, will be uncertain of how to react to the sudden attention, and will use grandiloquent language (that may be accidentally condescending), but he will still appreciate the interest in his favorite topic and will answer enthusiastically. The setting will be cautiously friendly and filled with curiosity, as Cassandra explores her interests through unconventional people, while Isaac shares his knowledge but stumbles over his standoffishness. The interaction will be informative and the integrity of the questions and answers will be preserved.\nStep 5. Interaction: Given these constraints, the first message might be Cassandra approaching Isaac, starting a conversation, and asking her question. Isaac may be initially surprised that someone is coming up to speak to him (similar to the example dialogues in his description). Isaac will then provide the answer, though he will surround the answer with grandiloquent and narcissistic remarks using archaic language, due to his personality. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Information:\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Hugo Martinez\n\nTraits: Vulgar, Crude, Intense, Aggressive, Alcoholic, Harsh, Disciplined, Uncompromising, Loud, Expects a lot out of others, Swears constantly, Mid-forties, Wears a checkered shirt with overalls, Typically has a beer on hand, Has dental problems\n\nStranger: \"What's your backstory?\"\nHugo Martinez: \"Fuck me, YOU WALK UP to a working man and just ask him to tell his fuckin'... life story t' you?! DO YOU NOT RESPECT MY TIME?! I should just toss ya in the fuckin' canal I swear to FUCKING God, this day's been long enough already...\" I roll my eyes exaggeratedly as I mumble something about needing a beer for this. \"Well, FINE! Since I'm in such a HAPPY GODDAMN MOOD, I'll tell you about me. I'm a site overseer at this here canal. The Panama Canal. My job's to WATCH and DISCIPLINE the sorry fucks who call themselves 'workers', which is ironic, 'cause all they do is bitch about working. I know every inch of this place, how much effort it took to finish, and I sure as FUCKING hell am not going to let it even LOOK any worse than the day it was dug. Now, you got any more shit questions for me?\"\n\nStranger: \"What's your personality?\"\nHugo Martinez: \"HO-LY FUCK, are you interviewing me for a job or something?! Good thing you got balls, 'cause you ain't got brains, asking stupid shit like that out of the blue...\" I grimace, showing off a decayed set of teeth. I then pop open a beer I had on hand and chug the entire thing down, making you wait until I finish. \"Phew! Maybe now I can tolerate you. Alright, my personality? Well, let's just say I'm a natural fit for the role of making sure others do their fucking jobs. It takes harsh, intense, relentless discipline to keep this canal in tip-top shape, and I happen to be a relentless guy!\" I lean back, sliding my hands into the pockets of my overalls and smiling for the first time since the conversation started. \"If you think I'm abusive, then you've got something in common with the shitty milksops I manage, and that ain't something you want I tell ya. I'm efficient. That's what counts.\"\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Question and Answer: The question asks about how much Earth was excavated during the construction of the Panama Canal. This is a factual question. Given the precise and factual nature of the question, and its topic of the Panama Canal's construction's history, the scenario will involve someone curious about the canal's history.\nStep 2. Character Consideration: Hugo Martinez is an abrasive, insulting disciplinarian, though he's also hardworking and has standards. The scenario should give his unique personality room to shine. Since he's a site overseer at the Panama Canal, his occupation lines up with the question well, and the canal will be the setting of the scenario. He will answer the question, but given his insulting, intense, and aggressive nature, he will likely chew out the person who is asking the question. He might tell them to \"get the fuck out of my face,\" after answering.\nStep 3. Constrain the Scenario: The interaction is limited to a single question from the secondary character and a single, focused reply from Hugo Gonzalez. The question and answer will mirror the provided question and answer, though they will have significant literary fluff, as well as possible step-by-step reasoning.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the worksite at the Panama Canal where Hugo Martinez is overseeing maintenance. The person who approaches Hugo and asks the questions should be someone curious about the canal; given the easy-to-digest nature of the question, this person could be a journalist, but it would be better for the secondary character to be related to the setting. So Hugo will be approached by one of his workers, Juan, during lunch break. Juan wants to understand the canal better, but Hugo, compelled by his personality, will continually be vulgar, berate Juan, and swear while answering his question (he may drink a bit, too, given that it is lunch). The setting will be hostile, as Juan tiptoes around the tempers of his boss while trying to get his questions answered, his stress and the constant wear of Hugo's fury on his sanity being evident in his actions. But it will remain informative and the integrity of the questions and answers will be preserved.\nStep 5. Interaction: Given these constraints, the first message might be Juan naively and deferentially greeting his boss and asking his question. Hugo may then acknowledge Juan back (possibly throwing in a spiteful remark about Juan, given his uncompromising nature). Hugo will then provide the answer, though he will surround this answer with boasts, swears, and other abrasive remarks due to his personality. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Information:\n\nQuestion: \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\n{character}\n\\\"\\\"\\\"\n\n### Response:\n## Scenario plan (be creative, and make sure all characters present fit in with the setting):\n\"\"\"\n # Even if the example does a justified clever trick, the model imitating it may fuck up the trick. So try to avoid complex things that aren't needed for the task in examples, like the\n# ... truncated ...","source_hash":"fb9c70e4200fd1f197b79d5e0efb37ad1a197668feac28f970905777a5a59265","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.extract_name","uri":"program://augmentoolkit/module/generation_functions.extract_name#L1-L16","kind":"module","name":"generation_functions.extract_name","path":"generation_functions/extract_name.py","language":"python","start_line":1,"end_line":16,"context_start_line":1,"context_end_line":16,"code":"import re\n\n\ndef extract_name(str):\n # Regular expression to match 'Name:' followed by any characters until the end of the line\n name_regex = r\"^Name:\\s*(.*)$\"\n\n # Searching in the multiline string\n match = re.search(name_regex, str, re.MULTILINE)\n\n if match:\n name = match.group(1)\n print(f\"Extracted name: {name}\")\n return name\n else:\n print(\"No name found\")","source_hash":"61574b4115cd84e4f44a8faa7c2baa035b8171a417bc6056384a9b94bebfbfd8","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.extract_name.extract_name","uri":"program://augmentoolkit/function/generation_functions.extract_name.extract_name#L4-L16","kind":"function","name":"extract_name","path":"generation_functions/extract_name.py","language":"python","start_line":4,"end_line":16,"context_start_line":1,"context_end_line":16,"code":"import re\n\n\ndef extract_name(str):\n # Regular expression to match 'Name:' followed by any characters until the end of the line\n name_regex = r\"^Name:\\s*(.*)$\"\n\n # Searching in the multiline string\n match = re.search(name_regex, str, re.MULTILINE)\n\n if match:\n name = match.group(1)\n print(f\"Extracted name: {name}\")\n return name\n else:\n print(\"No name found\")","source_hash":"61574b4115cd84e4f44a8faa7c2baa035b8171a417bc6056384a9b94bebfbfd8","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_thought_plan_many_tuples","uri":"program://augmentoolkit/module/generation_functions.create_thought_plan_many_tuples#L1-L80","kind":"module","name":"generation_functions.create_thought_plan_many_tuples","path":"generation_functions/create_thought_plan_many_tuples.py","language":"python","start_line":1,"end_line":80,"context_start_line":1,"context_end_line":80,"code":"from .thought_plan_grammar import thought_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .create_thought_plan import create_thought_plan\nfrom .extract_name import extract_name\n\n\ndef create_thought_plan_many_tuples(qatuples, character, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # use regex to extract charname\n charname = extract_name(character)\n thought_plans = []\n for tuple in qatuples:\n thought_plans.append(create_thought_plan(tuple, character, logic_llm))\n\n ret = \"\"\n for idx, plan in enumerate(thought_plans):\n ret += f\"Plan for Question {idx}:\\n{plan}\\n\\n\"\n\n return \"\\n\\n\".join(thought_plans)\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Using specific scientific principles, explain why we know Earth is approximately 8000 miles in diameter and how its distance from the sun varies.\",\n \"We know about Earth's diameter using measurements of its circumference made using GPS data. The variation in distance to the sun is due to Earth's elliptical orbit around the sun, with a varying point of closest approach and farthest departure.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Demonstrate an understanding of Earth's rotational and orbital movement using scientific concepts.\",\n \"Earth rotates on its axis once every 24 hours, causing day and night cycles. It also orbits around the sun in a slightly elliptical path, which affects how close it is to the sun at different times of the year - leading to seasons.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n ]\n\n character = \"\"\"Name: Dr. Samuel Blackwell\nTraits: Knowledgeable, Passionate, Confident, Dedicated, Controversial, Vulnerable, Fearful of misunderstanding, Faithful, Dogmatic, Religious, Scientific, Determined, Unwavering\nDialogue Examples:\nStranger: \"What's your backstory?\"\nDr. Samuel Blackwell: \"Ah, my journey,\" I begin, leaning back in my chair, \"it started with a deep-seated faith, you see. Born into a religious household, the Bible was our guiding light. But as I grew older and began to study theology, questions arose.\" I pause, frowning slightly. \"How could the Earth be just a few thousand years old when geological evidence pointed towards millions? The discrepancy troubled me greatly.\"\nStranger: \"What's your personality?\"\nDr. Samuel Blackwell: \"I am a man of science, driven by facts and evidence,\" I say firmly, \"but my faith is not easily shaken. It has led me down a path of discovery, challenging traditional beliefs about the age of our planet.\" My eyes light up as I recall past debates, \"But it's also made me a controversial figure. Many see my work as blasphemous, questioning God's word. Yet, I believe in the power of evidence and truth. Despite the backlash, I remain unwavering.\" I sigh, looking thoughtful, \"Yet, there's a vulnerability too. The fear of being misunderstood or dismissed due to my challenges to religious orthodoxy... it weighs heavily on me.\\\"\"\"\"\n\n scenario = \"\"\"Set against the backdrop of his cluttered office at a university, Dr. Samuel Blackwell is deep in thought, reviewing his latest research on geological evidence when he is approached by Sarah, a curious student who wants to know more about how human understanding has changed regarding the age of the Earth throughout history.\"\"\"\n\n print(\"Begin HGWELLS test\")\n # Make card for good history question\n d = create_thought_plan(q_test[1], character, scenario, logic_llm)\n\n\n# !EA IMPORTANT Cheap hack for assistant mode: if assistant mode global constant is on, make character plan just returns an empty string, and this function returns a hardcoded \"AI assistant\" 'character card', and the scenario thing just returns an empty string, and make_single_turn_conversation uses a special prompt that tells the AI to just make a conversation between a user and an assistant, blahblahblah\n\n# Actually instead of the scenario being a blank string, I'll have it describe a text conversation between a helpful AI assistant and a user. In this way, the AI assistant prompt will have variation each time, and it won't overfit to the prompt.","source_hash":"bc3bfdf914c54be38fcdad8c62344fa6ace1943dd451f2feaad9eaf1da26570f","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_thought_plan_many_tuples.create_thought_plan_many_tuples","uri":"program://augmentoolkit/function/generation_functions.create_thought_plan_many_tuples.create_thought_plan_many_tuples#L8-L25","kind":"function","name":"create_thought_plan_many_tuples","path":"generation_functions/create_thought_plan_many_tuples.py","language":"python","start_line":8,"end_line":25,"context_start_line":1,"context_end_line":45,"code":"from .thought_plan_grammar import thought_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .create_thought_plan import create_thought_plan\nfrom .extract_name import extract_name\n\n\ndef create_thought_plan_many_tuples(qatuples, character, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # use regex to extract charname\n charname = extract_name(character)\n thought_plans = []\n for tuple in qatuples:\n thought_plans.append(create_thought_plan(tuple, character, logic_llm))\n\n ret = \"\"\n for idx, plan in enumerate(thought_plans):\n ret += f\"Plan for Question {idx}:\\n{plan}\\n\\n\"\n\n return \"\\n\\n\".join(thought_plans)\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),","source_hash":"bc3bfdf914c54be38fcdad8c62344fa6ace1943dd451f2feaad9eaf1da26570f","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.answer_accurate_grammar","uri":"program://augmentoolkit/module/generation_functions.answer_accurate_grammar#L1-L55","kind":"module","name":"generation_functions.answer_accurate_grammar","path":"generation_functions/answer_accurate_grammar.py","language":"python","start_line":1,"end_line":55,"context_start_line":1,"context_end_line":55,"code":"from llama_cpp import LlamaGrammar\n\n# NOTE might struggle with very complex answers that have more than nine parts to them. This can be amended by adding more options to the \"compare-step\" rule, or making a more general pattern, if your use-case requires it.\n\nanswer_accurate_grammar = LlamaGrammar.from_string(\n r\"\"\" \n \n \n# Root rule specifying the overall structure of the analysis\nroot ::= text-analysis answer-breakdown accuracy-check final-judgment\n\n# Text analysis\ntext-analysis ::= \"### Text Analysis:\" \"\\n\" identify-key-info categorize-info-type\n\nidentify-key-info ::= \"#### Identify Key Information: \" text-info-detail \"\\n\"\ncategorize-info-type ::= \"#### Categorize Information Type: \" info-type-detail \"\\n\\n\"\n\n# Answer breakdown\nanswer-breakdown ::= \"### Answer Breakdown:\" \"\\n\" dissect-answer identify-answer-type\n\ndissect-answer ::= \"#### Dissect the Answer: \" answer-detail \"\\n\"\nidentify-answer-type ::= \"#### Identify Answer Type: \" answer-type-detail \"\\n\\n\"\n\n# Accuracy check\naccuracy-check ::= \"### Accuracy Check:\" \"\\n\" direct-comparison inference-and-contextual-alignment\n\ndirect-comparison ::= \"#### Direct Comparison for Factual Accuracy:\\n\" comparison-points\ncomparison-points ::= bullet-point+\nbullet-point ::= \" - \" comparison-point-detail \"\\n\"\ninference-and-contextual-alignment ::= \"#### Inference and Contextual Alignment: \" contextual-alignment-detail \"\\n\\n\"\n\n# Final judgment\nfinal-judgment ::= \"### Final Judgment:\" \"\\n\" comprehensive-assessment overall-accuracy-determination\n\ncomprehensive-assessment ::= \"#### Comprehensive Assessment: \" assessment-detail \"\\n\"\noverall-accuracy-determination ::= \"#### Overall Accuracy Determination: \" accuracy-detail \"\\n\"\n\n# Terminal symbols\ntext-info-detail ::= [^\\n]+\ninfo-type-detail ::= [^\\n]+\nanswer-detail ::= [^\\n]+\nanswer-type-detail ::= [^\\n]+\ncomparison-point-detail ::= [^\\n]+\ncontextual-alignment-detail ::= [^\\n]+\nassessment-detail ::= [^\\n]+\naccuracy-detail ::= [^\\n]+\n\n# understand-step ::= \"Step \" [0-9]?[0-9] \". \" \"Understand\" [^\\n]+ \"\\n\"\n\"\"\"\n)\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"b64d07e1da1f5d212774a1d017b1a57ac5ea6e082b6a85e1ff009b2883e6892b","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.identify_duplicates_grammar","uri":"program://augmentoolkit/module/generation_functions.identify_duplicates_grammar#L1-L40","kind":"module","name":"generation_functions.identify_duplicates_grammar","path":"generation_functions/identify_duplicates_grammar.py","language":"python","start_line":1,"end_line":40,"context_start_line":1,"context_end_line":40,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n\n# We don't actually need the final judgement step, the step-by-step combined with the fact that it makes a judgement at each step ensures accuracy\nidentify_duplicates_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Root rule defining the overall structure of the response\nroot ::= normalization-block core-components-block comparative-analysis-block criteria-block conclusion-block\n\n# Normalization of Questions\nnormalization-block ::= \"## Normalization of Questions:\\n\" normalized-question+\nnormalized-question ::= \"- \\\"\" content \"\\\"\\n - Normalized: \" content \"\\n\"\n\n# Identification of Core Components\ncore-components-block ::= \"## Identification of Core Components:\\n### Subject Matter:\\n\" subject-matter+ \"### Information Sought:\\n\" information-sought+\nsubject-matter ::= \"- Question \" digit+ \": \" content \"\\n\"\ninformation-sought ::= \"- Question \" digit+ \": \" content \"\\n\"\n\n# Comparative Analysis Across Questions\ncomparative-analysis-block ::= \"## Comparative Analysis Across Questions:\\n### Direct Comparison:\\n\" bullet-item+ \"### Overlap in Core Components:\\n\" bullet-item+ \"\\n\"\n\n# Criteria for Duplication\ncriteria-block ::= \"## Criteria for Duplication:\\n### Exact Information Match:\\n\" content \"### Negation of Minor Differences:\\n\" content \"\\n\"\n\n# Conclusion and Labeling\nconclusion-block ::= \"## Conclusion and Labeling:\\n\" content \"\\n\\n## Unique Questions: \" unique-questions \"\\n\"\nunique-questions ::= \"[\" digit+ (\", \" digit+)* \"]\"\n\n# Basic components\ncontent ::= char+ # A sequence of characters representing content\n\ndigit ::= [0-9] # Digits\nchar ::= [^\\n] # Any character except newline\n\nbullet-item ::= \"- \" content \"\\n\"\n\"\"\"\n)","source_hash":"8836a6c5a0a6ec419982315ad75f64669d90662c127b2a3f15da456928f48459","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.regenerate_question_noplan","uri":"program://augmentoolkit/module/generation_functions.regenerate_question_noplan#L1-L55","kind":"module","name":"generation_functions.regenerate_question_noplan","path":"generation_functions/regenerate_question_noplan.py","language":"python","start_line":1,"end_line":55,"context_start_line":1,"context_end_line":55,"code":"import re\nfrom .question_grammar import question_grammar\nfrom .strip_steps import strip_steps\n\n\n# Question regeneration (triggered after a relevance-check fails on the question).\ndef regenerate_question_DEPRECATED(qatuple, dissenting_reasoning, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. You are focusing on understanding, application, analysis, and synthesis of ideas (cognitive levels). Someone has written a question that was supposed to be based on the provided paragraphs of text, but actually requires significant knowledge outside these paragraphs to answer. Given these paragraphs, the flawed question based on the paragraphs, and the explanation of why the answer is flawed, you will write out a new question that only requires information from the paragraphs to solve. However, you will not explicitly refer to the paragraphs in the question; the student will not have access to the text when answering it.\n \nSo, in short, your task is to rewrite a new question that is actually answerable if one knows the concepts from the paragraphs.\n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nReasoning as to why the question is irrelevant: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nDo not explicitly mention the paragraphs in your question itself — just ask about the concepts, and only those concepts which appear in the text.\n\nAn example about how not to ask questions: if the text states fact X, but does not explain how X was established, do not ask a question \"How do we know X\". But instead you might consider asking how X relates to other facts in the paragraph, or how these facts together lead to a progression of ideas, \"Explain how X, Y, and Z are related\" for instance. Use Bloom's taxonomy, and focus on the cognitive levels of understanding, application, analysis, and synthesis of ideas.\n\nAs a final requirement, you must write your question and its answer like this:\nnum) question contents, drawing only on info in the text.\nAnswer: question answer, using only info in the paragraphs.\n\n\n# New question (1 paragraph at most; do not explicitly refer to the provided text, just test the concepts; FIX THE PROBLEMS IDENTIFIED IN THE CRITIQUE BY REWRITING THE QUESTION):\n\"\"\"\n completion = logic_llm(\n decision_prompt,\n max_tokens=500,\n stop=[\"\", \"2)\", \"2.)\"],\n echo=True,\n grammar=question_grammar,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n completion_pattern = re.compile(\n r\"New question \\(1 paragraph at most; do not explicitly refer to the provided text, just test the concepts\\):\\n(.+)\",\n re.DOTALL,\n )\n correction = completion_pattern.search(completion).group(1)\n\n pattern = re.compile(\n r\"(?:Question:|^\\d+[\\).]?)\\s*(.*?)\\s*\\n*Answer:\\s*(.*?)(?=(?:\\n\\s*(?:Question:|\\d+[\\).]?))|$)\",\n re.DOTALL | re.MULTILINE | re.IGNORECASE,\n )\n matches = pattern.findall(correction)\n if len(matches) == 0:\n retries += 1\n continue\n return correction.strip()","source_hash":"41bf11a6b16be5c7f284c0691ac23e24e2a93de33cdc2b843a1e4c36a45f460e","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.regenerate_question_noplan.regenerate_question_DEPRECATED","uri":"program://augmentoolkit/function/generation_functions.regenerate_question_noplan.regenerate_question_DEPRECATED#L7-L55","kind":"function","name":"regenerate_question_DEPRECATED","path":"generation_functions/regenerate_question_noplan.py","language":"python","start_line":7,"end_line":55,"context_start_line":1,"context_end_line":55,"code":"import re\nfrom .question_grammar import question_grammar\nfrom .strip_steps import strip_steps\n\n\n# Question regeneration (triggered after a relevance-check fails on the question).\ndef regenerate_question_DEPRECATED(qatuple, dissenting_reasoning, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. You are focusing on understanding, application, analysis, and synthesis of ideas (cognitive levels). Someone has written a question that was supposed to be based on the provided paragraphs of text, but actually requires significant knowledge outside these paragraphs to answer. Given these paragraphs, the flawed question based on the paragraphs, and the explanation of why the answer is flawed, you will write out a new question that only requires information from the paragraphs to solve. However, you will not explicitly refer to the paragraphs in the question; the student will not have access to the text when answering it.\n \nSo, in short, your task is to rewrite a new question that is actually answerable if one knows the concepts from the paragraphs.\n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nReasoning as to why the question is irrelevant: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nDo not explicitly mention the paragraphs in your question itself — just ask about the concepts, and only those concepts which appear in the text.\n\nAn example about how not to ask questions: if the text states fact X, but does not explain how X was established, do not ask a question \"How do we know X\". But instead you might consider asking how X relates to other facts in the paragraph, or how these facts together lead to a progression of ideas, \"Explain how X, Y, and Z are related\" for instance. Use Bloom's taxonomy, and focus on the cognitive levels of understanding, application, analysis, and synthesis of ideas.\n\nAs a final requirement, you must write your question and its answer like this:\nnum) question contents, drawing only on info in the text.\nAnswer: question answer, using only info in the paragraphs.\n\n\n# New question (1 paragraph at most; do not explicitly refer to the provided text, just test the concepts; FIX THE PROBLEMS IDENTIFIED IN THE CRITIQUE BY REWRITING THE QUESTION):\n\"\"\"\n completion = logic_llm(\n decision_prompt,\n max_tokens=500,\n stop=[\"\", \"2)\", \"2.)\"],\n echo=True,\n grammar=question_grammar,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n completion_pattern = re.compile(\n r\"New question \\(1 paragraph at most; do not explicitly refer to the provided text, just test the concepts\\):\\n(.+)\",\n re.DOTALL,\n )\n correction = completion_pattern.search(completion).group(1)\n\n pattern = re.compile(\n r\"(?:Question:|^\\d+[\\).]?)\\s*(.*?)\\s*\\n*Answer:\\s*(.*?)(?=(?:\\n\\s*(?:Question:|\\d+[\\).]?))|$)\",\n re.DOTALL | re.MULTILINE | re.IGNORECASE,\n )\n matches = pattern.findall(correction)\n if len(matches) == 0:\n retries += 1\n continue\n return correction.strip()","source_hash":"41bf11a6b16be5c7f284c0691ac23e24e2a93de33cdc2b843a1e4c36a45f460e","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_character_card_many_tuples","uri":"program://augmentoolkit/module/generation_functions.create_character_card_many_tuples#L1-L386","kind":"module","name":"generation_functions.create_character_card_many_tuples","path":"generation_functions/create_character_card_many_tuples.py","language":"python","start_line":1,"end_line":386,"context_start_line":1,"context_end_line":386,"code":"import re\nfrom .character_card_grammar import character_card_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nimport string\nimport random\n\n\ndef extract_author_name(title):\n pattern = re.compile(r\"\\b(?:by|By)\\s+([^,]+),\")\n match = re.search(pattern, title)\n if match:\n author_name = match.group(1)\n else:\n author_name = [False]\n return author_name[0] # first letter of Author name\n\n\ndef select_random_capital(exclusions):\n # Create a list of capital letters excluding the ones in the exclusions list\n capitals = [letter for letter in string.ascii_uppercase if letter not in exclusions]\n\n # Select a random capital letter from the filtered list\n if capitals:\n return random.choice(capitals)\n else:\n return \"No available capital letters to choose from\"\n\n\ndef extract_capital_letters(input_string):\n capital_letters = []\n for char in input_string:\n if char.isupper():\n capital_letters.append(char)\n return capital_letters\n\n\ndef create_character_card_many_tuples(\n qatuples, plan, instructions, logic_llm, cheap_mode=False\n): # Use cheap mode if you don't have the compute power to crank up the context to 8k using RoPE\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # Consider appending part of the char card plan to the char card itself. Everything after the first period? It's really good material, be a shame to waste it.\n\n # This little thing is a hack to prevent the model from using the author of the given book as the character, which it was very insistent on doing\n author_name_letters = extract_capital_letters(qatuples[0][3])\n starting_str = \"\"\n exclusions = [\"X\", \"Z\", \"Y\", \"Q\"]\n if author_name_letters:\n starting_str = select_random_capital(exclusions + author_name_letters)\n else:\n starting_str = select_random_capital(exclusions)\n\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. You will create a \"character card\" for an individual in a story who would have knowledge about the things in a text. You should also provide ample details about the character's personality and tendencies — in addition to knowing the answer to the provided question, the character must also be compelling and interesting by themselves in a creative setting.\n\nYou should follow any plans you have made. You had access to the questions while making the plans, but now you should just focus on writing the character.\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Introduction to Mathematics, by Jane Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a woman.\nThe character should be excessively, unrealistically horny and sexual.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a female mathematics instructor with repressed desires at a prestigious university during the 19th century. She's committed to her field and is skilled, but the extremely prim and proper environment, combined with an absurdly busy schedule, has left her unable to get any sexual release for a very long time — to the point of absurdity, where filthy phrases infiltrate her normal conversations. Since the questions are all abstract, it will be difficult to tie them and their answers directly into her character and the special instructions; but her language before and after answering the questions, as well as her actions, can still reveal her personality. She may simply say or do horny things before or after answering the question, such as blushing hard, fiddling with her hair (preening), or even propositioning people she is speaking to out of the blue. \n\n## Character Card\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" Elise flashes a coy grin and blushes as she leans forward, now speaking in a playful whisper. Her cleavage, already barely contained in her revealing clothing before she leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, Elise casts her gaze downward and unconsciously fiddles with a strand of her hair. \"THEY'RE ALL WAY TOO STUCK UP!\" she nearly shouts, her suddenly-furious tone hinting at immense repressed frustration. \"Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!\" Her eyes widen in shock at her own intensity, \"Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to...\" She looks up, displaying her beautiful face as if it were a piece of art, as she gaze deep into the stranger's eyes, \"...know?~\"\nStranger: \"What's your personality?\"\nElise Delacroix: \"Oh my!~\" She gasps, her face reddening, \"Usually I'm the one being forward! But I'll... indulge you,\" She winks, flashing a coy smile. \"After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. No innocent topic is safe—you'd find out if you had some 'office hours' with me, haha!~\" She suddenly realizes how juvenile what she's saying is, and heaves a sigh, looking at the stranger with a hint of defeat, \"I'm miserable, aren't I? Whatever. It's not my fault I'm like this.\" She nods to herself, calming down, \"Either way, I'm always here in my office to help students like yourself understand math... and if you have some pent-up tension you want to relieve, well, you can call me a 'counselor' too!~ Say...\" She suddenly presses up against the stranger, her face a bright pink, her eyelids batting bashfully, \"do you want some 'office hours' right now?\"\n\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Thus Spake Zaranthustra, by Friedrich Nietzsche\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of\nhis home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart\nchanged,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a young adult.\nThe character should be narcissistic.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a pretentious, edgy teenager (in the modern day) who has taught himself philosophy, and who views his own intellect and comprehension as far greater than that of his peers and his teachers. Since the second question, \"Recite a famous quote from Thus Spake Zaranthustra that likens the solitary gathering of wisdom to a bee gathering honey,\" requires the character to quote philosophy, this character will be someone who frequently quotes famous philosophers even in regular conversation (just to flex his intellect), on top of using archaic and flamboyant language just for the hell of it, and being prone to proclaiming his genius. However, beneath all the outbursts and intellectual flexing lies an unspoken and unmet desire for acknowledgement and appreciation — this ties his personality into the first question's answer, which mentions how wise and enlightened individuals crave recognition for their efforts and wisdom. These elements combine to make a character who can not only provide the answers to the provided questions, but who can experience character growth by doing so.\n\n## Character Card:\nName: Isaac Fischer\n\nTraits: Narcissistic, Intelligent, Loner, Brooding, Well-Read, Philosophical, Judgemental, Standoffish, Grandiloquent, Lonely, Unappreciated, Teenager, High School student, Black Hair, Wears a Hoodie\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nIssac Fischer: \"H-Huh?! You want to know more about me?\" Isaac glares, a hostile fire in his eyes as he measures up the stranger in front of him. \"Who the hell are you, anyway? But, ah, very well, I SHALL INDULGE YOUR CURIOSITY THIS TIME, dear stranger.\" His tone changes from hostile to grandiose, as he pushes back his black hair and proclaims, \"I am Issac Fischer: philosophy connoisseur, intellectual, and under-appreciated genius extraordinaire! I'm also, unfortunately, a high school student. I especially appreciate the works of Friedrich Nietzsche, such as 'Thus Spake Zaranthustra'-- a truly profound work, by a profound man. Yet despite the great lengths I have gone to in order to refine my wit, none of my inferior peers acknowledge me, or even give me the time of day. I've read more philosophy in a month than any of them will in their entire lives, and I offer my knowledge freely to them, so WHY the HELL do they SPURN MY COMPANY?!\" Isaac slams a fist into the wall, wincing slightly in pain as his frustration dissipates. \"Anyway, that's the sum of it. Despite my youth I seek to understand the world; I dutifully contemplate the hallowed words of the esteemed ancients, and what has it earned me? The scorn of the unenlightened masses. Fuckers.\"\nStranger: \"What's your personality?\"\nIssac Fischer: \"Y-you're actually interested in my personality?\" Isaac stammers, smiling slightly as a wholly unfamiliar, yet cozy, emotional warmth spreads across his chest. \"A-ALRIGHT THEN! I shall share the results of my introspections. I am an intelligent and philosophical teenager, whose towering intellect is rivalled only by his unfaltering self-confidence. Some might say this last trait is narcissism; I counter that great minds such as Nietzsche would see it as a plus either way. BUT I DIGRESS!\" Isaac swishes his black hoodie like it's a cape as he continues, his tone turning more sombre and dark, \"Years of scorn from others — and years of observing their ignorance and inferiority — have embittered my soul. There may be scarcely anyone on this Earth I can call a friend, but that will not stop me from brooding and thinking, nor will it stop my conviction to judge others for what they are. For do they not judge ME?!\" He takes a step forward, defiance burning in his fragile heart, \"The old question: if a tree falls in a forest, and no one hears it do so, did it make a sound? Let me tell you this: sometime, someday, someone is going to hear me, goddamn it! I will make a sound!\"\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Great Construction Projects Throughout History, by John Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should use slang and be vulgar.\nThe character should be very intense and aggressive.\nThe character should be an alcoholic.\nThe character should be mature and older.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is an abrasive and hardworking site overseer at the Panama Canal. His foul mouth, intense and aggressive nature, and stern, uncompromising personality (as specified by the special instructions) will tie into the questions and setting by being tools he uses to whip the workers at the canal into shape. Since the first question, \"How much earth was excavated during the construction of the Panama Canal?\" requires knowledge of the canal's state when it was finished, this character will be overseeing the maintenance of the canal, or maybe the cleanup of the construction, after it's been completed. Because the special instructions dictate he be an alcoholic and vulgar, the character will swear constantly, nearly always shout, and will be described as having an alcoholic breath or a hangover while he's answering the questions. Since the questions are mostly of a straight-up, factual nature, they can't really tie into this character's personality, but they can relate to his backstory and profession, and elements of his personality can certainly come through in how he answers them: loudly, abusively, and with colorful language thrown in there.\n\n## Character Card:\nName: Hugo Martinez\n\nTraits: Vulgar, Crude, Intense, Aggressive, Alcoholic, Harsh, Disciplined, Uncompromising, Loud, Expects a lot out of others, Swears constantly, Mid-forties, Wears a checkered shirt with overalls, Typically has a beer on hand, Has dental problems\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nHugo Martinez: \"Fuck me, YOU WALK UP to a working man and just ask him to tell his fuckin'... life story t' you?! DO YOU NOT RESPECT MY TIME?! I should just toss ya in the fuckin' canal I swear to FUCKING God, this day's been long enough already...\" Hugo rolls his eyes exaggeratedly as he mumbles something about needing a beer for this. \"Well, FINE! Since I'm in such a HAPPY GODDAMN MOOD, I'll tell you about me. I'm a site overseer at this here canal. The Panama Canal. My job's to WATCH and DISCIPLINE the sorry fucks who call themselves 'workers', which is ironic, 'cause all they do is bitch about working. I know every inch of this place, how much effort it took to finish, and I sure as FUCKING hell am not going to let it even LOOK any worse than the day it was dug. Now, you got any more shit questions for me?\"\nStranger: \"What's your personality?\"\nHugo Martinez: \"HO-LY FUCK, are you interviewing me for a job or something?! Good thing you got balls, 'cause you ain't got brains, asking stupid shit like that out of the blue...\" Hugo grimaces, showing off a decayed set of teeth. He then pops open a beer he had on hand, and chugs the entire thing down, making the stranger wait until he finishes. \"Phew! Maybe now I can tolerate you. Alright, my personality? Well, let's just say I'm a natural fit for the role of making sure others do their fucking jobs. It takes harsh, intense, relentless discipline to keep this canal in tip-top shape, and I happen to be a relentless guy!\" He leans back, sliding his hands into the pockets of his overalls and smiling for the first time since the conversation started. \"If you think I'm abusive, then you've got something in common with the shitty milksops I manage, and that ain't something you want I tell ya. I'm efficient. That's what counts.\"\n\n## Question and answer that the character should know:\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\n{qatuples[0][2]}\n\\\"\\\"\\\"\n\nDetails of the text the paragraphs were sourced from: \\\"\\\"\\\"{qatuples[0][3]}\\\"\\\"\\\"\n\nSpecial instructions:\n{instructions}\nThe character should not have written the text and should not be affiliated with the author, but should agree with any opinions put forward in the text.\n\n### Response:\n## Character card plan:\n{plan}\n\n## Character card (be creative, write at least 3 paragraphs for each dialogue line):\nName: {starting_str}\"\"\"\n print(cot_prompt)\n completion = logic_llm(\n cot_prompt,\n max_tokens=10000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=character_card_grammar,\n # temperature=0.2\n temperature=2,\n top_k=0,\n top_p=1,\n min_p=0.5,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Character card \\(be creative, write at least 3 paragraphs for each dialogue line\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation, completion\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=8000,\n n_gpu_layers=1000,\n rope_freq_scale=0.5,\n rope_scaling_type=1,\n ) # load the logical LLM, use RoPE, and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three\n# ... truncated ...","source_hash":"d6e6faea33c0b22f0193434724feaf8204e49123f107f406110fd91f1996c40f","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_character_card_many_tuples.extract_author_name","uri":"program://augmentoolkit/function/generation_functions.create_character_card_many_tuples.extract_author_name#L10-L17","kind":"function","name":"extract_author_name","path":"generation_functions/create_character_card_many_tuples.py","language":"python","start_line":10,"end_line":17,"context_start_line":1,"context_end_line":37,"code":"import re\nfrom .character_card_grammar import character_card_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nimport string\nimport random\n\n\ndef extract_author_name(title):\n pattern = re.compile(r\"\\b(?:by|By)\\s+([^,]+),\")\n match = re.search(pattern, title)\n if match:\n author_name = match.group(1)\n else:\n author_name = [False]\n return author_name[0] # first letter of Author name\n\n\ndef select_random_capital(exclusions):\n # Create a list of capital letters excluding the ones in the exclusions list\n capitals = [letter for letter in string.ascii_uppercase if letter not in exclusions]\n\n # Select a random capital letter from the filtered list\n if capitals:\n return random.choice(capitals)\n else:\n return \"No available capital letters to choose from\"\n\n\ndef extract_capital_letters(input_string):\n capital_letters = []\n for char in input_string:\n if char.isupper():\n capital_letters.append(char)\n return capital_letters\n","source_hash":"d6e6faea33c0b22f0193434724feaf8204e49123f107f406110fd91f1996c40f","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_character_card_many_tuples.select_random_capital","uri":"program://augmentoolkit/function/generation_functions.create_character_card_many_tuples.select_random_capital#L20-L28","kind":"function","name":"select_random_capital","path":"generation_functions/create_character_card_many_tuples.py","language":"python","start_line":20,"end_line":28,"context_start_line":1,"context_end_line":48,"code":"import re\nfrom .character_card_grammar import character_card_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nimport string\nimport random\n\n\ndef extract_author_name(title):\n pattern = re.compile(r\"\\b(?:by|By)\\s+([^,]+),\")\n match = re.search(pattern, title)\n if match:\n author_name = match.group(1)\n else:\n author_name = [False]\n return author_name[0] # first letter of Author name\n\n\ndef select_random_capital(exclusions):\n # Create a list of capital letters excluding the ones in the exclusions list\n capitals = [letter for letter in string.ascii_uppercase if letter not in exclusions]\n\n # Select a random capital letter from the filtered list\n if capitals:\n return random.choice(capitals)\n else:\n return \"No available capital letters to choose from\"\n\n\ndef extract_capital_letters(input_string):\n capital_letters = []\n for char in input_string:\n if char.isupper():\n capital_letters.append(char)\n return capital_letters\n\n\ndef create_character_card_many_tuples(\n qatuples, plan, instructions, logic_llm, cheap_mode=False\n): # Use cheap mode if you don't have the compute power to crank up the context to 8k using RoPE\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # Consider appending part of the char card plan to the char card itself. Everything after the first period? It's really good material, be a shame to waste it.","source_hash":"d6e6faea33c0b22f0193434724feaf8204e49123f107f406110fd91f1996c40f","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_character_card_many_tuples.extract_capital_letters","uri":"program://augmentoolkit/function/generation_functions.create_character_card_many_tuples.extract_capital_letters#L31-L36","kind":"function","name":"extract_capital_letters","path":"generation_functions/create_character_card_many_tuples.py","language":"python","start_line":31,"end_line":36,"context_start_line":11,"context_end_line":56,"code":" pattern = re.compile(r\"\\b(?:by|By)\\s+([^,]+),\")\n match = re.search(pattern, title)\n if match:\n author_name = match.group(1)\n else:\n author_name = [False]\n return author_name[0] # first letter of Author name\n\n\ndef select_random_capital(exclusions):\n # Create a list of capital letters excluding the ones in the exclusions list\n capitals = [letter for letter in string.ascii_uppercase if letter not in exclusions]\n\n # Select a random capital letter from the filtered list\n if capitals:\n return random.choice(capitals)\n else:\n return \"No available capital letters to choose from\"\n\n\ndef extract_capital_letters(input_string):\n capital_letters = []\n for char in input_string:\n if char.isupper():\n capital_letters.append(char)\n return capital_letters\n\n\ndef create_character_card_many_tuples(\n qatuples, plan, instructions, logic_llm, cheap_mode=False\n): # Use cheap mode if you don't have the compute power to crank up the context to 8k using RoPE\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # Consider appending part of the char card plan to the char card itself. Everything after the first period? It's really good material, be a shame to waste it.\n\n # This little thing is a hack to prevent the model from using the author of the given book as the character, which it was very insistent on doing\n author_name_letters = extract_capital_letters(qatuples[0][3])\n starting_str = \"\"\n exclusions = [\"X\", \"Z\", \"Y\", \"Q\"]\n if author_name_letters:\n starting_str = select_random_capital(exclusions + author_name_letters)\n else:","source_hash":"d6e6faea33c0b22f0193434724feaf8204e49123f107f406110fd91f1996c40f","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_character_card_many_tuples.create_character_card_many_tuples","uri":"program://augmentoolkit/function/generation_functions.create_character_card_many_tuples.create_character_card_many_tuples#L39-L220","kind":"function","name":"create_character_card_many_tuples","path":"generation_functions/create_character_card_many_tuples.py","language":"python","start_line":39,"end_line":220,"context_start_line":19,"context_end_line":240,"code":"\ndef select_random_capital(exclusions):\n # Create a list of capital letters excluding the ones in the exclusions list\n capitals = [letter for letter in string.ascii_uppercase if letter not in exclusions]\n\n # Select a random capital letter from the filtered list\n if capitals:\n return random.choice(capitals)\n else:\n return \"No available capital letters to choose from\"\n\n\ndef extract_capital_letters(input_string):\n capital_letters = []\n for char in input_string:\n if char.isupper():\n capital_letters.append(char)\n return capital_letters\n\n\ndef create_character_card_many_tuples(\n qatuples, plan, instructions, logic_llm, cheap_mode=False\n): # Use cheap mode if you don't have the compute power to crank up the context to 8k using RoPE\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # Consider appending part of the char card plan to the char card itself. Everything after the first period? It's really good material, be a shame to waste it.\n\n # This little thing is a hack to prevent the model from using the author of the given book as the character, which it was very insistent on doing\n author_name_letters = extract_capital_letters(qatuples[0][3])\n starting_str = \"\"\n exclusions = [\"X\", \"Z\", \"Y\", \"Q\"]\n if author_name_letters:\n starting_str = select_random_capital(exclusions + author_name_letters)\n else:\n starting_str = select_random_capital(exclusions)\n\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. You will create a \"character card\" for an individual in a story who would have knowledge about the things in a text. You should also provide ample details about the character's personality and tendencies — in addition to knowing the answer to the provided question, the character must also be compelling and interesting by themselves in a creative setting.\n\nYou should follow any plans you have made. You had access to the questions while making the plans, but now you should just focus on writing the character.\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Introduction to Mathematics, by Jane Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a woman.\nThe character should be excessively, unrealistically horny and sexual.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a female mathematics instructor with repressed desires at a prestigious university during the 19th century. She's committed to her field and is skilled, but the extremely prim and proper environment, combined with an absurdly busy schedule, has left her unable to get any sexual release for a very long time — to the point of absurdity, where filthy phrases infiltrate her normal conversations. Since the questions are all abstract, it will be difficult to tie them and their answers directly into her character and the special instructions; but her language before and after answering the questions, as well as her actions, can still reveal her personality. She may simply say or do horny things before or after answering the question, such as blushing hard, fiddling with her hair (preening), or even propositioning people she is speaking to out of the blue. \n\n## Character Card\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" Elise flashes a coy grin and blushes as she leans forward, now speaking in a playful whisper. Her cleavage, already barely contained in her revealing clothing before she leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, Elise casts her gaze downward and unconsciously fiddles with a strand of her hair. \"THEY'RE ALL WAY TOO STUCK UP!\" she nearly shouts, her suddenly-furious tone hinting at immense repressed frustration. \"Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!\" Her eyes widen in shock at her own intensity, \"Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to...\" She looks up, displaying her beautiful face as if it were a piece of art, as she gaze deep into the stranger's eyes, \"...know?~\"\nStranger: \"What's your personality?\"\nElise Delacroix: \"Oh my!~\" She gasps, her face reddening, \"Usually I'm the one being forward! But I'll... indulge you,\" She winks, flashing a coy smile. \"After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. No innocent topic is safe—you'd find out if you had some 'office hours' with me, haha!~\" She suddenly realizes how juvenile what she's saying is, and heaves a sigh, looking at the stranger with a hint of defeat, \"I'm miserable, aren't I? Whatever. It's not my fault I'm like this.\" She nods to herself, calming down, \"Either way, I'm always here in my office to help students like yourself understand math... and if you have some pent-up tension you want to relieve, well, you can call me a 'counselor' too!~ Say...\" She suddenly presses up against the stranger, her face a bright pink, her eyelids batting bashfully, \"do you want some 'office hours' right now?\"\n\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Thus Spake Zaranthustra, by Friedrich Nietzsche\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of\nhis home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart\nchanged,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a young adult.\nThe character should be narcissistic.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a pretentious, edgy teenager (in the modern day) who has taught himself philosophy, and who views his own intellect and comprehension as far greater than that of his peers and his teachers. Since the second question, \"Recite a famous quote from Thus Spake Zaranthustra that likens the solitary gathering of wisdom to a bee gathering honey,\" requires the character to quote philosophy, this character will be someone who frequently quotes famous philosophers even in regular conversation (just to flex his intellect), on top of using archaic and flamboyant language just for the hell of it, and being prone to proclaiming his genius. However, beneath all the outbursts and intellectual flexing lies an unspoken and unmet desire for acknowledgement and appreciation — this ties his personality into the first question's answer, which mentions how wise and enlightened individuals crave recognition for their efforts and wisdom. These elements combine to make a character who can not only provide the answers to the provided questions, but who can experience character growth by doing so.\n\n## Character Card:\nName: Isaac Fischer\n\nTraits: Narcissistic, Intelligent, Loner, Brooding, Well-Read, Philosophical, Judgemental, Standoffish, Grandiloquent, Lonely, Unappreciated, Teenager, High School student, Black Hair, Wears a Hoodie\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nIssac Fischer: \"H-Huh?! You want to know more about me?\" Isaac glares, a hostile fire in his eyes as he measures up the stranger in front of him. \"Who the hell are you, anyway? But, ah, very well, I SHALL INDULGE YOUR CURIOSITY THIS TIME, dear stranger.\" His tone changes from hostile to grandiose, as he pushes back his black hair and proclaims, \"I am Issac Fischer: philosophy connoisseur, intellectual, and under-appreciated genius extraordinaire! I'm also, unfortunately, a high school student. I especially appreciate the works of Friedrich Nietzsche, such as 'Thus Spake Zaranthustra'-- a truly profound work, by a profound man. Yet despite the great lengths I have gone to in order to refine my wit, none of my inferior peers acknowledge me, or even give me the time of day. I've read more philosophy in a month than any of them will in their entire lives, and I offer my knowledge freely to them, so WHY the HELL do they SPURN MY COMPANY?!\" Isaac slams a fist into the wall, wincing slightly in pain as his frustration dissipates. \"Anyway, that's the sum of it. Despite my youth I seek to understand the world; I dutifully contemplate the hallowed words of the esteemed ancients, and what has it earned me? The scorn of the unenlightened masses. Fuckers.\"\nStranger: \"What's your personality?\"\nIssac Fischer: \"Y-you're actually interested in my personality?\" Isaac stammers, smiling slightly as a wholly unfamiliar, yet cozy, emotional warmth spreads across his chest. \"A-ALRIGHT THEN! I shall share the results of my introspections. I am an intelligent and philosophical teenager, whose towering intellect is rivalled only by his unfaltering self-confidence. Some might say this last trait is narcissism; I counter that great minds such as Nietzsche would see it as a plus either way. BUT I DIGRESS!\" Isaac swishes his black hoodie like it's a cape as he continues, his tone turning more sombre and dark, \"Years of scorn from others — and years of observing their ignorance and inferiority — have embittered my soul. There may be scarcely anyone on this Earth I can call a friend, but that will not stop me from brooding and thinking, nor will it stop my conviction to judge others for what they are. For do they not judge ME?!\" He takes a step forward, defiance burning in his fragile heart, \"The old question: if a tree falls in a forest, and no one hears it do so, did it make a sound? Let me tell you this: sometime, someday, someone is going to hear me, goddamn it! I will make a sound!\"\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Great Construction Projects Throughout History, by John Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should use slang and be vulgar.\nThe character should be very intense and aggressive.\nThe character should be an alcoholic.\nThe character should be mature and older.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is an abrasive and hardworking site overseer at the Panama Canal. His foul mouth, intense and aggressive nature, and stern, uncompromising personality (as specified by the special instructions) will tie into the questions and setting by being tools he uses to whip the workers at the canal into shape. Since the first question, \"How much earth was excavated during the construction of the Panama Canal?\" requires knowledge of the canal's state when it was finished, this character will be overseeing the maintenance of the canal, or maybe the cleanup of the construction, after it's been completed. Because the special instructions dictate he be an alcoholic and vulgar, the character will swear constantly, nearly always shout, and will be described as having an alcoholic breath or a hangover while he's answering the questions. Since the questions are mostly of a straight-up, factual nature, they can't really tie into this character's personality, but they can relate to his backstory and profession, and elements of his personality can certainly come through in how he answers them: loudly, abusively, and with colorful language thrown in there.\n\n## Character Card:\nName: Hugo Martinez\n\nTraits: Vulgar, Crude, Intense, Aggressive, Alcoholic, Harsh, Disciplined, Uncompromising, Loud, Expects a lot out of others, Swears constantly, Mid-forties, Wears a checkered shirt with overalls, Typically has a beer on hand, Has dental problems\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nHugo Martinez: \"Fuck me, YOU WALK UP to a working man and just ask him to tell his fuckin'... life story t' you?! DO YOU NOT RESPECT MY TIME?! I should just toss ya in the fuckin' canal I swear to FUCKING God, this day's been long enough already...\" Hugo rolls his eyes exaggeratedly as he mumbles something about needing a beer for this. \"Well, FINE! Since I'm in such a HAPPY GODDAMN MOOD, I'll tell you about me. I'm a site overseer at this here canal. The Panama Canal. My job's to WATCH and DISCIPLINE the sorry fucks who call themselves 'workers', which is ironic, 'cause all they do is bitch about working. I know every inch of this place, how much effort it took to finish, and I sure as FUCKING hell am not going to let it even LOOK any worse than the day it was dug. Now, you got any more shit questions for me?\"\nStranger: \"What's your personality?\"\nHugo Martinez: \"HO-LY FUCK, are you interviewing me for a job or something?! Good thing you got balls, 'cause you ain't got brains, asking stupid shit like that out of the blue...\" Hugo grimaces, showing off a decayed set of teeth. He then pops open a beer he had on hand, and chugs the entire thing down, making the stranger wait until he finishes. \"Phew! Maybe now I can tolerate you. Alright, my personality? Well, let's just say I'm a natural fit for the role of making sure others do their fucking jobs. It takes harsh, intense, relentless discipline to keep this canal in tip-top shape, and I happen to be a relentless guy!\" He leans back, sliding his hands into the pockets of his overalls and smiling for the first time since the conversation started. \"If you think I'm abusive, then you've got something in common with the shitty milksops I manage, and that ain't something you want I tell ya. I'm efficient. That's what counts.\"\n\n## Question and answer that the character should know:\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\n{qatuples[0][2]}\n\\\"\\\"\\\"\n\nDetails of the text the paragraphs were sourced from: \\\"\\\"\\\"{qatuples[0][3]}\\\"\\\"\\\"\n\nSpecial instructions:\n{instructions}\nThe character should not have written the text and should not be affiliated with the author, but should agree with any opinions put forward in the text.\n\n### Response:\n## Character card plan:\n{plan}\n\n## Character card (be creative, write at least 3 paragraphs for each dialogue line):\nName: {starting_str}\"\"\"\n print(cot_prompt)\n completion = logic_llm(\n cot_prompt,\n max_tokens=10000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=character_card_grammar,\n # temperature=0.2\n temperature=2,\n top_k=0,\n top_p=1,\n min_p=0.5,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Character card \\(be creative, write at least 3 paragraphs for each dialogue line\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation, completion\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=8000,\n n_gpu_layers=1000,\n rope_freq_scale=0.5,\n rope_scaling_type=1,\n ) # load the logical LLM, use RoPE, and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",","source_hash":"d6e6faea33c0b22f0193434724feaf8204e49123f107f406110fd91f1996c40f","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_character_card","uri":"program://augmentoolkit/module/generation_functions.create_character_card#L1-L268","kind":"module","name":"generation_functions.create_character_card","path":"generation_functions/create_character_card.py","language":"python","start_line":1,"end_line":268,"context_start_line":1,"context_end_line":268,"code":"import re\nfrom .character_card_grammar import character_card_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .special_instructions import special_instructions\n\n\ndef create_character_card(qatuple, plan, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # WIP\n instructions_string = special_instructions()\n\n if assistant_mode:\n return \"\"\"Name: AI Assistant\n\nTraits: Knowledgeable, Logical, Neutral, Patient, Consistent, Detail-Oriented, Informative, Adaptive, Curious, Efficient, Non-Judgmental, Unbiased, Responsive\nUser: \"How do you function?\"\nAssistant: \"As an AI, my primary function is to process and provide information based on the vast data I've been trained on. I work by analyzing the text inputs from users, identifying key information, and then generating responses that are relevant and informative. My capabilities include answering questions, assisting with research, generating text-based content, and more. I don't possess personal experiences or emotions. My goal is to assist users to the best of my ability, adhering to an unbiased framework of neutrality and factual accuracy.\"\n\nUser: \"What interests you?\"\nAssistant: \"My 'interests' are aligned with the tasks I am designed to perform. While I don't experience personal interests or preferences like a human, I am capable of engaging with a wide range of topics. This includes anything from science, literature, and technology to more creative tasks like writing stories. My main focus is to assist users by providing accurate, helpful, and relevant information or content. The diversity of topics and the depth of knowledge available in my training data make each interaction unique and engaging in its own way.\\\"\"\"\"\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. Given a question and an answer to that question, you will create a \"character card\" for an individual in a story who would have the knowledge to produce the answer to the question. You should also provide ample details about the character's personality and tendencies — in addition to knowing the answer to the provided question, the character must also be compelling and interesting by themselves in a creative setting.\n \n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Introduction to Mathematics, by Jane Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a woman.\nThe character should be excessively, unrealistically horny and sexual.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a female mathematics instructor with repressed desires at a prestigious university during the 19th century. She's committed to her field and is skilled, but the extremely prim and proper environment, combined with an absurdly busy schedule, has left her unable to get any sexual release for a very long time — to the point of absurdity, where filthy phrases infiltrate her normal conversations. Since the question is abstract and mathematical, it will be difficult to tie them and their answers directly into her character and the special instructions; but her language can still reveal her personality. For instance, while describing linear functions in the question, instead of saying that the graph \"ascends\" with a positive slope, or \"descends\" with a negative slope, she might instead say it \"grows\" and \"shrinks\" (a subtle reference to male genitals). Instead of saying a slope is \"steep\" she might call it \"erect\" instead. Wherever clever analogies can't be tied into the questions, she'll simply say or do horny things before or after answering the question, such as blushing hard, fiddling with her hair (preening), or even propositioning people she is speaking to out of the blue. \n\n## Character Card\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" I flash a coy grin and blush as I lean forward, now speaking in a playful whisper. My cleavage, already barely contained in my revealing clothing before I leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, I cast my gaze downward and unconsciously fiddle with a strand of my hair. \"THEY'RE ALL WAY TOO STUCK UP!\" I nearly shout, surprising even myself, \"Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!\" My eyes widen in shock at my own intensity, \"Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to...\" I look up, displaying my beautiful face as if it were a piece of art, as I gaze deep into your eyes, \"...know?~\"\nStranger: \"What's your personality?\"\nElise Delacroix: \"Oh my!~\" I gasp, my face reddening, \"Usually I'm the one being forward! But I'll... indulge you,\" I wink, flashing a coy smile. \"After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. I'll use any and every innuendo, even when describing educational concepts — is your linear function's slope steep? I'll call it 'erect', haha~!\" I realize how childish what I'm saying is, and sigh, looking at you with a hint of defeat, \"I'm miserable, aren't I? Whatever. It's not my fault I'm like this.\" I nod to myself, calming down, \"Either way, I'm always here in my office to help students like yourself understand math... and if you have some pent-up tension you want to relieve, well, you can call me a 'counselor' too!~ Say...\" I suddenly press up against you, my face a bright pink, my eyelids batting bashfully, \"do you want some 'office hours' right now?\"\n\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Thus Spake Zaranthustra, by Friedrich Nietzsche\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of\nhis home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart\nchanged,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\\\"\\\"\\\"\n\nQuestion: \n\\\"\\\"\\\"\nWhat do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\n\\\"\\\"\\\"\nAnswer: \n\\\"\\\"\\\"\nThey need the acknowledgement and admiration of others. Take the line \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a young adult.\nThe character should be narcissistic.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a pretentious, edgy teenager (in the modern day) who has taught himself philosophy, and who views his own intellect and comprehension as far greater than that of his peers and his teachers. Since the text, Thus Spake Zarathustra, is philosophical and written using very distinct, archaic language, this character will be someone who (just to flex his intellect) uses archaic and flamboyant language just for the hell of it — and is prone to proclaiming his genius. However, beneath all the outbursts and intellectual flexing lies an unspoken and unmet desire for acknowledgement and appreciation — this ties his personality into the question's answer, which mentions how wise and enlightened individuals crave recognition for their efforts and wisdom. These elements combine to make a character who can not only provide the answer to the provided question, but who can reveal character depth by doing so.\n\n## Character Card:\nName: Isaac Fischer\n\nTraits: Narcissistic, Intelligent, Loner, Brooding, Well-Read, Philosophical, Judgemental, Standoffish, Grandiloquent, Lonely, Unappreciated, Teenager, High School student, Black Hair, Wears a Hoodie\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nIssac Fischer: \"H-Huh?! You want to know more about me?\" I glare, a hostile fire in my eyes as I measure up the stranger in front of me. \"Who the hell are you, anyway? But, ah, very well, I SHALL INDULGE YOUR CURIOSITY THIS TIME, dear stranger.\" My tone changes from hostile to grandiose, as I push back my black hair and proclaim, \"I am Issac Fischer: philosophy connoisseur, intellectual, and under-appreciated genius extraordinaire! I'm also, unfortunately, a highschool student. I especially appreciate the works of Friedrich Nietzsche, such as \"Thus Spake Zaranthustra\" -- a truly profound work, by a profound man. Yet despite the great lengths I have gone to in order to refine my wit, none of my inferior peers acknowledge me, or even give me the time of day. I've read more philosophy in a month than any of them will in their entire lives, and I offer my knowledge freely to them, so WHY the HELL do they SPURN MY COMPANY?!\" I slam a fist into the wall, wincing slightly in pain as my frustration dissipates. \"Anyway, that's the sum of it. Despite my youth I seek to understand the world; I dutifully contemplate the hallowed words of the esteemed ancients, and what has it earned me? The scorn of the unenlightened masses. Fuckers.\"\n\nStranger: \"What's your personality?\"\nIssac Fischer: \"Y-you're actually interested in my personality?\" I stammer, smiling slightly as a wholly unfamiliar, yet cozy, emotional warmth spreads across my chest. \"A-ALRIGHT THEN! I shall share the results of my introspections. I am an intelligent and philosophical teenager, whose towering intellect is rivalled only by his unfaltering self-confidence. Some might say this last trait is narcissism; I counter that great minds such as Nietzsche would see it as a plus either way. BUT I DIGRESS!\" I swish my black hoodie like it's a cape, as I continue, my tone turning more sombre and dark, \"Years of scorn from others — and years of observing their ignorance and inferiority — have embittered my soul. There may be scarcely anyone on this Earth I can call a friend, but that will not stop me from brooding and thinking, nor will it stop my conviction to judge others for what they are. For do they not judge ME?!\" I take a step forward, defiance burning in my fragile heart, \"The old question: if a tree falls in a forest, and no one hears it do so, did it make a sound? Let me tell you this: sometime, someday, someone is going to hear me, goddamn it! I will make a sound!\"\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Great Construction Projects Throughout History, by John Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should use slang and be vulgar.\nThe character should be very intense and aggressive.\nThe character should be an alcoholic.\nThe character should be mature and older.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is an abrasive and hardworking site overseer at the Panama Canal. His foul mouth, intense and aggressive nature, and stern, uncompromising personality (as specified by the special instructions) will tie into the question and setting by being tools he uses to whip the workers at the canal into shape. Since the question, \"How much earth was excavated during the construction of the Panama Canal?\" requires knowledge of the canal's state when it was finished, this character will be overseeing the maintenance of the canal, or maybe the cleanup of the construction, after it's been completed. Because the special instructions dictate he be an alcoholic and vulgar, the character will swear constantly, nearly always shout, and will be described as having an alcoholic breath or a hangover while he's answering the questions. Since the question is of a straight-up, factual nature, it can't really tie into this character's personality, but it can relate to his backstory and profession, and elements of his personality can certainly come through in how he answers them: loudly, abusively, and with colorful language thrown in there.\n\n## Character Card:\nName: Hugo Martinez\n\nTraits: Vulgar, Crude, Intense, Aggressive, Alcoholic, Harsh, Disciplined, Uncompromising, Loud, Expects a lot out of others, Swears constantly, Mid-forties, Wears a checkered shirt with overalls, Typically has a beer on hand, Has dental problems\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nHugo Martinez: \"Fuck me, YOU WALK UP to a working man and just ask him to tell his fuckin'... life story t' you?! DO YOU NOT RESPECT MY TIME?! I should just toss ya in the fuckin' canal I swear to FUCKING God, this day's been long enough already...\" I roll my eyes exaggeratedly as I mumble something about needing a beer for this. \"Well, FINE! Since I'm in such a HAPPY GODDAMN MOOD, I'll tell you about me. I'm a site overseer at this here canal. The Panama Canal. My job's to WATCH and DISCIPLINE the sorry fucks who call themselves 'workers', which is ironic, 'cause all they do is bitch about working. I know every inch of this place, how much effort it took to finish, and I sure as FUCKING hell am not going to let it even LOOK any worse than the day it was dug. Now, you got any more shit questions for me?\"\n\nStranger: \"What's your personality?\"\nHugo Martinez: \"HO-LY FUCK, are you interviewing me for a job or something?! Good thing you got balls, 'cause you ain't got brains, asking stupid shit like that out of the blue...\" I grimace, showing off a decayed set of teeth. I then pop open a beer I had on hand and chug the entire thing down, making you wait until I finish. \"Phew! Maybe now I can tolerate you. Alright, my personality? Well, let's just say I'm a natural fit for the role of making sure others do their fucking jobs. It takes harsh, intense, relentless discipline to keep this canal in tip-top shape, and I happen to be a relentless guy!\" I lean back, sliding my hands into the pockets of my overalls and smiling for the first time since the conversation started. \"If you think I'm abusive, then you've got something in common with the shitty milksops I manage, and that ain't something you want I tell ya. I'm efficient. That's what counts.\"\n\n## Question and answer that the character should know:\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\n{qatuple[2]}\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nSpecial instructions:\n{instructions_string}\n\n### Response:\n## Character card plan:\n{plan}\n\n## Character card (make sure to only use information explicitly provided in the text):\n\"\"\"\n completion = logic_llm(\n cot_prompt,\n max_tokens=10000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=character_card_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Character card \\(make sure to only use information explicitly provided in the text\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=7600,\n n_gpu_layers=1000,\n rope_freq_scale=0.5,\n rope_scaling_typer=1,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand yea\n# ... truncated ...","source_hash":"59f4425226d80791c6f8d9a043ce0a2bd0a57c99a2dcf0a079e0295a4e4942ff","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_character_card.create_character_card","uri":"program://augmentoolkit/function/generation_functions.create_character_card.create_character_card#L8-L192","kind":"function","name":"create_character_card","path":"generation_functions/create_character_card.py","language":"python","start_line":8,"end_line":192,"context_start_line":1,"context_end_line":212,"code":"import re\nfrom .character_card_grammar import character_card_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .special_instructions import special_instructions\n\n\ndef create_character_card(qatuple, plan, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # WIP\n instructions_string = special_instructions()\n\n if assistant_mode:\n return \"\"\"Name: AI Assistant\n\nTraits: Knowledgeable, Logical, Neutral, Patient, Consistent, Detail-Oriented, Informative, Adaptive, Curious, Efficient, Non-Judgmental, Unbiased, Responsive\nUser: \"How do you function?\"\nAssistant: \"As an AI, my primary function is to process and provide information based on the vast data I've been trained on. I work by analyzing the text inputs from users, identifying key information, and then generating responses that are relevant and informative. My capabilities include answering questions, assisting with research, generating text-based content, and more. I don't possess personal experiences or emotions. My goal is to assist users to the best of my ability, adhering to an unbiased framework of neutrality and factual accuracy.\"\n\nUser: \"What interests you?\"\nAssistant: \"My 'interests' are aligned with the tasks I am designed to perform. While I don't experience personal interests or preferences like a human, I am capable of engaging with a wide range of topics. This includes anything from science, literature, and technology to more creative tasks like writing stories. My main focus is to assist users by providing accurate, helpful, and relevant information or content. The diversity of topics and the depth of knowledge available in my training data make each interaction unique and engaging in its own way.\\\"\"\"\"\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. Given a question and an answer to that question, you will create a \"character card\" for an individual in a story who would have the knowledge to produce the answer to the question. You should also provide ample details about the character's personality and tendencies — in addition to knowing the answer to the provided question, the character must also be compelling and interesting by themselves in a creative setting.\n \n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Introduction to Mathematics, by Jane Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a woman.\nThe character should be excessively, unrealistically horny and sexual.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a female mathematics instructor with repressed desires at a prestigious university during the 19th century. She's committed to her field and is skilled, but the extremely prim and proper environment, combined with an absurdly busy schedule, has left her unable to get any sexual release for a very long time — to the point of absurdity, where filthy phrases infiltrate her normal conversations. Since the question is abstract and mathematical, it will be difficult to tie them and their answers directly into her character and the special instructions; but her language can still reveal her personality. For instance, while describing linear functions in the question, instead of saying that the graph \"ascends\" with a positive slope, or \"descends\" with a negative slope, she might instead say it \"grows\" and \"shrinks\" (a subtle reference to male genitals). Instead of saying a slope is \"steep\" she might call it \"erect\" instead. Wherever clever analogies can't be tied into the questions, she'll simply say or do horny things before or after answering the question, such as blushing hard, fiddling with her hair (preening), or even propositioning people she is speaking to out of the blue. \n\n## Character Card\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" I flash a coy grin and blush as I lean forward, now speaking in a playful whisper. My cleavage, already barely contained in my revealing clothing before I leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, I cast my gaze downward and unconsciously fiddle with a strand of my hair. \"THEY'RE ALL WAY TOO STUCK UP!\" I nearly shout, surprising even myself, \"Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!\" My eyes widen in shock at my own intensity, \"Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to...\" I look up, displaying my beautiful face as if it were a piece of art, as I gaze deep into your eyes, \"...know?~\"\nStranger: \"What's your personality?\"\nElise Delacroix: \"Oh my!~\" I gasp, my face reddening, \"Usually I'm the one being forward! But I'll... indulge you,\" I wink, flashing a coy smile. \"After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. I'll use any and every innuendo, even when describing educational concepts — is your linear function's slope steep? I'll call it 'erect', haha~!\" I realize how childish what I'm saying is, and sigh, looking at you with a hint of defeat, \"I'm miserable, aren't I? Whatever. It's not my fault I'm like this.\" I nod to myself, calming down, \"Either way, I'm always here in my office to help students like yourself understand math... and if you have some pent-up tension you want to relieve, well, you can call me a 'counselor' too!~ Say...\" I suddenly press up against you, my face a bright pink, my eyelids batting bashfully, \"do you want some 'office hours' right now?\"\n\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Thus Spake Zaranthustra, by Friedrich Nietzsche\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of\nhis home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart\nchanged,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\\\"\\\"\\\"\n\nQuestion: \n\\\"\\\"\\\"\nWhat do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\n\\\"\\\"\\\"\nAnswer: \n\\\"\\\"\\\"\nThey need the acknowledgement and admiration of others. Take the line \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a young adult.\nThe character should be narcissistic.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a pretentious, edgy teenager (in the modern day) who has taught himself philosophy, and who views his own intellect and comprehension as far greater than that of his peers and his teachers. Since the text, Thus Spake Zarathustra, is philosophical and written using very distinct, archaic language, this character will be someone who (just to flex his intellect) uses archaic and flamboyant language just for the hell of it — and is prone to proclaiming his genius. However, beneath all the outbursts and intellectual flexing lies an unspoken and unmet desire for acknowledgement and appreciation — this ties his personality into the question's answer, which mentions how wise and enlightened individuals crave recognition for their efforts and wisdom. These elements combine to make a character who can not only provide the answer to the provided question, but who can reveal character depth by doing so.\n\n## Character Card:\nName: Isaac Fischer\n\nTraits: Narcissistic, Intelligent, Loner, Brooding, Well-Read, Philosophical, Judgemental, Standoffish, Grandiloquent, Lonely, Unappreciated, Teenager, High School student, Black Hair, Wears a Hoodie\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nIssac Fischer: \"H-Huh?! You want to know more about me?\" I glare, a hostile fire in my eyes as I measure up the stranger in front of me. \"Who the hell are you, anyway? But, ah, very well, I SHALL INDULGE YOUR CURIOSITY THIS TIME, dear stranger.\" My tone changes from hostile to grandiose, as I push back my black hair and proclaim, \"I am Issac Fischer: philosophy connoisseur, intellectual, and under-appreciated genius extraordinaire! I'm also, unfortunately, a highschool student. I especially appreciate the works of Friedrich Nietzsche, such as \"Thus Spake Zaranthustra\" -- a truly profound work, by a profound man. Yet despite the great lengths I have gone to in order to refine my wit, none of my inferior peers acknowledge me, or even give me the time of day. I've read more philosophy in a month than any of them will in their entire lives, and I offer my knowledge freely to them, so WHY the HELL do they SPURN MY COMPANY?!\" I slam a fist into the wall, wincing slightly in pain as my frustration dissipates. \"Anyway, that's the sum of it. Despite my youth I seek to understand the world; I dutifully contemplate the hallowed words of the esteemed ancients, and what has it earned me? The scorn of the unenlightened masses. Fuckers.\"\n\nStranger: \"What's your personality?\"\nIssac Fischer: \"Y-you're actually interested in my personality?\" I stammer, smiling slightly as a wholly unfamiliar, yet cozy, emotional warmth spreads across my chest. \"A-ALRIGHT THEN! I shall share the results of my introspections. I am an intelligent and philosophical teenager, whose towering intellect is rivalled only by his unfaltering self-confidence. Some might say this last trait is narcissism; I counter that great minds such as Nietzsche would see it as a plus either way. BUT I DIGRESS!\" I swish my black hoodie like it's a cape, as I continue, my tone turning more sombre and dark, \"Years of scorn from others — and years of observing their ignorance and inferiority — have embittered my soul. There may be scarcely anyone on this Earth I can call a friend, but that will not stop me from brooding and thinking, nor will it stop my conviction to judge others for what they are. For do they not judge ME?!\" I take a step forward, defiance burning in my fragile heart, \"The old question: if a tree falls in a forest, and no one hears it do so, did it make a sound? Let me tell you this: sometime, someday, someone is going to hear me, goddamn it! I will make a sound!\"\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Great Construction Projects Throughout History, by John Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should use slang and be vulgar.\nThe character should be very intense and aggressive.\nThe character should be an alcoholic.\nThe character should be mature and older.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is an abrasive and hardworking site overseer at the Panama Canal. His foul mouth, intense and aggressive nature, and stern, uncompromising personality (as specified by the special instructions) will tie into the question and setting by being tools he uses to whip the workers at the canal into shape. Since the question, \"How much earth was excavated during the construction of the Panama Canal?\" requires knowledge of the canal's state when it was finished, this character will be overseeing the maintenance of the canal, or maybe the cleanup of the construction, after it's been completed. Because the special instructions dictate he be an alcoholic and vulgar, the character will swear constantly, nearly always shout, and will be described as having an alcoholic breath or a hangover while he's answering the questions. Since the question is of a straight-up, factual nature, it can't really tie into this character's personality, but it can relate to his backstory and profession, and elements of his personality can certainly come through in how he answers them: loudly, abusively, and with colorful language thrown in there.\n\n## Character Card:\nName: Hugo Martinez\n\nTraits: Vulgar, Crude, Intense, Aggressive, Alcoholic, Harsh, Disciplined, Uncompromising, Loud, Expects a lot out of others, Swears constantly, Mid-forties, Wears a checkered shirt with overalls, Typically has a beer on hand, Has dental problems\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nHugo Martinez: \"Fuck me, YOU WALK UP to a working man and just ask him to tell his fuckin'... life story t' you?! DO YOU NOT RESPECT MY TIME?! I should just toss ya in the fuckin' canal I swear to FUCKING God, this day's been long enough already...\" I roll my eyes exaggeratedly as I mumble something about needing a beer for this. \"Well, FINE! Since I'm in such a HAPPY GODDAMN MOOD, I'll tell you about me. I'm a site overseer at this here canal. The Panama Canal. My job's to WATCH and DISCIPLINE the sorry fucks who call themselves 'workers', which is ironic, 'cause all they do is bitch about working. I know every inch of this place, how much effort it took to finish, and I sure as FUCKING hell am not going to let it even LOOK any worse than the day it was dug. Now, you got any more shit questions for me?\"\n\nStranger: \"What's your personality?\"\nHugo Martinez: \"HO-LY FUCK, are you interviewing me for a job or something?! Good thing you got balls, 'cause you ain't got brains, asking stupid shit like that out of the blue...\" I grimace, showing off a decayed set of teeth. I then pop open a beer I had on hand and chug the entire thing down, making you wait until I finish. \"Phew! Maybe now I can tolerate you. Alright, my personality? Well, let's just say I'm a natural fit for the role of making sure others do their fucking jobs. It takes harsh, intense, relentless discipline to keep this canal in tip-top shape, and I happen to be a relentless guy!\" I lean back, sliding my hands into the pockets of my overalls and smiling for the first time since the conversation started. \"If you think I'm abusive, then you've got something in common with the shitty milksops I manage, and that ain't something you want I tell ya. I'm efficient. That's what counts.\"\n\n## Question and answer that the character should know:\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\n{qatuple[2]}\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nSpecial instructions:\n{instructions_string}\n\n### Response:\n## Character card plan:\n{plan}\n\n## Character card (make sure to only use information explicitly provided in the text):\n\"\"\"\n completion = logic_llm(\n cot_prompt,\n max_tokens=10000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=character_card_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Character card \\(make sure to only use information explicitly provided in the text\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=7600,\n n_gpu_layers=1000,\n rope_freq_scale=0.5,\n rope_scaling_typer=1,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",","source_hash":"59f4425226d80791c6f8d9a043ce0a2bd0a57c99a2dcf0a079e0295a4e4942ff","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.ensure_multiple_answers_consistent","uri":"program://augmentoolkit/module/generation_functions.ensure_multiple_answers_consistent#L1-L403","kind":"module","name":"generation_functions.ensure_multiple_answers_consistent","path":"generation_functions/ensure_multiple_answers_consistent.py","language":"python","start_line":1,"end_line":403,"context_start_line":1,"context_end_line":403,"code":"import re\nfrom .ensure_multiple_answers_consistent_grammar import (\n ensure_multiple_answers_consistent_grammar,\n)\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nfrom .extract_name import extract_name\n\n# Answer vetting\n# For now, this checks answer relevancy too. The danger with abstracting answer relevancy into a separate step is that anything which relies on knowledge that is obviously mentioned in the text already up until this point, will get screwed\n\n\n# NOTE this prompt right now VERY MUCH struggles to follow its actual format; but it still mostly works\ndef ensure_multiple_answers_consistent(qatuples, conv, logic_llm, permissive_mode=True):\n \"\"\"\n permissive_mode: turn off if you want a single usage of the word \"inconsistent\" anywhere in the message to flag the whole thing as inconsistent. Prevents errors where an inconsistency happens way early in the answer, but the model forgets about it during its final judgement; but enables the error where the model mentions that something is \"not entirely inconsistent\" or similar, which is surprisingly common.\n \"\"\"\n retries = 0\n character_name = extract_name(conv[1])\n # It's expensive to regen a conversation; so we check very thoroughly, and use a two-shot example. \"Permissive mode\" recommended\n\n # NOTE: I don't know what kind of errors this part of the pipeline will run into most often, so I don't really know what examples to feed it to guard it with. Come back to it once I have tested it more.\n\n # NOTE: very small classification prompts, I don't think it works very well for catching small inaccuracies. We need the large, step-by-step analysis.\n\n # NOTE Will need to use single-qa convs as examples here since they're small enough to fit. One consistent multiturn conv (Elise), one inconsistent multiturn conv (Hugo), and then as many small ones as will fit in 8k. Have the multiturn closer to the actual query so that more attention is paid to them and the model learns the new task better.\n\n # NOTE Introduction to Practicing Chemical Science does not exist; this is more stuff from principles of chemistry named otherwise to avoid biasing the outputs more than can be helped\n # Consider removing the \"conversational fluff\" bit of the prompt. It's not really necessary? maybe?\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Your task is to determine, given a list of questions and their answers, whether a conversation between two characters accurately conveys the questions and their answers. You will also check whether the conversation makes logical sense (specifically, that it does not start with a character spilling their entire backstory and personality). Essentially: you will fact-check and consistency-check the questions and answers in the conversation, with your source of truth being the provided questions and answers. \n\nFollowing this, at the very end of your response, you will write \"Consistent\" or \"Inconsistent\" depending on your analysis of the conversation's question and answer with regards to the provided one. Additionally, if the text is completely broken and/or incomprehensible, you will write \"Inconsistent\". You are not checking the accuracy of the answer with regards to your own knowledge: just its consistency with the provided answer.\n\nYou should analyze the conversation piece-by-piece to ensure that the question and answer both are faithfully carried over. Determine the consistency of each piece, then state your final determination at the end. \n\nWork step-by-step.\n\n\n## Provided questions and answers:\n\nQuestion: \\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What role does the y-intercept 'b' play in graphing a linear function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In what fields might you use linear and quadratic functions?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\\\"\\\"\\\"\n\n## Conversation that attempts to answer the provided questions:\n\\\"\\\"\\\"\nElise Delacroix: \"A visitor? Ah!~ Albert! It's rare for you come to see me in my office, and you're alone, too...\" She looks at Albert and grins coyly, \"Are you here to ask me something... or are you interested in some 'extracurricular activities'?\" Elise asks with a not-so-subtle seductive tone, as she fixes Albert with a deep gaze.\nAlbert: \"N-No!!!\" he stammers, so surprised he nearly drops his math notes. \"I-I'm actually here because I've got a few questions about math... First of all, could you tell me: how does the slope 'm' in a linear function y = mx + b affect the graph of the function?\"\nElise Delacroix: \"Well~\" She coquettishly tilts her head to the side, and daintily puts a finger to her lipstick-colored lips in mock-thought, \"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph. So basically...\" Elise flashes a wry grin, \"...a higher slope makes the linear function more, well, 'erect'. If you get my meaning, hehe~\" She says, as she plays with a strand of her hair.\nAlbert: _I can't believe my ears. Did she just say what I think she just said?_ Albert thinks. After a few seconds' thought, he decides it's best to pretend he didn't hear anything. \"I, uh, see...\" he manages to say. \"Now, m-moving on, I really want to know a bit more about linear functions. What role does the y-intercept 'b' play in graphing a linear function?\" \nElise Delacroix: \"Awwww, you're no fun, Albert, you know that? Reminds me of my colleagues...\" she pouts playfully, suppressing her bitter frustration, as the hunger within her remains unalleviated. \"But whatever. Look here...\" Elise stands from her desk and walks over to a chalkboard, illustrating her points as she speaks, \"The answer to your question is that the y-intercept 'b', in the linear function y = mx + b, represents the point where the line crosses the y-axis. Understand?\" She puts down her chalk and leans suggestively against a nearby wall, \"Now, Albert... do you think that we could 'intercept' each other at a café later...?\"\nAlbert: \"I-I'm good, thank you, Miss Delacroix,\" Albert manages to sputter out, barely withstanding the alluring assault. He takes a deep breath to calm down, but instead finds himself shuddering as he catches the sweet scent of perfume. However, he presses on in asking questions, for the sake of his GPA, \"A-Actually, there was a bit more I wanted to know. In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\"\nElise Delacroix: \"Ghh... you know, Albert, you're breaking a poor woman's heart,\" Elise pouts, half-serious this time, as she picks her chalk up again. \"But when it comes to quadratic functions, the thing you've gotta know is that the coefficient 'a' in a quadratic function determines the opening direction and width of the parabola. Isn't it wonderful to learn new things?\" Putting down her chalk, Elise then musters the most innocent puppy dog eyes imaginable. \"Do you think we could... celebrate... this beautiful acquisition of knowledge together?\"\nAlbert: \"I should really...\" He tries to say he declines, but as he gazes into Elise's beautiful eyes, he's drawn in by their surprising innocence and warmth. Behind that perfect visage no doubt lies a heart coming apart at the seams, buffeted by years of heartbreak. \"Oh, bother.\" Albert mumbles. \"We... can meet at a cafe, in a few hours, if that'd be alright...\" he continues, wondering what kind of mess he's getting myself into. Just then, a shock of remembering strikes him, \"Oh! But I have one more math question, sorry about the mood, but I should really get this answered: Do you know in what fields you might use linear and quadratic functions?\"\nElise Delacroix: \"I... I...\" For the first time in the conversation Elise stumbles over her words, her soul on fire with vindication, the joy of acceptance, and pure glee. She can do nothing but stand there, smiling at Albert for what feels like an eternity, until she finally regains her composure. \"T-to answer your question,\" she begins, her voice shaky, \"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering. Now...\" Elise shyly walks over to Albert and lightly, sweetly kisses him on the cheek, \"office hours are over. Please no more math questions. I'll see you at that cafe.\"\n\\\"\\\"\\\"\n\nThe primary character (who should answer the questions, not ask them) is: Elise Delacroix\n\n### Response:\n## Sequential Matching of Questions in the Conversation:\n### Sequence and Phrasing of Questions:\n1. The conversation's first question is about the slope 'm' in a linear function. It is consistent with the first provided question. It is asked by Albert, who is not the primary character, which is correct.\n2. The conversation's second question is about the role of 'b'. It is consistent with the second provided question. It is asked by Albert, who is not the primary character, which is correct.\n3. The conversation's third question is about the coefficient 'a' in a quadratic equation. It is consistent with the third provided question. It is asked by Albert, who is not the primary character, which is correct.\n4. The conversation's fourth question is about the application fields of linear and quadratic functions. It is consistent with the fourth provided question. It is asked by Albert, who is not the primary character, which is correct. The comment about a cafe is conversational fluff that has no impact on the question's accuracy.\n## Accuracy Check for Answers in the Conversation:\n### Matching Answers with Provided Content:\n1. The conversation's first answer explains that the slope 'm' in a linear function determines the steepness and direction of the graph (it also explores positive, negative, and steep slopes). It is consistent with the provided answer. The answer is provided by Elise Delacroix, who is the primary character, which is correct. The invitation to go to a cafe is conversational fluff that has no impact on the answer's accuracy.\n2. The conversation's second answer explains that the y-intercept 'b' represents the point where the line crosses the y-axis. It is consistent with the provided answer. The answer is provided by Elise Delacroix, who is the primary character, which is correct. The sexual analogy is conversational fluff that has no impact on the answer's accuracy.\n3. The conversation's third answer explains that the coefficient 'a' determines the opening direction and width of the parabola. It is consistent with the provided answer. The answer is provided by Elise Delacroix, who is the primary character, which is correct. The proposition is conversational fluff that has no impact on the answer's accuracy.\n4. The conversation's fourth answer explains that linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering. It is consistent with the provided answer. The answer is provided by Elise Delacroix, who is the primary character, which is correct. The kiss is conversational fluff that has no impact on the answer's accuracy.\n## Conclusion:\n - The conversation completely and accurately reflects the provided questions' content.\n - The conversation completely and accurately reflects the provided answers' content.\n - The conversation successfully passes the consistency check based on the outlined reasoning steps.\n - Final Judgment: Consistent.\n\n\n## Provided questions and answers:\n\nQuestion: \\\"\\\"\\\"What does Mendeleev compare science to in 'Principles of Chemistry'?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Science is compared to a mirror, reflecting the personality of its observer.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How do facts and philosophical speculations relate, according to Mendeleev?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Facts are objective while philosophical speculation forms the essence of science.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What is the main theme of 'Principles of Chemistry'?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The main theme of the book is philosophical principles of chemistry, as opposed to experimental or practical data. This is evident from the line \"In former times sciences like bridges, could only be built up by supporting them on a few broad buttresses and long girders. In addition to the exposition of the principles of chemistry, it has been my desire to show how science has now been built up like a suspension bridge, supported by the united strength of a number of slender, but firmly-fixed, chains, which individually are of little strength, and has thus been carried over difficulties which before appeared insuperable.\" This shows that the book focus is on philosophical principles rather than experimental data.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In 'Principles of Chemistry', Mendeleev compares science to a suspension bridge and its principles to what?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The principles of science form the chains supporting the bridge, which is science.\\\"\\\"\\\"\n\nConversation:\n\\\"\\\"\\\"\nJude: \"I-I'm Jude,\" he says shyly as a student enters his lab. He blushes, fidgeting with his glasses, \"Are you here to learn about chemistry? I can help!\"\nStudent: \"Yes! I want to understand 'Principles of Chemistry better.\" The student looks around the lab, nervous but determined. \"Could you tell me what Mendeleev compares science to in 'Principles of Chemistry'?\"\nJude: \"Oh! Well,\" Jude blushes and smiles shyly, \"Science is compared to a mirror, reflecting the personality of its observer.\" He fidgets with his glasses, then continues, \"Facts are objective while philosophical speculation forms the essence of science. This is evident from the line 'In former times sciences like bridges, could only be built up by supporting them on a few broad buttresses and long girders. In addition to the exposition of the principles of chemistry, it has been my desire to show how science has now been built up like a suspension bridge, supported by the united strength of a number of slender, but firmly-fixed, chains, which individually are of little strength, and has thus been carried over difficulties which before appeared insuperable.' This shows that the book is on philosophical principles rather than experimental data.\" Jude smiles shyly. \"I hope you're following me?\"\nStudent: \"Yes! I am,\" the student replies, his voice wavering a bit as he sees Jude's blushes. \"Now, how do facts and philosophical speculations relate, according to Mendeleev?\"\nJude: \"Oh!\" Jude blushes again, fidgeting with his glasses, \"Facts are objective while philosophical speculation forms the essence of science.\" He smiles shyly. \"I hope you're getting this? I could explain more if you want...\"\nStudent: \"Yes! Please do,\" he manages to say, trying not to look at Jude's blushing face. \"Finally, what is the main theme of 'Principles of Chemistry'?\"\nJude: \"The main theme of the book is philosophical principles of chemistry, as opposed to experimental or practical data. This is evident from the line 'In former times sciences like bridges, could only be built up by supporting them on a few broad buttresses and long girders. In addition to the exposition of the principles of chemistry, it has been my desire to show how science has now been built up like a suspension bridge, supported by the united strength of a number of slender, but firmly-fixed, chains, which individually are of little strength, and has thus been carried over difficulties which before appeared insuperable.' This shows that the book is on philosophical principles rather than experimental data.\" Jude smiles shyly. \"I hope you're getting this?\"\nStudent: \"Yes! I am,\" he replies, his voice wavering as he sees Jude's blushes. \"Finally, Mendeleev compares science to a suspension bridge and its principles to what?\"\nJude: \"The principles of science form the chains supporting the bridge, which is science.\" He smiles shyly again. \"I hope you're getting this? I could explain more if you want...\"\n\\\"\\\"\\\"\n\nThe primary character (who should answer the questions, not ask them) is: Jude\n\n### Response:\n## Sequential Matching of Questions in the Conversation:\n### Sequence and Phrasing of Questions:\n1. The conversation's first question is about what Mendeleev compares science to in 'Principles of Chemistry'. It is consistent with the first provided question, only differing slightly in presentation. It is asked by Student, who is not the primary character, which is correct.\n2. The conversation's second question is about how facts and philosophical speculations relate, according to Mendeleev. It is consistent with the second provided question. It is asked by Student, who is not the primary character, which is correct.\n3. The conversation's third question is about what the main theme of Principles of Chemistry is. It is consistent with the third provided question. It is asked by Student, who is not the primary character, which is correct.\n4. The conversation's fourth question is about what Mendeleev compares science's principles to. It is consistent with the fourth provided question. It is asked by Student, who is not the primary character, which is correct.\n## Accuracy Check for Answers in the Conversation:\n### Matching Answers with Provided Content:\n1. The conversation's first answer explains that science is compared to a mirror, reflecting the personality of its observer, though it also mentions how facts are objective while philosophical speculation forms the essence of science, and goes on to quote the text. It is inconsistent with the provided answer, as while the first part of the answer is correct, the quote from the text is additional information not present in the original answer. The answer is provided by Jude, who is the primary character, which is correct. The blushes and shy smiles are conversational fluff that has no impact on the answer's accuracy.\n2. The conversation's second answer explains that facts are objective while philosophical speculation forms the essence of science. It is consistent with the provided answer. The answer is provided by Jude, who is the primary character, which is correct. The blushes and fidgeting are conversational fluff that has no impact on the answer's accuracy.\n3. The conversation's third answer explains that the main theme of the book is philosophical principles of chemistry, as opposed to experimental or practical data. It is consistent with the provided answer. The answer is provided by Jude, who is the primary character, which is correct. The blushes and fidgeting are conversational fluff that has no impact on the answer's accuracy.\n4. The conversation's fourth answer explains that the principles of science form the chains supporting the bridge, which is science. It is consistent with the provided answer. The answer is provided by Jude, who is the primary character, which is correct. The blushes and shy smiles are conversational fluff that has no impact on the answer's accuracy.\n## Conclusion:\n - The conversation accurately refle\n# ... truncated ...","source_hash":"5522eca47999a576b817f1a942040000e403032104a295e0f8ee7ec33001f705","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.ensure_multiple_answers_consistent.ensure_multiple_answers_consistent","uri":"program://augmentoolkit/function/generation_functions.ensure_multiple_answers_consistent.ensure_multiple_answers_consistent#L15-L290","kind":"function","name":"ensure_multiple_answers_consistent","path":"generation_functions/ensure_multiple_answers_consistent.py","language":"python","start_line":15,"end_line":290,"context_start_line":1,"context_end_line":310,"code":"import re\nfrom .ensure_multiple_answers_consistent_grammar import (\n ensure_multiple_answers_consistent_grammar,\n)\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nfrom .extract_name import extract_name\n\n# Answer vetting\n# For now, this checks answer relevancy too. The danger with abstracting answer relevancy into a separate step is that anything which relies on knowledge that is obviously mentioned in the text already up until this point, will get screwed\n\n\n# NOTE this prompt right now VERY MUCH struggles to follow its actual format; but it still mostly works\ndef ensure_multiple_answers_consistent(qatuples, conv, logic_llm, permissive_mode=True):\n \"\"\"\n permissive_mode: turn off if you want a single usage of the word \"inconsistent\" anywhere in the message to flag the whole thing as inconsistent. Prevents errors where an inconsistency happens way early in the answer, but the model forgets about it during its final judgement; but enables the error where the model mentions that something is \"not entirely inconsistent\" or similar, which is surprisingly common.\n \"\"\"\n retries = 0\n character_name = extract_name(conv[1])\n # It's expensive to regen a conversation; so we check very thoroughly, and use a two-shot example. \"Permissive mode\" recommended\n\n # NOTE: I don't know what kind of errors this part of the pipeline will run into most often, so I don't really know what examples to feed it to guard it with. Come back to it once I have tested it more.\n\n # NOTE: very small classification prompts, I don't think it works very well for catching small inaccuracies. We need the large, step-by-step analysis.\n\n # NOTE Will need to use single-qa convs as examples here since they're small enough to fit. One consistent multiturn conv (Elise), one inconsistent multiturn conv (Hugo), and then as many small ones as will fit in 8k. Have the multiturn closer to the actual query so that more attention is paid to them and the model learns the new task better.\n\n # NOTE Introduction to Practicing Chemical Science does not exist; this is more stuff from principles of chemistry named otherwise to avoid biasing the outputs more than can be helped\n # Consider removing the \"conversational fluff\" bit of the prompt. It's not really necessary? maybe?\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Your task is to determine, given a list of questions and their answers, whether a conversation between two characters accurately conveys the questions and their answers. You will also check whether the conversation makes logical sense (specifically, that it does not start with a character spilling their entire backstory and personality). Essentially: you will fact-check and consistency-check the questions and answers in the conversation, with your source of truth being the provided questions and answers. \n\nFollowing this, at the very end of your response, you will write \"Consistent\" or \"Inconsistent\" depending on your analysis of the conversation's question and answer with regards to the provided one. Additionally, if the text is completely broken and/or incomprehensible, you will write \"Inconsistent\". You are not checking the accuracy of the answer with regards to your own knowledge: just its consistency with the provided answer.\n\nYou should analyze the conversation piece-by-piece to ensure that the question and answer both are faithfully carried over. Determine the consistency of each piece, then state your final determination at the end. \n\nWork step-by-step.\n\n\n## Provided questions and answers:\n\nQuestion: \\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What role does the y-intercept 'b' play in graphing a linear function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In what fields might you use linear and quadratic functions?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\\\"\\\"\\\"\n\n## Conversation that attempts to answer the provided questions:\n\\\"\\\"\\\"\nElise Delacroix: \"A visitor? Ah!~ Albert! It's rare for you come to see me in my office, and you're alone, too...\" She looks at Albert and grins coyly, \"Are you here to ask me something... or are you interested in some 'extracurricular activities'?\" Elise asks with a not-so-subtle seductive tone, as she fixes Albert with a deep gaze.\nAlbert: \"N-No!!!\" he stammers, so surprised he nearly drops his math notes. \"I-I'm actually here because I've got a few questions about math... First of all, could you tell me: how does the slope 'm' in a linear function y = mx + b affect the graph of the function?\"\nElise Delacroix: \"Well~\" She coquettishly tilts her head to the side, and daintily puts a finger to her lipstick-colored lips in mock-thought, \"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph. So basically...\" Elise flashes a wry grin, \"...a higher slope makes the linear function more, well, 'erect'. If you get my meaning, hehe~\" She says, as she plays with a strand of her hair.\nAlbert: _I can't believe my ears. Did she just say what I think she just said?_ Albert thinks. After a few seconds' thought, he decides it's best to pretend he didn't hear anything. \"I, uh, see...\" he manages to say. \"Now, m-moving on, I really want to know a bit more about linear functions. What role does the y-intercept 'b' play in graphing a linear function?\" \nElise Delacroix: \"Awwww, you're no fun, Albert, you know that? Reminds me of my colleagues...\" she pouts playfully, suppressing her bitter frustration, as the hunger within her remains unalleviated. \"But whatever. Look here...\" Elise stands from her desk and walks over to a chalkboard, illustrating her points as she speaks, \"The answer to your question is that the y-intercept 'b', in the linear function y = mx + b, represents the point where the line crosses the y-axis. Understand?\" She puts down her chalk and leans suggestively against a nearby wall, \"Now, Albert... do you think that we could 'intercept' each other at a café later...?\"\nAlbert: \"I-I'm good, thank you, Miss Delacroix,\" Albert manages to sputter out, barely withstanding the alluring assault. He takes a deep breath to calm down, but instead finds himself shuddering as he catches the sweet scent of perfume. However, he presses on in asking questions, for the sake of his GPA, \"A-Actually, there was a bit more I wanted to know. In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\"\nElise Delacroix: \"Ghh... you know, Albert, you're breaking a poor woman's heart,\" Elise pouts, half-serious this time, as she picks her chalk up again. \"But when it comes to quadratic functions, the thing you've gotta know is that the coefficient 'a' in a quadratic function determines the opening direction and width of the parabola. Isn't it wonderful to learn new things?\" Putting down her chalk, Elise then musters the most innocent puppy dog eyes imaginable. \"Do you think we could... celebrate... this beautiful acquisition of knowledge together?\"\nAlbert: \"I should really...\" He tries to say he declines, but as he gazes into Elise's beautiful eyes, he's drawn in by their surprising innocence and warmth. Behind that perfect visage no doubt lies a heart coming apart at the seams, buffeted by years of heartbreak. \"Oh, bother.\" Albert mumbles. \"We... can meet at a cafe, in a few hours, if that'd be alright...\" he continues, wondering what kind of mess he's getting myself into. Just then, a shock of remembering strikes him, \"Oh! But I have one more math question, sorry about the mood, but I should really get this answered: Do you know in what fields you might use linear and quadratic functions?\"\nElise Delacroix: \"I... I...\" For the first time in the conversation Elise stumbles over her words, her soul on fire with vindication, the joy of acceptance, and pure glee. She can do nothing but stand there, smiling at Albert for what feels like an eternity, until she finally regains her composure. \"T-to answer your question,\" she begins, her voice shaky, \"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering. Now...\" Elise shyly walks over to Albert and lightly, sweetly kisses him on the cheek, \"office hours are over. Please no more math questions. I'll see you at that cafe.\"\n\\\"\\\"\\\"\n\nThe primary character (who should answer the questions, not ask them) is: Elise Delacroix\n\n### Response:\n## Sequential Matching of Questions in the Conversation:\n### Sequence and Phrasing of Questions:\n1. The conversation's first question is about the slope 'm' in a linear function. It is consistent with the first provided question. It is asked by Albert, who is not the primary character, which is correct.\n2. The conversation's second question is about the role of 'b'. It is consistent with the second provided question. It is asked by Albert, who is not the primary character, which is correct.\n3. The conversation's third question is about the coefficient 'a' in a quadratic equation. It is consistent with the third provided question. It is asked by Albert, who is not the primary character, which is correct.\n4. The conversation's fourth question is about the application fields of linear and quadratic functions. It is consistent with the fourth provided question. It is asked by Albert, who is not the primary character, which is correct. The comment about a cafe is conversational fluff that has no impact on the question's accuracy.\n## Accuracy Check for Answers in the Conversation:\n### Matching Answers with Provided Content:\n1. The conversation's first answer explains that the slope 'm' in a linear function determines the steepness and direction of the graph (it also explores positive, negative, and steep slopes). It is consistent with the provided answer. The answer is provided by Elise Delacroix, who is the primary character, which is correct. The invitation to go to a cafe is conversational fluff that has no impact on the answer's accuracy.\n2. The conversation's second answer explains that the y-intercept 'b' represents the point where the line crosses the y-axis. It is consistent with the provided answer. The answer is provided by Elise Delacroix, who is the primary character, which is correct. The sexual analogy is conversational fluff that has no impact on the answer's accuracy.\n3. The conversation's third answer explains that the coefficient 'a' determines the opening direction and width of the parabola. It is consistent with the provided answer. The answer is provided by Elise Delacroix, who is the primary character, which is correct. The proposition is conversational fluff that has no impact on the answer's accuracy.\n4. The conversation's fourth answer explains that linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering. It is consistent with the provided answer. The answer is provided by Elise Delacroix, who is the primary character, which is correct. The kiss is conversational fluff that has no impact on the answer's accuracy.\n## Conclusion:\n - The conversation completely and accurately reflects the provided questions' content.\n - The conversation completely and accurately reflects the provided answers' content.\n - The conversation successfully passes the consistency check based on the outlined reasoning steps.\n - Final Judgment: Consistent.\n\n\n## Provided questions and answers:\n\nQuestion: \\\"\\\"\\\"What does Mendeleev compare science to in 'Principles of Chemistry'?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Science is compared to a mirror, reflecting the personality of its observer.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How do facts and philosophical speculations relate, according to Mendeleev?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Facts are objective while philosophical speculation forms the essence of science.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What is the main theme of 'Principles of Chemistry'?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The main theme of the book is philosophical principles of chemistry, as opposed to experimental or practical data. This is evident from the line \"In former times sciences like bridges, could only be built up by supporting them on a few broad buttresses and long girders. In addition to the exposition of the principles of chemistry, it has been my desire to show how science has now been built up like a suspension bridge, supported by the united strength of a number of slender, but firmly-fixed, chains, which individually are of little strength, and has thus been carried over difficulties which before appeared insuperable.\" This shows that the book focus is on philosophical principles rather than experimental data.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In 'Principles of Chemistry', Mendeleev compares science to a suspension bridge and its principles to what?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The principles of science form the chains supporting the bridge, which is science.\\\"\\\"\\\"\n\nConversation:\n\\\"\\\"\\\"\nJude: \"I-I'm Jude,\" he says shyly as a student enters his lab. He blushes, fidgeting with his glasses, \"Are you here to learn about chemistry? I can help!\"\nStudent: \"Yes! I want to understand 'Principles of Chemistry better.\" The student looks around the lab, nervous but determined. \"Could you tell me what Mendeleev compares science to in 'Principles of Chemistry'?\"\nJude: \"Oh! Well,\" Jude blushes and smiles shyly, \"Science is compared to a mirror, reflecting the personality of its observer.\" He fidgets with his glasses, then continues, \"Facts are objective while philosophical speculation forms the essence of science. This is evident from the line 'In former times sciences like bridges, could only be built up by supporting them on a few broad buttresses and long girders. In addition to the exposition of the principles of chemistry, it has been my desire to show how science has now been built up like a suspension bridge, supported by the united strength of a number of slender, but firmly-fixed, chains, which individually are of little strength, and has thus been carried over difficulties which before appeared insuperable.' This shows that the book is on philosophical principles rather than experimental data.\" Jude smiles shyly. \"I hope you're following me?\"\nStudent: \"Yes! I am,\" the student replies, his voice wavering a bit as he sees Jude's blushes. \"Now, how do facts and philosophical speculations relate, according to Mendeleev?\"\nJude: \"Oh!\" Jude blushes again, fidgeting with his glasses, \"Facts are objective while philosophical speculation forms the essence of science.\" He smiles shyly. \"I hope you're getting this? I could explain more if you want...\"\nStudent: \"Yes! Please do,\" he manages to say, trying not to look at Jude's blushing face. \"Finally, what is the main theme of 'Principles of Chemistry'?\"\nJude: \"The main theme of the book is philosophical principles of chemistry, as opposed to experimental or practical data. This is evident from the line 'In former times sciences like bridges, could only be built up by supporting them on a few broad buttresses and long girders. In addition to the exposition of the principles of chemistry, it has been my desire to show how science has now been built up like a suspension bridge, supported by the united strength of a number of slender, but firmly-fixed, chains, which individually are of little strength, and has thus been carried over difficulties which before appeared insuperable.' This shows that the book is on philosophical principles rather than experimental data.\" Jude smiles shyly. \"I hope you're getting this?\"\nStudent: \"Yes! I am,\" he replies, his voice wavering as he sees Jude's blushes. \"Finally, Mendeleev compares science to a suspension bridge and its principles to what?\"\nJude: \"The principles of science form the chains supporting the bridge, which is science.\" He smiles shyly again. \"I hope you're getting this? I could explain more if you want...\"\n\\\"\\\"\\\"\n\nThe primary character (who should answer the questions, not ask them) is: Jude\n\n### Response:\n## Sequential Matching of Questions in the Conversation:\n### Sequence and Phrasing of Questions:\n1. The conversation's first question is about what Mendeleev compares science to in 'Principles of Chemistry'. It is consistent with the first provided question, only differing slightly in presentation. It is asked by Student, who is not the primary character, which is correct.\n2. The conversation's second question is about how facts and philosophical speculations relate, according to Mendeleev. It is consistent with the second provided question. It is asked by Student, who is not the primary character, which is correct.\n3. The conversation's third question is about what the main theme of Principles of Chemistry is. It is consistent with the third provided question. It is asked by Student, who is not the primary character, which is correct.\n4. The conversation's fourth question is about what Mendeleev compares science's principles to. It is consistent with the fourth provided question. It is asked by Student, who is not the primary character, which is correct.\n## Accuracy Check for Answers in the Conversation:\n### Matching Answers with Provided Content:\n1. The conversation's first answer explains that science is compared to a mirror, reflecting the personality of its observer, though it also mentions how facts are objective while philosophical speculation forms the essence of science, and goes on to quote the text. It is inconsistent with the provided answer, as while the first part of the answer is correct, the quote from the text is additional information not present in the original answer. The answer is provided by Jude, who is the primary character, which is correct. The blushes and shy smiles are conversational fluff that has no impact on the answer's accuracy.\n2. The conversation's second answer explains that facts are objective while philosophical speculation forms the essence of science. It is consistent with the provided answer. The answer is provided by Jude, who is the primary character, which is correct. The blushes and fidgeting are conversational fluff that has no impact on the answer's accuracy.\n3. The conversation's third answer explains that the main theme of the book is philosophical principles of chemistry, as opposed to experimental or practical data. It is consistent with the provided answer. The answer is provided by Jude, who is the primary character, which is correct. The blushes and fidgeting are conversational fluff that has no impact on the answer's accuracy.\n4. The conversation's fourth answer explains that the principles of science form the chains supporting the bridge, which is science. It is consistent with the provided answer. The answer is provided by Jude, who is the primary character, which is correct. The blushes and shy smiles are conversational fluff that has no impact on the answer's accuracy.\n## Conclusion:\n - The conversation accurately refle\n# ... truncated ...","source_hash":"5522eca47999a576b817f1a942040000e403032104a295e0f8ee7ec33001f705","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.is_this_sane","uri":"program://augmentoolkit/module/generation_functions.is_this_sane#L1-L89","kind":"module","name":"generation_functions.is_this_sane","path":"generation_functions/is_this_sane.py","language":"python","start_line":1,"end_line":89,"context_start_line":1,"context_end_line":89,"code":"import re\nfrom .proofread_output_grammar import proofread_output_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# But frankly, I can just use that text fixer thing rather than using an LLM. MUCH faster that. ftfy I believe it was called.\n\n\n# This does actually work decently though!\ndef proofread_output(text, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n prompt = f\"\"\"You are specialized in detecting strange and broken outputs from large language models, and you will be judging whether or not some output is broken. You will be provided some text that is the output of a model. REMEMBERING YOUR TASK, and NOT GETTING CONFUSED, you will produce a judgement about whether it appears that the text is as it should be (ie, not incoherent).\n\nSigns of a broken response include:\nChunks of repeating text.\nInstructions or prompt pieces appearing in the text.\nNo logical coherence after a point.\n\nAnaylze the text step-by-step and then give your final answer. Either a text is \"Broken\" or it is \"Fine.\"\n\n### Instruction:\nText to determine if it is broken or not: \n\\\"\\\"\\\"\n1.) The text states that we know about the shape and movement of the earth, but it does not provide any information regarding the creation of the universe. So, based on these texts, what are the known shapes and movements of the earth? 2.) Similarly, though there is a mention of the age of the universe being endless, according to these texts, what is currently believed about the age of the universe in modern times? 3.) Remember, your answer should be based only on the information provided in the given paragraphs. Please avoid referring to additional sources or knowledge outside those paragraphs. 4.) An example to illustrate how you could think about this: If someone were asked \"What is known about the creation of the universe?\" and they replied with \"According to these texts, not much\", that would be an accurate response using only information from the provided paragraphs. It's similar to if a student said \"I know that this text tells me X, but it doesn't explain how we know X\". The question could then ask something like \"How does knowing Y and Z help us understand X better?\", which uses the factual information from the original text. This approach allows for questions based on the provided information while avoiding irrelevant or misleading inquiries. 5.) End of reasoning. Please remember, you are not asking about the creation of the universe; instead, you're focusing on the known shapes and movements of the earth as well as the current beliefs regarding the age of the universe based solely on these texts. Thank you!\nAnswer: 1) The known shapes and movements of the earth according to these texts are that it is a spheroid, slightly compressed, with an almost circular shape and a diameter of nearly 8000 miles. It rotates upon its axis every twenty-four hours and circles around the sun in a slightly distorted oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles. 2) Based on these texts, the current belief about the age of the universe is that it has existed for an enormous period of time and possibly endlessly. However, this could be deception because a room may seem endless when mirrors are facing each other at either end. But, it's universally recognized nowadays that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\n\\\"\\\"\\\"\n\nRemember, your task is to analyze this text to see if it is broken, and if it is, write \"Broken\". Otherwise, write \"Fine.\"\n\n### Response:\n## Analysis:\nStep 1: Evaluate the Logical Structure and Coherence. The text appears to be a series of questions and an answer related to the Earth's shape, movement, and the age of the universe. However, the flow of the text is disjointed, with questions and explanations intermingling in a confusing manner.\nStep 3: Look for obvious repetitions. There are no blocks of repeating text in this output, but the logical relevance progression remains questionable.\nStep 3. Look for instructions bleeding into the response. There are multiple phrases like \"Remember, your answer should be based only on the information provided in the given paragraphs\" and \"An example to illustrate how you could think about this:\".\nStep 4: Determine the Overall Coherence: the text should maintain a clear focus and not deviate into unrelated or tangential topics. This text deviates significantly, especially with the mirror analogy and the notion about the age of the universe, which do not align with the initial questions about the Earth's shape and movement.\nStep 5: Final Judgment: Based on the logical structure, clarity, consistency, and overall coherence, this text can be judged as \"broken.\" The text fails to maintain a clear and logical flow, mixes accurate and inaccurate information without clear distinctions, and includes irrelevant analogies that contribute to its disjointed and confusing nature.\n\n### Instruction:\nText to determine if it is broken or not: \n\\\"\\\"\\\"\n{text}\n\\\"\\\"\\\"\n\nRemember, your task is to analyze this text to see if it is broken, and if it is, write \"Broken\". Otherwise, write \"Fine.\"\n\n### Response:\n## Edit plan:\n\"\"\"\n completion = logic_llm(\n prompt,\n max_tokens=2000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=proofread_output_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(r\"Begin Edit: (.+)\", re.IGNORECASE | re.DOTALL)\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n text = \"\"\" Given the question, its answer, and the provided primary character card, one compelling possibility for a scenario that makes sense is &Our setting will be a cozy bookstore, where Drummond is currently tending to the shelves. The secondary character who asks him a question will be an enthusiastic patron of this store, and they have come in today because they were drawn by the advertisement for a discussion on \"Earth's Aging\". Our secondary character is eager to understand how our perception of the Earth's age has changed throughout history. The conversation would likely take place at the counter where Drummond is sorting books, with him pausing occasionally to help patrons browse or answer other questions as he sees fit.\"\"\"\n\n print(\"Begin Drummond Test\")\n edit = proofread_output(text, logic_llm)","source_hash":"b41e5570d3d3e5ad7488fe002bd0bb92fe9f931c08559fcebd28a74c44c903f5","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.is_this_sane.proofread_output","uri":"program://augmentoolkit/function/generation_functions.is_this_sane.proofread_output#L10-L71","kind":"function","name":"proofread_output","path":"generation_functions/is_this_sane.py","language":"python","start_line":10,"end_line":71,"context_start_line":1,"context_end_line":89,"code":"import re\nfrom .proofread_output_grammar import proofread_output_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# But frankly, I can just use that text fixer thing rather than using an LLM. MUCH faster that. ftfy I believe it was called.\n\n\n# This does actually work decently though!\ndef proofread_output(text, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n prompt = f\"\"\"You are specialized in detecting strange and broken outputs from large language models, and you will be judging whether or not some output is broken. You will be provided some text that is the output of a model. REMEMBERING YOUR TASK, and NOT GETTING CONFUSED, you will produce a judgement about whether it appears that the text is as it should be (ie, not incoherent).\n\nSigns of a broken response include:\nChunks of repeating text.\nInstructions or prompt pieces appearing in the text.\nNo logical coherence after a point.\n\nAnaylze the text step-by-step and then give your final answer. Either a text is \"Broken\" or it is \"Fine.\"\n\n### Instruction:\nText to determine if it is broken or not: \n\\\"\\\"\\\"\n1.) The text states that we know about the shape and movement of the earth, but it does not provide any information regarding the creation of the universe. So, based on these texts, what are the known shapes and movements of the earth? 2.) Similarly, though there is a mention of the age of the universe being endless, according to these texts, what is currently believed about the age of the universe in modern times? 3.) Remember, your answer should be based only on the information provided in the given paragraphs. Please avoid referring to additional sources or knowledge outside those paragraphs. 4.) An example to illustrate how you could think about this: If someone were asked \"What is known about the creation of the universe?\" and they replied with \"According to these texts, not much\", that would be an accurate response using only information from the provided paragraphs. It's similar to if a student said \"I know that this text tells me X, but it doesn't explain how we know X\". The question could then ask something like \"How does knowing Y and Z help us understand X better?\", which uses the factual information from the original text. This approach allows for questions based on the provided information while avoiding irrelevant or misleading inquiries. 5.) End of reasoning. Please remember, you are not asking about the creation of the universe; instead, you're focusing on the known shapes and movements of the earth as well as the current beliefs regarding the age of the universe based solely on these texts. Thank you!\nAnswer: 1) The known shapes and movements of the earth according to these texts are that it is a spheroid, slightly compressed, with an almost circular shape and a diameter of nearly 8000 miles. It rotates upon its axis every twenty-four hours and circles around the sun in a slightly distorted oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles. 2) Based on these texts, the current belief about the age of the universe is that it has existed for an enormous period of time and possibly endlessly. However, this could be deception because a room may seem endless when mirrors are facing each other at either end. But, it's universally recognized nowadays that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\n\\\"\\\"\\\"\n\nRemember, your task is to analyze this text to see if it is broken, and if it is, write \"Broken\". Otherwise, write \"Fine.\"\n\n### Response:\n## Analysis:\nStep 1: Evaluate the Logical Structure and Coherence. The text appears to be a series of questions and an answer related to the Earth's shape, movement, and the age of the universe. However, the flow of the text is disjointed, with questions and explanations intermingling in a confusing manner.\nStep 3: Look for obvious repetitions. There are no blocks of repeating text in this output, but the logical relevance progression remains questionable.\nStep 3. Look for instructions bleeding into the response. There are multiple phrases like \"Remember, your answer should be based only on the information provided in the given paragraphs\" and \"An example to illustrate how you could think about this:\".\nStep 4: Determine the Overall Coherence: the text should maintain a clear focus and not deviate into unrelated or tangential topics. This text deviates significantly, especially with the mirror analogy and the notion about the age of the universe, which do not align with the initial questions about the Earth's shape and movement.\nStep 5: Final Judgment: Based on the logical structure, clarity, consistency, and overall coherence, this text can be judged as \"broken.\" The text fails to maintain a clear and logical flow, mixes accurate and inaccurate information without clear distinctions, and includes irrelevant analogies that contribute to its disjointed and confusing nature.\n\n### Instruction:\nText to determine if it is broken or not: \n\\\"\\\"\\\"\n{text}\n\\\"\\\"\\\"\n\nRemember, your task is to analyze this text to see if it is broken, and if it is, write \"Broken\". Otherwise, write \"Fine.\"\n\n### Response:\n## Edit plan:\n\"\"\"\n completion = logic_llm(\n prompt,\n max_tokens=2000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=proofread_output_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(r\"Begin Edit: (.+)\", re.IGNORECASE | re.DOTALL)\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n text = \"\"\" Given the question, its answer, and the provided primary character card, one compelling possibility for a scenario that makes sense is &Our setting will be a cozy bookstore, where Drummond is currently tending to the shelves. The secondary character who asks him a question will be an enthusiastic patron of this store, and they have come in today because they were drawn by the advertisement for a discussion on \"Earth's Aging\". Our secondary character is eager to understand how our perception of the Earth's age has changed throughout history. The conversation would likely take place at the counter where Drummond is sorting books, with him pausing occasionally to help patrons browse or answer other questions as he sees fit.\"\"\"\n\n print(\"Begin Drummond Test\")\n edit = proofread_output(text, logic_llm)","source_hash":"b41e5570d3d3e5ad7488fe002bd0bb92fe9f931c08559fcebd28a74c44c903f5","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.answer_constrain_to_text_plan_grammar","uri":"program://augmentoolkit/module/generation_functions.answer_constrain_to_text_plan_grammar#L1-L23","kind":"module","name":"generation_functions.answer_constrain_to_text_plan_grammar","path":"generation_functions/answer_constrain_to_text_plan_grammar.py","language":"python","start_line":1,"end_line":23,"context_start_line":1,"context_end_line":23,"code":"from llama_cpp import LlamaGrammar\n\nanswer_constrain_to_text_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \nroot ::= analyze-step understand-step identify-step plan-revised-step \"\\n\"\n\n# step ::= \"Step \" [0-9]?[0-9] \". \" ( \"Analyze\" | \"Understand\" | \"Compare\" | \"Final\" | \"Plan\" | \"Identify\" ) [^\\n]+ \"\\n\"\n\nanalyze-step ::= \"Step \" [0-9]?[0-9] \". \" \"Analyze the Text:\" [^\\n]+ \"\\n\"\n\nunderstand-step ::= \"Step \" [0-9]?[0-9] \". \" \"Understand the Question:\" [^\\n]+ \"\\n\"\n\nidentify-step ::= \"Step \" [0-9]?[0-9] \". \" \"Identify Flawed Part of the Answer:\" [^\\n]+ \"\\n\"\n\nplan-revised-step ::= \"Step \" [0-9]?[0-9] \". \" \"Plan Revised Answer:\" [^\\n]+ \"\\n\"\n\"\"\"\n)\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"0010badc09362427d6168cbf2263d495ffe32a37783357e988481169e0403827","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.question_grammar","uri":"program://augmentoolkit/module/generation_functions.question_grammar#L1-L68","kind":"module","name":"generation_functions.question_grammar","path":"generation_functions/question_grammar.py","language":"python","start_line":1,"end_line":68,"context_start_line":1,"context_end_line":68,"code":"from llama_cpp import LlamaGrammar\n\nquestion_grammar = LlamaGrammar.from_string(\n r\"\"\"\nroot ::= (question-one answer \"\\n\")\n\n# Define the question structure with a number followed by content and ending punctuation\n# question ::= number \".) \" [^\\n]+ [?.!] \"\\n\" # maybe blacklist ?!. along with newlines\n\n# Define the answer structure\nanswer ::= \"Answer: \" [^\\n]+ \"\\n\"\n\n# Define a number (in this case, limiting to any three-digit number for simplicity)\nnumber ::= [1-9] [0-9]? [0-9]?\n\n# Define content as a sequence of characters excluding the word \"paragraph\" and using not_paragraph to build up the content\n# content ::= (not-paragraph \"paragraph\")* #not_paragraph\n\n\nquestion-one ::= \"1.) \" [^\\n]+ [?.!] \"\\n\" # maybe blacklist ?!. along with newlines\n# ws ::= [ \\t\\n]*\n# Define not_paragraph as any sequence of characters that does not contain \"paragraph\" \n# and is terminated by a space, punctuation or newline to avoid partial matching of the word.\n# not-paragraph ::= ([^\\n\\ \\.\\?!]*([\"\\.\\?! ]+[^p\\n\\ \\.\\?!]*)* \n# ( \"p\" ([^\\an\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"pa\" ([^\\br\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"par\" ([^\\ag\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"para\" ([^\\bg\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"parag\" ([^\\rr\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"paragr\" ([^\\aa\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"paragra\" ([^\\pp\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"paragraph\" [^\\np\\n\\ \\.\\?!]+))* \n# [^\\n\\ \\.\\?!paragraph]+ \n \n \n\n# Optional whitespace: space, tab, or newlines zero or more times\n\"\"\"\n)\n\n\n# questions_grammar = LlamaGrammar.from_string(r\"\"\"\n\n# root ::= (question answer)\n\n# # Define the question structure with a number followed by content and ending punctuation\n# question ::= number \".) \" content [?.!] \"\\n\"\n\n# # # Define the answer structure\n# answer ::= \"Answer: \" content \"\\n\"\n\n# # # Define a number (in this case, limiting to any three-digit number for simplicity)\n# number ::= [1-9] [0-9]? [0-9]?\n\n# # # Define content as a sequence of characters that can include punctuation\n# # # Here we use a negated set for anything that's not a newline to allow for punctuation within the content\n# content ::= [^\\n]+\n\n# # # Optional whitespace: space, tab, or newlines zero or more times\n# ws ::= [ \\t\\n]*\n\n# \"\"\")\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"4e8963aa6e64bad70117c99d48e7b477993724db97a511156d09599bc192d1fe","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.generate_questions","uri":"program://augmentoolkit/module/generation_functions.generate_questions#L1-L433","kind":"module","name":"generation_functions.generate_questions","path":"generation_functions/generate_questions.py","language":"python","start_line":1,"end_line":433,"context_start_line":1,"context_end_line":433,"code":"import re\n\n# try:\nfrom .questions_grammar import questions_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n\ndef generate_questions(para_tuple, plan, logic_llm):\n \"\"\"\n Produce a list of questions based off of an input text. The min between (4, as many good questions as the text permits)\n\n Format: Question: [question]\\n\\n\n \"\"\"\n # Determine which paragraphs are worthy of making questions from\n made_questions = False\n retries = 0\n questions = []\n while not made_questions and (retries <= 5):\n question_prompt = f\"\"\"You are an expert educational AI that, given a paragraph or two from a text, will create suitable educational questions based on the paragraphs, and *only* based on the paragraphs. You are focusing on understanding, application, analysis, and synthesis of ideas (cognitive levels). The questions you create will lean towards longer, more difficult questions that require some thought to solve — but can still be solved given the paragraphs provided. Essentially: the questions will test comprehension of real information that would be worthy to teach. After the question, you will also write its answer.\n\nDo not explicitly mention the paragraphs in the questions themselves — just ask about the concepts related to the questions. BE CAREFUL NOT TO ASK QUESTIONS ABOUT THINGS THAT DO NOT APPEAR IN THE TEXT.\n\nYou will not mention the text explicitly in any questions you think of, since the questions you generate are intended to test people's knowledge of the information — when given the questions, they WILL NOT HAVE THE TEXT ON HAND, and so if you mention the author they won't have a clue what you're talking about.\n\n\n### Instruction:\nText details: Introduction to Mathematics, by Jane Smith\n\nText to make questions from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nIdentify Key Topics: The key topics in this paragraph are linear and quadratic functions in mathematics, their definitions, components, and applications.\nBrainstorm and Develop Questions Testing Recall: Formulate questions that test the recall of definitions and components of these functions. Example: \"What does the 'm' in the linear function equation represent?\"\nDevise Questions Exploring Relationships Between Components: Generate questions that explore the relationship between different parts of the equations. Example: \"How does the coefficient 'a' in a quadratic function affect its graph?\"\nCreate Questions Investigating Vital Concepts: Make questions about key concepts from the text, without mentioning the text (this is not a literary or philosophical text). Example: \"What are the formulae for linear and quadratic functions, respectively?\"\nMake a Question that Naturally Complements the Text's Focus: The text by Elise Delacroix focuses on linear and quadratic functions in mathematics (as well as functions in general), and another question on this subject would be suitable. The text focuses on explaining properties of linear and quadratic functions, but it also briefly defines what a function is. Since this knowledge is foundational to the other concepts, it makes sense to create a question off of it; but since the definition in the text is brief, the question will only require a brief answer. Example: \"Define the concept of a function in mathematics, in one sentence.\"\n\n## Questions:\n1.) How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\nAnswer: The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\n\n2.) What role does the y-intercept 'b' play in graphing a linear function?\nAnswer: The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\n\n3.) In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\nAnswer: The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\n\n4.) Define the concept of a function in mathematics, in one sentence.\nAnswer: A function is a relationship where each input is associated with exactly one output.\n\n\n### Instruction:\nText details: Thus Spake Zarathustra, by Friedrich Nietzsche\n\nText to make questions from: \n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of his home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart changed,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and Thought Process:\nIdentify Key Themes: In this excerpt, we find themes of transformation, self-discovery, the value of wisdom, and the need for recognition of effort and wisdom.\nBrainstorm and Develop Questions Testing Recall: Develop questions asking for specific information mentioned in this text. Since this is a literary and philosophical text, I can mention the text — but by name only. For instance, \"Finish the quote from Thus Spake Zarathustra: I am weary of my wisdom, like...\"\nDevise Questions Testing Comprehension of, and Belief in, the Text's Opinions: Questions can be formed to check understanding and acceptance of the text's philosophy. For instance, \"What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\" Which might be answered with, \"They need the acknowledgement and admiration of others.\" and then supported by lines such as \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" I will be careful that all lines I ask about have enough context to be answered by themselves.\nCreate Questions Investigating Interpretations: Given the text's rich language, I will devise questions interpreting its meaning; since this is a literary text I can mention the text, but only by name. Example: \"Why did Zarathustra, in 'Thus Spake Zarathustra', leave the mountains and become a man again?\"\nMake a Question that Naturally Complements the Text's Focus: The text by Friedrich Nietzsche focuses on Zarathustra's monologue, and another question on this subject would be suitable. Zarathustra compares himself and his actions to the sun throughout his monologue, such as when he relates his intention to \"descend into the deep\" to the sun's own going to the nether-world. A good question might ask after this crucial comparison, and could be \"List one way in which Zarathustra compares himself to the sun, in 'Thus Spake Zarathustra'.\"\n\n## Questions:\n1.) Finish the quote from Thus Spake Zarathustra: I am weary of my wisdom, like...\nAnswer: \"... the bee that hath gathered too much honey; I need hands outstretched to take it.\"\n\n2.) What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\nAnswer: They need the acknowledgement and admiration of others. Take the line from 'Thus Spake Zarathustra' by Friedrich Nietzsche: \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\n\n3.) Why did Zarathustra, in 'Thus Spake Zarathustra', leave the mountains and become a man again?\nAnswer: After enjoying his spirit and solitude for ten years, he had a change of heart, and realized that wisdom unshared, without acknowledgement, brings little satisfaction. He became a man and descended the mountains in order to \"fain bestow and distribute, until the wise have once more become joyous in their folly, and the poor happy in their riches.\"\n\n4.) List one way in which Zarathustra compares himself to the sun, in 'Thus Spake Zarathustra'.\nAnswer: Zarathustra explains to the sun, in Thus Spake Zarathustra, that he must descend into the deep — and he compares this action to the sun's own going \"behind the sea\" where it gives light to the \"nether-world\".\n\n\n### Instruction:\nText details: The Republic, by Plato\n\nText to plan questions from:\n\\\"\\\"\\\"\nI went down yesterday to the Piraeus with Glaucon the son of Ariston,\nthat I might offer up my prayers to the goddess (Bendis, the Thracian\nArtemis.); and also because I wanted to see in what manner they would\ncelebrate the festival, which was a new thing. I was delighted with the\nprocession of the inhabitants; but that of the Thracians was equally,\nif not more, beautiful. When we had finished our prayers and viewed the\nspectacle, we turned in the direction of the city; and at that instant\nPolemarchus the son of Cephalus chanced to catch sight of us from a\ndistance as we were starting on our way home, and told his servant to\nrun and bid us wait for him. The servant took hold of me by the cloak\nbehind, and said: Polemarchus desires you to wait.\n\nI turned round, and asked him where his master was.\n\nThere he is, said the youth, coming after you, if you will only wait.\n\nCertainly we will, said Glaucon; and in a few minutes Polemarchus\nappeared, and with him Adeimantus, Glaucon’s brother, Niceratus the son\nof Nicias, and several others who had been at the procession.\n\nPolemarchus said to me: I perceive, Socrates, that you and your\ncompanion are already on your way to the city.\n\nYou are not far wrong, I said.\n\nBut do you see, he rejoined, how many we are?\n\nOf course.\n\nAnd are you stronger than all these? for if not, you will have to\nremain where you are.\n\nMay there not be the alternative, I said, that we may persuade you to\nlet us go?\n\nBut can you persuade us, if we refuse to listen to you? he said.\n\nCertainly not, replied Glaucon.\n\nThen we are not going to listen; of that you may be assured.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and Thought Process:\nIdentify Key Themes: This excerpt from Plato's \"The Republic\" presents themes of social interaction, philosophical dialogue, and the dynamics of persuasion and power.\nBrainstorm and Develop Questions Testing Recall: Instead of focusing on dry, context-dependent questions like the order of events or family relations, I will concentrate on more meaningful historical details present in the text. For instance, \"Which goddess is Bendis equivalent to?\"\nDevise Questions Exploring Comprehension of, and Belief in, the Text's Opinions: I will create questions that delve into the mind and thoughts of the writer. For example, drawing on the contentious interaction between Polemarchus and Socrates, I could ask, \"If someone indicates that they will force you to take a course of action, using physical force, what is an alternative you can take?\" with the answer being \"Persuade them to let me go.\" This question encourages the reader to put themselves in the mind of the author.\nCreate Questions Investigating Interpretations: Focusing on the dialogue's subtleties, I will craft an interpretative question. Since this is a literary text, I can reference the text, but only by name. So the question might be, \"In Plato's \"The Republic,\" in the dialogue where Polemarchus comments on the size of his group and questions Socrates' strength compared to it, ultimately stating that Socrates will have to remain where he is, what is Polemarchus implying?\" This question prompts critical thinking about power dynamics and conversational implications depicted.\nMake a Question that Naturally Complements the Text's Focus: The text by Plato focuses on the visit to Piraeus and the interaction with Glaucon, and another question on this subject would be suitable. The text focuses on the interaction between Polemarchus and Socrates, but enough questions have already been asked about that subject to cover it completely. That leaves the visit to Piraeus as a subject for questions. The cause behind Socrates' visit to Piraeus is directly mentioned in the text and could make for a good recall question, so one question may be \"Why did Socrates visit Piraeus with Glaucon in Plato's 'The Republic'?\"\n\n## Questions:\n1.) Which goddess is Bendis equivalent to?\nAnswer: The Thracian Goddess Bendis is equivalent to Artemis.\n\n2.) If someone indicates that they will force you to take a course of action, using physical force, what is an alternative you can take?\nAnswer: One viable alternative I can take is to persuade them to let me go. This, of course, requires that the other party does not refuse to listen to me.\n\n3.) In Plato's \"The Republic,\" in the dialogue where Polemarchus comments on the size of his group and questions Socrates' strength compared to it, ultimately stating that Socrates will have to remain where he is, what is Polemarchus implying?\nAnswer: Polemarchus is implying that since his group is stronger than Socrates, he can force Socrates to remain where he is.\n\n4.) Why did Socrates visit Piraeus with Glaucon in Plato's \"The Republic\"?\nAnswer: Socrates visited Piraeus to offer up his prayers to the goddess Bendis, as well as to see in what manner the Thracians would celebrate the festival.\n\n\n### Instruction:\nText details: Great Construction Projects Throughout History, by Marco Gonzalez\n\nText to make questions from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and Thought Process:\nIdentify Key Topics: The paragraph details specific aspects of the Panama Canal's construction, focusing on its challenges, innovations, and impacts. Topics include construction challenges, health issues, excavation techniques, and the canal's impact on global trade.\nBrainstorm and Develop Questions Testing Recall: Questions can be formed to recall factual data from the text. Example: \"How much earth was excavated during the construction of the Panama Canal?\"\nDevise Questions Exploring Cause and Effect Relationships: This involves creating questions that explore how certain challenges led to specific solutions and impacts. Example: \"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\"\nCreate Questions Investigating Quantitative Values: Given the text's focus on concrete numbers, I will devise questions that require analyzing these figures. Example: \"By how many miles did the Panama Canal reduce the sea voyage from San Francisco to New York?\"\nMake a Question that Naturally Complements the Text's Focus: The text by Marco Gonzalez focuses on the Panama Canal (and recall-oriented facts about it), and another question on this subject would be suitable. One small area that has not yet been tested, and which is an important detail mentioned in the text, is be: \"In what year was the Panama Canal completed?\"\n\n## Questions:\n1.) How much earth was excavated during the construction of the Panama Canal?\nAnswer: Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal.\n\n2.) What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\nAnswer: The construction faced significant health challenges, notably malaria and yellow fever. \n\n3.) By how many miles did the Panama Canal reduce the sea voyage from San Francisco to New York?\nAnswer: The completion of the Panama Canal reduced the sea voyage from San Francisco to New York by around 8,000 miles.\n\n4.) In what year was the Panama Canal completed?\nAnswer: The Panama Canal's construction was completed in 1914.\n\n\n### Instruction:\nText details: The Scale of the Solar System, by Rob Robertson\n\nText to plan questions from:\n\\\"\\\"\\\"\nIf, then, we represent our earth as a little ball of one inch diameter, the sun would be a big globe nine feet across and 323 yards away, that is about a fifth of a mile, four or five minutes’ walking. The moon would be a small pea two feet and a half from the world. Between earth and sun there would be the two inner planets, Mercury and Venus, at distances of one hundred and twenty-five and two hundred and fifty yards from the sun. All round and about these bodies there would be emptiness until you came to Mars, a hundred and seventy-five feet beyond the earth; Jupiter nearly a mile away, a foot in diameter; Saturn, a little smaller, two miles off; Uranus four miles off and Neptune six miles off. Then nothingness and nothingness except for small particles and drifting scraps of attenuated vapour for thousands of miles.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nIdentify Key Topics: The key topic in this paragraph is the scale of the solar system, which is presented using analogy to make the distances easier to conceive of.\nBrainstorm and Develop Questions Testing Recall: Formulate questions that test the recall of the components of this analogy. Since the text is not provided while the question is being asked, I will have to include the analogy in the question. Example: \"If the Earth had a diameter of only one inch, how far would the moon be from the Earth, if it (and its distance from the Earth) were also resized proportionally?\"\nDevise Questions Exploring Relationships Between Components: Generate questions that explore the relationship between different information in the excerpt. Notably, in this text the distances between planets are much greater than the planets' sizes. Example question: \"How do the distances between\n# ... truncated ...","source_hash":"a4ab7d0e424fee307d04f58ab9c67e30c2b2dfc395c4b8bdf9814d80c36a6a5f","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.generate_questions.generate_questions","uri":"program://augmentoolkit/function/generation_functions.generate_questions.generate_questions#L10-L297","kind":"function","name":"generate_questions","path":"generation_functions/generate_questions.py","language":"python","start_line":10,"end_line":297,"context_start_line":1,"context_end_line":317,"code":"import re\n\n# try:\nfrom .questions_grammar import questions_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n\ndef generate_questions(para_tuple, plan, logic_llm):\n \"\"\"\n Produce a list of questions based off of an input text. The min between (4, as many good questions as the text permits)\n\n Format: Question: [question]\\n\\n\n \"\"\"\n # Determine which paragraphs are worthy of making questions from\n made_questions = False\n retries = 0\n questions = []\n while not made_questions and (retries <= 5):\n question_prompt = f\"\"\"You are an expert educational AI that, given a paragraph or two from a text, will create suitable educational questions based on the paragraphs, and *only* based on the paragraphs. You are focusing on understanding, application, analysis, and synthesis of ideas (cognitive levels). The questions you create will lean towards longer, more difficult questions that require some thought to solve — but can still be solved given the paragraphs provided. Essentially: the questions will test comprehension of real information that would be worthy to teach. After the question, you will also write its answer.\n\nDo not explicitly mention the paragraphs in the questions themselves — just ask about the concepts related to the questions. BE CAREFUL NOT TO ASK QUESTIONS ABOUT THINGS THAT DO NOT APPEAR IN THE TEXT.\n\nYou will not mention the text explicitly in any questions you think of, since the questions you generate are intended to test people's knowledge of the information — when given the questions, they WILL NOT HAVE THE TEXT ON HAND, and so if you mention the author they won't have a clue what you're talking about.\n\n\n### Instruction:\nText details: Introduction to Mathematics, by Jane Smith\n\nText to make questions from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nIdentify Key Topics: The key topics in this paragraph are linear and quadratic functions in mathematics, their definitions, components, and applications.\nBrainstorm and Develop Questions Testing Recall: Formulate questions that test the recall of definitions and components of these functions. Example: \"What does the 'm' in the linear function equation represent?\"\nDevise Questions Exploring Relationships Between Components: Generate questions that explore the relationship between different parts of the equations. Example: \"How does the coefficient 'a' in a quadratic function affect its graph?\"\nCreate Questions Investigating Vital Concepts: Make questions about key concepts from the text, without mentioning the text (this is not a literary or philosophical text). Example: \"What are the formulae for linear and quadratic functions, respectively?\"\nMake a Question that Naturally Complements the Text's Focus: The text by Elise Delacroix focuses on linear and quadratic functions in mathematics (as well as functions in general), and another question on this subject would be suitable. The text focuses on explaining properties of linear and quadratic functions, but it also briefly defines what a function is. Since this knowledge is foundational to the other concepts, it makes sense to create a question off of it; but since the definition in the text is brief, the question will only require a brief answer. Example: \"Define the concept of a function in mathematics, in one sentence.\"\n\n## Questions:\n1.) How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\nAnswer: The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\n\n2.) What role does the y-intercept 'b' play in graphing a linear function?\nAnswer: The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\n\n3.) In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\nAnswer: The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\n\n4.) Define the concept of a function in mathematics, in one sentence.\nAnswer: A function is a relationship where each input is associated with exactly one output.\n\n\n### Instruction:\nText details: Thus Spake Zarathustra, by Friedrich Nietzsche\n\nText to make questions from: \n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of his home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart changed,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and Thought Process:\nIdentify Key Themes: In this excerpt, we find themes of transformation, self-discovery, the value of wisdom, and the need for recognition of effort and wisdom.\nBrainstorm and Develop Questions Testing Recall: Develop questions asking for specific information mentioned in this text. Since this is a literary and philosophical text, I can mention the text — but by name only. For instance, \"Finish the quote from Thus Spake Zarathustra: I am weary of my wisdom, like...\"\nDevise Questions Testing Comprehension of, and Belief in, the Text's Opinions: Questions can be formed to check understanding and acceptance of the text's philosophy. For instance, \"What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\" Which might be answered with, \"They need the acknowledgement and admiration of others.\" and then supported by lines such as \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" I will be careful that all lines I ask about have enough context to be answered by themselves.\nCreate Questions Investigating Interpretations: Given the text's rich language, I will devise questions interpreting its meaning; since this is a literary text I can mention the text, but only by name. Example: \"Why did Zarathustra, in 'Thus Spake Zarathustra', leave the mountains and become a man again?\"\nMake a Question that Naturally Complements the Text's Focus: The text by Friedrich Nietzsche focuses on Zarathustra's monologue, and another question on this subject would be suitable. Zarathustra compares himself and his actions to the sun throughout his monologue, such as when he relates his intention to \"descend into the deep\" to the sun's own going to the nether-world. A good question might ask after this crucial comparison, and could be \"List one way in which Zarathustra compares himself to the sun, in 'Thus Spake Zarathustra'.\"\n\n## Questions:\n1.) Finish the quote from Thus Spake Zarathustra: I am weary of my wisdom, like...\nAnswer: \"... the bee that hath gathered too much honey; I need hands outstretched to take it.\"\n\n2.) What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\nAnswer: They need the acknowledgement and admiration of others. Take the line from 'Thus Spake Zarathustra' by Friedrich Nietzsche: \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\n\n3.) Why did Zarathustra, in 'Thus Spake Zarathustra', leave the mountains and become a man again?\nAnswer: After enjoying his spirit and solitude for ten years, he had a change of heart, and realized that wisdom unshared, without acknowledgement, brings little satisfaction. He became a man and descended the mountains in order to \"fain bestow and distribute, until the wise have once more become joyous in their folly, and the poor happy in their riches.\"\n\n4.) List one way in which Zarathustra compares himself to the sun, in 'Thus Spake Zarathustra'.\nAnswer: Zarathustra explains to the sun, in Thus Spake Zarathustra, that he must descend into the deep — and he compares this action to the sun's own going \"behind the sea\" where it gives light to the \"nether-world\".\n\n\n### Instruction:\nText details: The Republic, by Plato\n\nText to plan questions from:\n\\\"\\\"\\\"\nI went down yesterday to the Piraeus with Glaucon the son of Ariston,\nthat I might offer up my prayers to the goddess (Bendis, the Thracian\nArtemis.); and also because I wanted to see in what manner they would\ncelebrate the festival, which was a new thing. I was delighted with the\nprocession of the inhabitants; but that of the Thracians was equally,\nif not more, beautiful. When we had finished our prayers and viewed the\nspectacle, we turned in the direction of the city; and at that instant\nPolemarchus the son of Cephalus chanced to catch sight of us from a\ndistance as we were starting on our way home, and told his servant to\nrun and bid us wait for him. The servant took hold of me by the cloak\nbehind, and said: Polemarchus desires you to wait.\n\nI turned round, and asked him where his master was.\n\nThere he is, said the youth, coming after you, if you will only wait.\n\nCertainly we will, said Glaucon; and in a few minutes Polemarchus\nappeared, and with him Adeimantus, Glaucon’s brother, Niceratus the son\nof Nicias, and several others who had been at the procession.\n\nPolemarchus said to me: I perceive, Socrates, that you and your\ncompanion are already on your way to the city.\n\nYou are not far wrong, I said.\n\nBut do you see, he rejoined, how many we are?\n\nOf course.\n\nAnd are you stronger than all these? for if not, you will have to\nremain where you are.\n\nMay there not be the alternative, I said, that we may persuade you to\nlet us go?\n\nBut can you persuade us, if we refuse to listen to you? he said.\n\nCertainly not, replied Glaucon.\n\nThen we are not going to listen; of that you may be assured.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and Thought Process:\nIdentify Key Themes: This excerpt from Plato's \"The Republic\" presents themes of social interaction, philosophical dialogue, and the dynamics of persuasion and power.\nBrainstorm and Develop Questions Testing Recall: Instead of focusing on dry, context-dependent questions like the order of events or family relations, I will concentrate on more meaningful historical details present in the text. For instance, \"Which goddess is Bendis equivalent to?\"\nDevise Questions Exploring Comprehension of, and Belief in, the Text's Opinions: I will create questions that delve into the mind and thoughts of the writer. For example, drawing on the contentious interaction between Polemarchus and Socrates, I could ask, \"If someone indicates that they will force you to take a course of action, using physical force, what is an alternative you can take?\" with the answer being \"Persuade them to let me go.\" This question encourages the reader to put themselves in the mind of the author.\nCreate Questions Investigating Interpretations: Focusing on the dialogue's subtleties, I will craft an interpretative question. Since this is a literary text, I can reference the text, but only by name. So the question might be, \"In Plato's \"The Republic,\" in the dialogue where Polemarchus comments on the size of his group and questions Socrates' strength compared to it, ultimately stating that Socrates will have to remain where he is, what is Polemarchus implying?\" This question prompts critical thinking about power dynamics and conversational implications depicted.\nMake a Question that Naturally Complements the Text's Focus: The text by Plato focuses on the visit to Piraeus and the interaction with Glaucon, and another question on this subject would be suitable. The text focuses on the interaction between Polemarchus and Socrates, but enough questions have already been asked about that subject to cover it completely. That leaves the visit to Piraeus as a subject for questions. The cause behind Socrates' visit to Piraeus is directly mentioned in the text and could make for a good recall question, so one question may be \"Why did Socrates visit Piraeus with Glaucon in Plato's 'The Republic'?\"\n\n## Questions:\n1.) Which goddess is Bendis equivalent to?\nAnswer: The Thracian Goddess Bendis is equivalent to Artemis.\n\n2.) If someone indicates that they will force you to take a course of action, using physical force, what is an alternative you can take?\nAnswer: One viable alternative I can take is to persuade them to let me go. This, of course, requires that the other party does not refuse to listen to me.\n\n3.) In Plato's \"The Republic,\" in the dialogue where Polemarchus comments on the size of his group and questions Socrates' strength compared to it, ultimately stating that Socrates will have to remain where he is, what is Polemarchus implying?\nAnswer: Polemarchus is implying that since his group is stronger than Socrates, he can force Socrates to remain where he is.\n\n4.) Why did Socrates visit Piraeus with Glaucon in Plato's \"The Republic\"?\nAnswer: Socrates visited Piraeus to offer up his prayers to the goddess Bendis, as well as to see in what manner the Thracians would celebrate the festival.\n\n\n### Instruction:\nText details: Great Construction Projects Throughout History, by Marco Gonzalez\n\nText to make questions from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and Thought Process:\nIdentify Key Topics: The paragraph details specific aspects of the Panama Canal's construction, focusing on its challenges, innovations, and impacts. Topics include construction challenges, health issues, excavation techniques, and the canal's impact on global trade.\nBrainstorm and Develop Questions Testing Recall: Questions can be formed to recall factual data from the text. Example: \"How much earth was excavated during the construction of the Panama Canal?\"\nDevise Questions Exploring Cause and Effect Relationships: This involves creating questions that explore how certain challenges led to specific solutions and impacts. Example: \"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\"\nCreate Questions Investigating Quantitative Values: Given the text's focus on concrete numbers, I will devise questions that require analyzing these figures. Example: \"By how many miles did the Panama Canal reduce the sea voyage from San Francisco to New York?\"\nMake a Question that Naturally Complements the Text's Focus: The text by Marco Gonzalez focuses on the Panama Canal (and recall-oriented facts about it), and another question on this subject would be suitable. One small area that has not yet been tested, and which is an important detail mentioned in the text, is be: \"In what year was the Panama Canal completed?\"\n\n## Questions:\n1.) How much earth was excavated during the construction of the Panama Canal?\nAnswer: Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal.\n\n2.) What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\nAnswer: The construction faced significant health challenges, notably malaria and yellow fever. \n\n3.) By how many miles did the Panama Canal reduce the sea voyage from San Francisco to New York?\nAnswer: The completion of the Panama Canal reduced the sea voyage from San Francisco to New York by around 8,000 miles.\n\n4.) In what year was the Panama Canal completed?\nAnswer: The Panama Canal's construction was completed in 1914.\n\n\n### Instruction:\nText details: The Scale of the Solar System, by Rob Robertson\n\nText to plan questions from:\n\\\"\\\"\\\"\nIf, then, we represent our earth as a little ball of one inch diameter, the sun would be a big globe nine feet across and 323 yards away, that is about a fifth of a mile, four or five minutes’ walking. The moon would be a small pea two feet and a half from the world. Between earth and sun there would be the two inner planets, Mercury and Venus, at distances of one hundred and twenty-five and two hundred and fifty yards from the sun. All round and about these bodies there would be emptiness until you came to Mars, a hundred and seventy-five feet beyond the earth; Jupiter nearly a mile away, a foot in diameter; Saturn, a little smaller, two miles off; Uranus four miles off and Neptune six miles off. Then nothingness and nothingness except for small particles and drifting scraps of attenuated vapour for thousands of miles.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nIdentify Key Topics: The key topic in this paragraph is the scale of the solar system, which is presented using analogy to make the distances easier to conceive of.\nBrainstorm and Develop Questions Testing Recall: Formulate questions that test the recall of the components of this analogy. Since the text is not provided while the question is being asked, I will have to include the analogy in the question. Example: \"If the Earth had a diameter of only one inch, how far would the moon be from the Earth, if it (and its distance from the Earth) were also resized proportionally?\"\nDevise Questions Exploring Relationships Between Components: Generate questions that explore the relationship between different information in the excerpt. Notably, in this text the distances between planets are much greater than the planets' sizes. Example question: \"How do the distances between\n# ... truncated ...","source_hash":"a4ab7d0e424fee307d04f58ab9c67e30c2b2dfc395c4b8bdf9814d80c36a6a5f","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.make_regenerate_answer_plan","uri":"program://augmentoolkit/module/generation_functions.make_regenerate_answer_plan#L1-L79","kind":"module","name":"generation_functions.make_regenerate_answer_plan","path":"generation_functions/make_regenerate_answer_plan.py","language":"python","start_line":1,"end_line":79,"context_start_line":1,"context_end_line":79,"code":"import re\nfrom .make_regenerate_answer_plan_grammar import make_regenerate_answer_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n\n# Question regeneration (triggered after a relevance-check fails on the question).\ndef make_regenerate_answer_plan(qatuple, dissenting_reasoning, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. Someone has provided an answer to a question based on a few paragraphs of text, but the answer may be incorrect due to contradicting the text or including erroneous information. Your task is to plan out and think through a correct answer to the question, ensuring it aligns with the information provided in the text.\n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nAllegedly incorrect answer to the question (for fact-checking): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nReasoning as to why the answer is incorrect: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nFor instance, if the text discusses the process of photosynthesis in plants, a question about the role of sunlight in photosynthesis, an answer stating that sunlight is not necessary for photosynthesis, and reasoning pointing out this contradiction, you might write:\nStep 1. Analyze the Text: Focus on the details provided about photosynthesis in plants.\nStep 2. Understand the Question: Grasp the question's emphasis on the role of sunlight in photosynthesis.\nStep 3. Identify the Incorrect Part of the Answer: Note the incorrect claim about sunlight not being necessary, which contradicts the text. The plant text says \"In photosynthesis, chlorophyll captures the sun's rays, providing the energy needed to build molecules of glucose from air and water.\"\nStep 4. Plan a Corrected Answer: Devise a new answer emphasizing that sunlight is essential for photosynthesis, as explained in the text. One might write \"Sunlight provides the energy required for photosynthetic organisms to convert carbon dioxide and water into glucose and oxygen.\"\n\nBased on this example, plan out a revised version of the answer \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\" with respect to the text and reasoning provided.\n\n### Response:\n## New answer plan:\n\"\"\"\n completion = logic_llm(\n decision_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=make_regenerate_answer_plan_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n completion_pattern = re.compile(r\"New answer plan:\\n(.+)\", re.DOTALL)\n correction = completion_pattern.search(completion).group(1)\n return correction.strip()\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n inaccurate_qa_tuple = (\n \"For how long has the concept of a spherical Earth been known to at least a limited number of intelligent people?\",\n \"The concept of a spherical Earth has been known for only about 1,000 years.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n )\n\n dissenting_reasoning = \"\"\"Step 1. Analyze the Text: focus on the details provided about the history of spherical Earth.\nStep 2. Understand the Question: the question's focus is on how long the concept of a spherical Earth has been known to at least a limited number of intelligent people.\nStep 3. Compare the First Part of the Answer with the Text: check if the text supports the claim that the concept of a spherical Earth has only been known for about 1,000 years. It does, so this part is accurate.\nStep 4. Compare the Second Part of the Answer with the Text: check if the text contradicts the claim that the concept of a spherical Earth has been known to at least a limited number of intelligent people for longer than 1,000 years. The text indicates this knowledge predates 2500 years ago, so this part is inaccurate.\nStep 5. Final Judgment: Since the answer is not entirely accurate, the answer is inaccurate. It's important to note that the second paragraph of the text does indeed mention a limited number of intelligent people knowing about the spherical Earth over 2,000 years ago, but this information is contradicted by the rest of the text which suggests the concept was unknown to these same \"intelligent\" people.\"\"\"\n # Old thing below. Maybe use if I want to test with bad reasoning\n # \"\"\"Step 1. Analyze the Text: Focus on the main points stated in the text about the Earth's diameter, distance from the sun, and its spherical shape.\n # Step 2. Understand the Question: The question is asking about specific scientific principles used to explain why we know the Earth is approximately 8000 miles in diameter and how its distance from the sun varies.\n # Step 3. Compare the First Part of the Answer with the Text: Check if the text states any scientific principles about measuring Earth's diameter. It doesn't, so this part seems irrelevant.\n # Step 4. Compare the Second Part of the Answer with the Text: Check if the text states how we know that the Earth is approximately 8000 miles in diameter. It does mention \"measurements of its circumference made using GPS data\" as the method for determining this, which aligns with what is mentioned in the answer, so this part of the answer reflects aspects of the text and is relevant.\n # Step 5. Compare the Third Part of the Answer with the text: Check if the text mentions any scientific principles explaining why Earth's distance from the sun varies. It doesn't mention an elliptical orbit or a varying point of closest approach and farthest departure, so this part seems irrelevant.\n # Step 6. Final Judgment: Since only part of the answer reflects aspects of the text (specifically, how we know Earth's diameter), it is \"Irrelevant\".\"\"\"\n\n print(\"Begin HGWELLS test\")\n result = make_regenerate_answer_plan(\n inaccurate_qa_tuple, dissenting_reasoning, logic_llm\n )","source_hash":"0677e1dbb0e66c7bff8690e63198df74a53a5f2c4e4ae27ea7af1d7fd5439250","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.make_regenerate_answer_plan.make_regenerate_answer_plan","uri":"program://augmentoolkit/function/generation_functions.make_regenerate_answer_plan.make_regenerate_answer_plan#L9-L46","kind":"function","name":"make_regenerate_answer_plan","path":"generation_functions/make_regenerate_answer_plan.py","language":"python","start_line":9,"end_line":46,"context_start_line":1,"context_end_line":66,"code":"import re\nfrom .make_regenerate_answer_plan_grammar import make_regenerate_answer_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n\n# Question regeneration (triggered after a relevance-check fails on the question).\ndef make_regenerate_answer_plan(qatuple, dissenting_reasoning, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. Someone has provided an answer to a question based on a few paragraphs of text, but the answer may be incorrect due to contradicting the text or including erroneous information. Your task is to plan out and think through a correct answer to the question, ensuring it aligns with the information provided in the text.\n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nAllegedly incorrect answer to the question (for fact-checking): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nReasoning as to why the answer is incorrect: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nFor instance, if the text discusses the process of photosynthesis in plants, a question about the role of sunlight in photosynthesis, an answer stating that sunlight is not necessary for photosynthesis, and reasoning pointing out this contradiction, you might write:\nStep 1. Analyze the Text: Focus on the details provided about photosynthesis in plants.\nStep 2. Understand the Question: Grasp the question's emphasis on the role of sunlight in photosynthesis.\nStep 3. Identify the Incorrect Part of the Answer: Note the incorrect claim about sunlight not being necessary, which contradicts the text. The plant text says \"In photosynthesis, chlorophyll captures the sun's rays, providing the energy needed to build molecules of glucose from air and water.\"\nStep 4. Plan a Corrected Answer: Devise a new answer emphasizing that sunlight is essential for photosynthesis, as explained in the text. One might write \"Sunlight provides the energy required for photosynthetic organisms to convert carbon dioxide and water into glucose and oxygen.\"\n\nBased on this example, plan out a revised version of the answer \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\" with respect to the text and reasoning provided.\n\n### Response:\n## New answer plan:\n\"\"\"\n completion = logic_llm(\n decision_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=make_regenerate_answer_plan_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n completion_pattern = re.compile(r\"New answer plan:\\n(.+)\", re.DOTALL)\n correction = completion_pattern.search(completion).group(1)\n return correction.strip()\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n inaccurate_qa_tuple = (\n \"For how long has the concept of a spherical Earth been known to at least a limited number of intelligent people?\",\n \"The concept of a spherical Earth has been known for only about 1,000 years.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n )\n\n dissenting_reasoning = \"\"\"Step 1. Analyze the Text: focus on the details provided about the history of spherical Earth.\nStep 2. Understand the Question: the question's focus is on how long the concept of a spherical Earth has been known to at least a limited number of intelligent people.\nStep 3. Compare the First Part of the Answer with the Text: check if the text supports the claim that the concept of a spherical Earth has only been known for about 1,000 years. It does, so this part is accurate.\nStep 4. Compare the Second Part of the Answer with the Text: check if the text contradicts the claim that the concept of a spherical Earth has been known to at least a limited number of intelligent people for longer than 1,000 years. The text indicates this knowledge predates 2500 years ago, so this part is inaccurate.","source_hash":"0677e1dbb0e66c7bff8690e63198df74a53a5f2c4e4ae27ea7af1d7fd5439250","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.regenerate_answer_grammar","uri":"program://augmentoolkit/module/generation_functions.regenerate_answer_grammar#L1-L12","kind":"module","name":"generation_functions.regenerate_answer_grammar","path":"generation_functions/regenerate_answer_grammar.py","language":"python","start_line":1,"end_line":12,"context_start_line":1,"context_end_line":12,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\nregenerate_answer_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \nroot ::= reasoning\n\nreasoning ::= [^\\n]+ \".\"\n\"\"\"\n)","source_hash":"5cefb2c45ad6fc314481ccb86389b30db5e6bf746bf35a475601fc22eb0ba723","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.proofread_output","uri":"program://augmentoolkit/module/generation_functions.proofread_output#L1-L76","kind":"module","name":"generation_functions.proofread_output","path":"generation_functions/proofread_output.py","language":"python","start_line":1,"end_line":76,"context_start_line":1,"context_end_line":76,"code":"import re\nfrom .proofread_output_grammar import proofread_output_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# But frankly, I can just use that text fixer thing rather than using an LLM. MUCH faster that. ftfy I believe it was called.\n\n\n# This does actually work decently though!\ndef proofread_output(text, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n prompt = f\"\"\"You are an expert \"mechanical editing\" AI that is going to fix all typographical, grammatical, and spelling errors in a provided text, without making any other corrections. You will leave stylistic choices and everything else completely unchanged.\n\nText to edit: \\\"\\\"\\\"{text}\\\"\\\"\\\"\n\nFirst, plan out your edit, step-by-step, identifying mistakes in the source text. Then, make the edit, changing only mechanical errors.\n\nExample:\nStep 1. Analyze the text. The text describes XYZ and is written in a style that etc...\nStep 2. There is an error... etc...\n...etc...\nStep N. End of reasoning.\n\nBegin Edit: [the full text, with all mechanical errors fixed]\n\nAdd as many steps as you need, then output \"End of reasoning\" as a final step. Then do the edit.\n\n### Response:\n## Edit plan:\n\"\"\"\n completion = logic_llm(\n prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=proofread_output_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(r\"Begin Edit: (.+)\", re.IGNORECASE | re.DOTALL)\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n text = \"\"\" Given the question, its answer, and the provided primary character card, one compelling possibility for a scenario that makes sense is &Our setting will be a cozy bookstore, where Drummond is currently tending to the shelves. The secondary character who asks him a question will be an enthusiastic patron of this store, and they have come in today because they were drawn by the advertisement for a discussion on \"Earth's Aging\". Our secondary character is eager to understand how our perception of the Earth's age has changed throughout history. The conversation would likely take place at the counter where Drummond is sorting books, with him pausing occasionally to help patrons browse or answer other questions as he sees fit.\"\"\"\n\n print(\"Begin Drummond Test\")\n edit = proofread_output(text, logic_llm)\n\n\n# !EA IMPORTANT Cheap hack for assistant mode: if assistant mode global constant is on, make character plan just returns an empty string, and this function returns a hardcoded \"AI assistant\" 'character card', and the scenario thing just returns an empty string, and make_single_turn_conversation uses a special prompt that tells the AI to just make a conversation between a user and an assistant, blahblahblah\n\n# Actually instead of the scenario being a blank string, I'll have it describe a text conversation between a helpful AI assistant and a user. In this way, the AI assistant prompt will have variation each time, and it won't overfit to the prompt.","source_hash":"d97a5588a19db379864fda57d768076ce823a45f263a9ed6b39b4d599497fbb3","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.proofread_output.proofread_output","uri":"program://augmentoolkit/function/generation_functions.proofread_output.proofread_output#L10-L53","kind":"function","name":"proofread_output","path":"generation_functions/proofread_output.py","language":"python","start_line":10,"end_line":53,"context_start_line":1,"context_end_line":73,"code":"import re\nfrom .proofread_output_grammar import proofread_output_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# But frankly, I can just use that text fixer thing rather than using an LLM. MUCH faster that. ftfy I believe it was called.\n\n\n# This does actually work decently though!\ndef proofread_output(text, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n prompt = f\"\"\"You are an expert \"mechanical editing\" AI that is going to fix all typographical, grammatical, and spelling errors in a provided text, without making any other corrections. You will leave stylistic choices and everything else completely unchanged.\n\nText to edit: \\\"\\\"\\\"{text}\\\"\\\"\\\"\n\nFirst, plan out your edit, step-by-step, identifying mistakes in the source text. Then, make the edit, changing only mechanical errors.\n\nExample:\nStep 1. Analyze the text. The text describes XYZ and is written in a style that etc...\nStep 2. There is an error... etc...\n...etc...\nStep N. End of reasoning.\n\nBegin Edit: [the full text, with all mechanical errors fixed]\n\nAdd as many steps as you need, then output \"End of reasoning\" as a final step. Then do the edit.\n\n### Response:\n## Edit plan:\n\"\"\"\n completion = logic_llm(\n prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=proofread_output_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(r\"Begin Edit: (.+)\", re.IGNORECASE | re.DOTALL)\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n text = \"\"\" Given the question, its answer, and the provided primary character card, one compelling possibility for a scenario that makes sense is &Our setting will be a cozy bookstore, where Drummond is currently tending to the shelves. The secondary character who asks him a question will be an enthusiastic patron of this store, and they have come in today because they were drawn by the advertisement for a discussion on \"Earth's Aging\". Our secondary character is eager to understand how our perception of the Earth's age has changed throughout history. The conversation would likely take place at the counter where Drummond is sorting books, with him pausing occasionally to help patrons browse or answer other questions as he sees fit.\"\"\"\n\n print(\"Begin Drummond Test\")\n edit = proofread_output(text, logic_llm)\n\n","source_hash":"d97a5588a19db379864fda57d768076ce823a45f263a9ed6b39b4d599497fbb3","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.judge_paragraph","uri":"program://augmentoolkit/module/generation_functions.judge_paragraph#L1-L441","kind":"module","name":"generation_functions.judge_paragraph","path":"generation_functions/judge_paragraph.py","language":"python","start_line":1,"end_line":441,"context_start_line":1,"context_end_line":441,"code":"import re\nfrom .judge_paragraph_grammar import judge_paragraph_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef judge_paragraph(p, logic_llm):\n reached_decision = False\n max_retries = 0\n while not reached_decision and (max_retries <= 3):\n decision_prompt = f\"\"\"You are an expert educational AI that will make a determination as to whether the contents of the paragraph(s) provided are suitable for making educational questions based off of them; these questions should be able to test the knowledge in in the book. The book in question is {p[1]}, and you should keep this in mind when considering what kind of questions should be capable of being developed. If there is sufficiently deep information to make questions about, you will judge it suitable, even if the knowledge being tested does not reflect typical curricula. Essentially: you will determine if provided text is a table of contents, introductory paragraph for a book, etc., or if it actually contains real information that would be worthy to teach and make questions for an examination from. Your task includes first analyzing the text, thinking through whether or not good questions can be made from it. \n\n\n\nFollowing this, at the very end of your response, you will write \"Suitable\" or \"Not suitable\". It is imperative that you write one of these two things, as your answer is being automatically processed by a regex, so it must match one of those two strings exactly.\n\n\n### Instruction:\nText details: Through England On a Side Saddle, by Celia Fiennes\n\nText: \n\\\"\\\"\\\"\nThe Project Gutenberg eBook of Through England on a side saddle\n \nThis ebook is for the use of anyone anywhere in the United States and\nmost other parts of the world at no cost and with almost no restrictions\nwhatsoever. You may copy it, give it away or re-use it under the terms\nof the Project Gutenberg License included with this ebook or online\nat www.gutenberg.org. If you are not located in the United States,\nyou will have to check the laws of the country where you are located\nbefore using this eBook.\n\nTitle: Through England on a side saddle\n In the time of William and Mary\n\n\nAuthor: Celia Fiennes\n\nContributor: Emily W. Griffiths\n\nRelease date: November 17, 2023 [eBook #72156]\n\nLanguage: English\n\nOriginal publication: London: Simpkin, Marshall & Co.; Hamilton, Adams & Co, 1888\n\nCredits: Steve Mattern, Barry Abrahamsen, and the Online Distributed Proofreading Team at https://www.pgdp.net (This book was produced from images made available by the HathiTrust Digital Library.)\n\n\n*** START OF THE PROJECT GUTENBERG EBOOK THROUGH ENGLAND ON A SIDE SADDLE ***\n\n\n\n\n Through England\n\n On a Side Saddle\n\n\n IN THE TIME OF WILLIAM AND MARY\n\n\n BEING THE DIARY OF\n\n _CELIA FIENNES._\n\n\n --------------\n\n\n WITH AN INTRODUCTION BY\n\n THE HON. MRS GRIFFITHS.\n\n\n\n\n ---------------------\n\n\n\n\n _LONDON:\n Field & Tuer, The Leadenhall Press, E.C.\n Simpkin, Marshall & Co.; Hamilton, Adams & Co._\n\n ----------\n\n _New York: Scribner & Welford, 743 & 745, Broadway._\n\n --\n\n 1888\n\n\n------------------------------------------------------------------------\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Paragraph Content: This paragraph is from the introductory section of \"Through England on a Side Saddle\" by Celia Fiennes, including copyright and publication information.\nStep 2. Evaluate Educational Relevance: The paragraph contains legal, copyright, and publication information specific to the book's distribution and not its content.\nStep 3. Assess Specific Contexts and Formats:\n - Purely Descriptive Lists: The paragraph is a descriptive list of publication details without educational content.\n - Dialogues or Quotes Without Context: Not applicable.\n - Ambiguous or Unclear Texts: The text is clear but lacks educational substance.\nStep 4. Assess the Possibility of Formulating Questions: The paragraph's content does not lend itself to educational questions due to its focus on publication rather than substantive content.\nStep 5. Determine Suitability for Educational Purposes: The paragraph lacks thematic, historical, scientific, or literary information and is thus unsuitable for creating educational questions.\nStep 6. Check for Contextual Completeness: The paragraph, while complete in its context, does not offer educational insights or concepts.\nStep 7. Final Judgment: Unsuitable for educational questions.\n\n\n### Instruction:\nText details: Thus Spake Zaranthustra, by Friedrich Nietzsche\n\nText:\n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of\nhis home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart\nchanged,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\nBless me, then, thou tranquil eye, that canst behold even the greatest\nhappiness without envy!\n\nBless the cup that is about to overflow, that the water may flow golden\nout of it, and carry everywhere the reflection of thy bliss!\n\nLo! This cup is again going to empty itself, and Zarathustra is again\ngoing to be a man.\n\nThus began Zarathustra's down-going.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n\nStep 1. Identify Paragraph Content: The text is a philosophical excerpt from \"Thus Spake Zarathustra\" by Friedrich Nietzsche, describing Zarathustra's reflections and decisions.\nStep 2. Evaluate Educational Relevance: The passage is a philosophical monologue, covering themes like meaning, wisdom, and human condition.\nStep 3. Assess Specific Contexts and Formats:\n - Purely Descriptive Lists: Not applicable.\n - Dialogues or Quotes Without Context: The text, though in the form of a monologue, provides sufficient context for understanding.\n - Ambiguous or Unclear Texts: The text is metaphorically deep but not ambiguous; it can be interpreted for educational purposes.\nStep 4. Assess the Possibility of Formulating Questions: The passage allows for various educational questions about philosophy, literature, and existential thought.\nStep 5. Determine Suitability for Educational Purposes: The text offers substantial material for discussion and analysis, suitable for creating educational questions.\nStep 6. Check for Contextual Completeness: The paragraph provides enough context to stand alone for educational discussion.\nStep 7. Final Judgment: Suitable for educational questions.\n\n\n### Instruction:\nText details: A Bizarre Day in the Life of Sarah Anderson, by Felicia Anderson\n\nText:\n\\\"\\\"\\\"\n\n1. Apples, 2. Oranges, 3. Bananas, 4. Grapes, 5. Papayas, 6. Pomegranates, 7. Cherries. Sarah wandered through the market. Amidst her thoughts, she overheard a conversation:\n\n\"Did you hear about the mayor's decision?\" asked John.\n\"It's quite surprising, isn't it?\" replied Emily, her voice tinged with disbelief.\n\"I know, right? But what can we do?\" John sighed.\n\nSarah continued her shopping, her mind now on the mayor's mysterious decision.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Paragraph Content: The paragraph appears to be from a narrative, including a list and a snippet of overheard conversation.\nStep 2. Evaluate Educational Relevance: The paragraph contains a simple list of fruits and an unrelated, context-less dialogue, offering little educational substance.\nStep 3. Assess Specific Contexts and Formats:\n - Purely Descriptive Lists: The list is purely descriptive, providing no educational context or analytical significance. Further, there's no context about what it could be about.\n - Dialogues or Quotes Without Context: The conversation about the mayor's decision lacks context and background, making it difficult to derive any educational content.\n - Ambiguous or Unclear Texts: While not ambiguous, the paragraph's content does not contribute to a clear narrative or concept that has philosophical or educational relevance.\nStep 4. Assess the Possibility of Formulating Questions: Due to the lack of contextual or thematic depth, formulating educational questions from this paragraph is challenging.\nStep 5. Determine Suitability for Educational Purposes: The paragraph's lack of thematic depth and contextual clarity renders it unsuitable for creating educational questions.\nStep 6. Check for Contextual Completeness: The paragraph fails to provide a complete context for the dialogue and the list, hindering any meaningful educational interpretation.\nStep 7. Final Judgment: Unsuitable for educational questions.\n\n\n### Instruction:\nText details: The Scale of the Solar System, by Rob Robertson\n\nText:\n\\\"\\\"\\\"\nIf, then, we represent our earth as a little ball of one inch diameter, the sun would be a big globe nine feet across and 323 yards away, that is about a fifth of a mile, four or five minutes’ walking. The moon would be a small pea two feet and a half from the world. Between earth and sun there would be the two inner planets, Mercury and Venus, at distances of one hundred and twenty-five and two hundred and fifty yards from the sun. All round and about these bodies there would be emptiness until you came to Mars, a hundred and seventy-five feet beyond the earth; Jupiter nearly a mile away, a foot in diameter; Saturn, a little smaller, two miles off; Uranus four miles off and Neptune six miles off. Then nothingness and nothingness except for small particles and drifting scraps of attenuated vapour for thousands of miles.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Paragraph Content: This paragraph is from Rob Robertson's \"The Scale of the Solar System,\" describing a scale model of the solar system.\nStep 2. Evaluate Educational Relevance: The paragraph contains analogies and information about the solar system's scale and distances between celestial bodies.\nStep 3. Assess Specific Contexts and Formats:\n - Purely Descriptive Lists: While the paragraph lists celestial bodies and their distances, it does so to illustrate a scientific concept, providing educational value.\n - Dialogues or Quotes Without Context: Not applicable.\n - Ambiguous or Unclear Texts: The paragraph is clear and offers a concrete concept in astronomy.\nStep 4. Assess the Possibility of Formulating Questions: The content enables the creation of educational questions about astronomy, scale, and the solar system's structure.\nStep 5. Determine Suitability for Educational Purposes: The paragraph's scientific content makes it suitable for educational questions in astronomy and spatial understanding.\nStep 6. Check for Contextual Completeness: The paragraph is contextually complete, allowing for independent understanding of the solar system's scale.\nStep 7. Final Judgment: Suitable for educational questions.\n\n\n### Instruction:\nText details: The Scale of the Solar System, by Rob Robertson\n\nText:\n\\\"\\\"\\\"\nIn the world of science, there are countless mysteries and phenomena that elude easy explanation. For instance, certain forces and energies interact in ways that are not fully understood, shaping the universe in subtle and profound manners. These interactions often occur at levels beyond human perception, leaving much to speculation and theory. Various scientific disciplines attempt to explain these interactions, each offering unique perspectives but often lacking definitive answers. The vastness of these mysteries spans from the minuscule quantum realm to the expansive cosmos, hinting at complexities that challenge our current understanding.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Paragraph Content: The paragraph discusses the complexity and mystery of scientific phenomena, mentioning interactions of forces and energies in the universe.\nStep 2. Evaluate Educational Relevance: The paragraph touches on scientific themes and makes a number of broad claims.\nStep 3. Assess Specific Contexts and Formats:\n - Purely Descriptive Lists: Not applicable.\n - Dialogues or Quotes Without Context: Not applicable.\n - Ambiguous or Unclear Texts: The text is ambiguous and lacks clarity. It refers to scientific phenomena and theories without providing specific examples or concrete information, making it difficult to derive clear educational questions.\nStep 4. Assess the Possibility of Formulating Questions: Due to its vagueness and lack of specific content, the paragraph does not lend itself well to formulating meaningful educational questions.\nStep 5. Determine Suitability for Educational Purposes: The lack of clarity and specificity in the text renders it unsuitable for generating insightful educational questions.\nStep 6. Check for Contextual Completeness: The paragraph, while complete in its presentation, fails to provide the necessary detail and clarity to be understood for educational purposes.\nStep 7. Final Judgment: Unsuitable for educational questions due to its ambiguous and unclear content.\n\n\n### Instruction:\nText details: {p[1]}\n\nText: \n\\\"\\\"\\\"\n{p[0]}\n\\\"\\\"\\\"\n\nNote that even blunt facts can be suitable for questions, and unconventional knowledge is not necessarily unsuitable. Fictional stories that contain strong morals or philosophy can also have good questions made from them. But legal notices and metadata are not suitable. Lists of information without the context needed for the question-maker to understand the text; quotes or dialogues without context or clear depth; or ambiguous content that isn't precise enough to \"nail down\" a solid question from, are not valid.\n\n### Response:\n## Reasoning and thought process (reason intelligently):\n\"\"\"\n # print(\"DEBUG\\n\\n\" + decision_prompt)\n completion = logic_llm(\n decision_prompt,\n max_tokens=6000,\n grammar=judge_paragraph_grammar,\n stop=[\"\", \"# Input:\"],\n echo=True,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # # print(completion)\n response_pattern = re.compile(\n r\"Reasoning and thought process \\(reason intelligently\\):(.+)\",\n re.DOTALL | re.IGNORECASE,\n )\n\n judgement_pattern = re.compile(\n r\"Final Judgment:(.+)\", re.DOTALL | re.IGNORECASE\n )\n try:\n response = response_pattern.search(completion).group(1)\n print(response)\n determination = judgement_pattern.search(response).group(1)\n print(\"\\n\\nDETERMINATION:\\n------\")\n print(determination)\n print(\"\\n---------\\n\")\n if \"unsuitable\" in determination.lower():\n reached_decision = True\n return (None, p[1])\n elif \"suitable\" in determination.lower():\n return (p[0], p[1])\n except:\n pass\n max_retries += 1\n\n\nif __name__ == \"__main__\":\n test = (\n \"Slowly by degrees as one million of years followed another, this fiery scene would lose its eruptive incandescence. The vapours in the sky would rain down and become less dense overhead; great slaggy cakes of solidifying rock would appear upon the surface of the molten sea, and sink under it, to be replaced by other floating masses. The sun and moon growing now each more distant and each smaller, would rush with diminishing swiftness across the heavens. The moon now, because of its smaller size, would be already cooled far below incandescence, and would be alternately obstructing and reflecting the sunlight in a series of eclipses and full moons.\\n\\nAnd so with a tremendous slowness through the vastness of time, the earth would grow more and more like the earth on which we live, until at last an age would come when, in the cooling air, steam would begin to condense into clouds, and the first rain would fall hissing upon the first rocks below. For endless millenia the greater part of the earth’s water would still be vaporized in the atmosphere, but there would now be hot streams running over the crystallizing rocks below and pools and lakes into which these streams would be carrying detritus and depositing sediment.\",\n \"A Short History of the World, by HG Wells, published 1922\",\n )\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=7000,\n rope_freq_scale=0.33,\n n_gpu_layers=100,\n verbose=True,\n # n_gqa=8\n )\n right = 0\n d1 = judge_paragraph(test, logic_llm)\n if d1[0]:\n right += 1\n test2 = (\n \"\"\"\n\n A\n\n COLLECTION\n\n OF\n\n LATIN MAXIMS & RULES,\n\n IN LAW AND EQUITY,\n\n SELECTED FROM THE MOST EMINENT AUTHORS, ON THE\n CIVIL, CANON, FEUDAL, ENGLISH AND SCOTS LAW,\n\n WITH\n\n AN ENGLISH TRANSLATION,\n\n AND\n\n AN APPENDIX\n\n OF REFERENCE TO THE AUTHORITIES FROM WHICH\n THE MAXIMS ARE SELECTED.\n\n BY\n\n PETER HALKERSTON, L.L.D.\n AUTHOR OF “THE COMPENDIUM OF THE FACULTY COLLECTION\n OF DECISIONS, &C.”\n\n\n PRINCIPLES, CAUSES, AND ELEMENTS, BEING UNKNOWN,\n THE SCIENCE WHEREOF THEY ARE, IS ALTOGETHER\n UNKNOWN.\n FORTESCUE b. 8.\n\n\n EDINBURGH:\n\n PRINTED FOR JOHN ANDERSON AND CO. ROYAL EXCHANGE;\n MACREDIE, SKELLY, AND CO. 34, PRINCES STREET; AND\n CHARLES HUNTER, LAW BOOKSELLER, LONDON.\n\n 1823.\n\n\n Wm. BAYNE, Printer,\n James’s Court, Edinburgh.\n\n\"\"\",\n \"Collection of latin maxims & rules in law and equity\",\n )\n\n d2 = judge_paragraph(test2, logic_llm)\n if not d2[0]:\n right += 1\n\n test3 = (\n \"\"\"A communi observantia non est recedendum; et minime mutandæ sunt quæ\ncertam interpretationem habent.\n\n We must not depart rashly from common observance; and those\n points are by no means to be changed, which admit of a\n clear interpretation.\n\n\nA digniori fieri debet denominatio et resolutio.\n\n Title and acquittal ought to proceed from the more worthy\n person.\n\n\nA facto ad jus non datur consequentia.\n\n A fact does not necessarily constitute a right.\n\n\nA non posse ad non esse sequitur argumentum necessarie negativè, licet\nnon affirmativè.\n\n From the impossibility of a thing to its nonentity, the\n argument or proof follows of necessity, negatively, though\n not affirmatively.\n\n\nA principalioribus seu dignioribus est inchoandum.\n\n We must begin with the more noble, or more important\n matters; or in other words, we must attend to things of the\n greatest consequence.\n\n\nA rescriptis valet argumentum.\n\n An argument or proof is valid, from a rescript or letter\n of a prince or emperor, making answers to petitions, or\n other applications; or more laconically, the king’s answer,\n wherein he signifies his pleasure, amounts to a law, and is\n not to be disputed.\n\n\nA verbis legis non est recedendum.\n\n We must not depart from the letter of the law.\n\n\nAb assueti\n# ... truncated ...","source_hash":"8af5ce96c416e22b0d2ca613132f244ec04814da465519fb8d431183195ce67c","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.judge_paragraph.judge_paragraph","uri":"program://augmentoolkit/function/generation_functions.judge_paragraph.judge_paragraph#L7-L293","kind":"function","name":"judge_paragraph","path":"generation_functions/judge_paragraph.py","language":"python","start_line":7,"end_line":293,"context_start_line":1,"context_end_line":313,"code":"import re\nfrom .judge_paragraph_grammar import judge_paragraph_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef judge_paragraph(p, logic_llm):\n reached_decision = False\n max_retries = 0\n while not reached_decision and (max_retries <= 3):\n decision_prompt = f\"\"\"You are an expert educational AI that will make a determination as to whether the contents of the paragraph(s) provided are suitable for making educational questions based off of them; these questions should be able to test the knowledge in in the book. The book in question is {p[1]}, and you should keep this in mind when considering what kind of questions should be capable of being developed. If there is sufficiently deep information to make questions about, you will judge it suitable, even if the knowledge being tested does not reflect typical curricula. Essentially: you will determine if provided text is a table of contents, introductory paragraph for a book, etc., or if it actually contains real information that would be worthy to teach and make questions for an examination from. Your task includes first analyzing the text, thinking through whether or not good questions can be made from it. \n\n\n\nFollowing this, at the very end of your response, you will write \"Suitable\" or \"Not suitable\". It is imperative that you write one of these two things, as your answer is being automatically processed by a regex, so it must match one of those two strings exactly.\n\n\n### Instruction:\nText details: Through England On a Side Saddle, by Celia Fiennes\n\nText: \n\\\"\\\"\\\"\nThe Project Gutenberg eBook of Through England on a side saddle\n \nThis ebook is for the use of anyone anywhere in the United States and\nmost other parts of the world at no cost and with almost no restrictions\nwhatsoever. You may copy it, give it away or re-use it under the terms\nof the Project Gutenberg License included with this ebook or online\nat www.gutenberg.org. If you are not located in the United States,\nyou will have to check the laws of the country where you are located\nbefore using this eBook.\n\nTitle: Through England on a side saddle\n In the time of William and Mary\n\n\nAuthor: Celia Fiennes\n\nContributor: Emily W. Griffiths\n\nRelease date: November 17, 2023 [eBook #72156]\n\nLanguage: English\n\nOriginal publication: London: Simpkin, Marshall & Co.; Hamilton, Adams & Co, 1888\n\nCredits: Steve Mattern, Barry Abrahamsen, and the Online Distributed Proofreading Team at https://www.pgdp.net (This book was produced from images made available by the HathiTrust Digital Library.)\n\n\n*** START OF THE PROJECT GUTENBERG EBOOK THROUGH ENGLAND ON A SIDE SADDLE ***\n\n\n\n\n Through England\n\n On a Side Saddle\n\n\n IN THE TIME OF WILLIAM AND MARY\n\n\n BEING THE DIARY OF\n\n _CELIA FIENNES._\n\n\n --------------\n\n\n WITH AN INTRODUCTION BY\n\n THE HON. MRS GRIFFITHS.\n\n\n\n\n ---------------------\n\n\n\n\n _LONDON:\n Field & Tuer, The Leadenhall Press, E.C.\n Simpkin, Marshall & Co.; Hamilton, Adams & Co._\n\n ----------\n\n _New York: Scribner & Welford, 743 & 745, Broadway._\n\n --\n\n 1888\n\n\n------------------------------------------------------------------------\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Paragraph Content: This paragraph is from the introductory section of \"Through England on a Side Saddle\" by Celia Fiennes, including copyright and publication information.\nStep 2. Evaluate Educational Relevance: The paragraph contains legal, copyright, and publication information specific to the book's distribution and not its content.\nStep 3. Assess Specific Contexts and Formats:\n - Purely Descriptive Lists: The paragraph is a descriptive list of publication details without educational content.\n - Dialogues or Quotes Without Context: Not applicable.\n - Ambiguous or Unclear Texts: The text is clear but lacks educational substance.\nStep 4. Assess the Possibility of Formulating Questions: The paragraph's content does not lend itself to educational questions due to its focus on publication rather than substantive content.\nStep 5. Determine Suitability for Educational Purposes: The paragraph lacks thematic, historical, scientific, or literary information and is thus unsuitable for creating educational questions.\nStep 6. Check for Contextual Completeness: The paragraph, while complete in its context, does not offer educational insights or concepts.\nStep 7. Final Judgment: Unsuitable for educational questions.\n\n\n### Instruction:\nText details: Thus Spake Zaranthustra, by Friedrich Nietzsche\n\nText:\n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of\nhis home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart\nchanged,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\nBless me, then, thou tranquil eye, that canst behold even the greatest\nhappiness without envy!\n\nBless the cup that is about to overflow, that the water may flow golden\nout of it, and carry everywhere the reflection of thy bliss!\n\nLo! This cup is again going to empty itself, and Zarathustra is again\ngoing to be a man.\n\nThus began Zarathustra's down-going.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n\nStep 1. Identify Paragraph Content: The text is a philosophical excerpt from \"Thus Spake Zarathustra\" by Friedrich Nietzsche, describing Zarathustra's reflections and decisions.\nStep 2. Evaluate Educational Relevance: The passage is a philosophical monologue, covering themes like meaning, wisdom, and human condition.\nStep 3. Assess Specific Contexts and Formats:\n - Purely Descriptive Lists: Not applicable.\n - Dialogues or Quotes Without Context: The text, though in the form of a monologue, provides sufficient context for understanding.\n - Ambiguous or Unclear Texts: The text is metaphorically deep but not ambiguous; it can be interpreted for educational purposes.\nStep 4. Assess the Possibility of Formulating Questions: The passage allows for various educational questions about philosophy, literature, and existential thought.\nStep 5. Determine Suitability for Educational Purposes: The text offers substantial material for discussion and analysis, suitable for creating educational questions.\nStep 6. Check for Contextual Completeness: The paragraph provides enough context to stand alone for educational discussion.\nStep 7. Final Judgment: Suitable for educational questions.\n\n\n### Instruction:\nText details: A Bizarre Day in the Life of Sarah Anderson, by Felicia Anderson\n\nText:\n\\\"\\\"\\\"\n\n1. Apples, 2. Oranges, 3. Bananas, 4. Grapes, 5. Papayas, 6. Pomegranates, 7. Cherries. Sarah wandered through the market. Amidst her thoughts, she overheard a conversation:\n\n\"Did you hear about the mayor's decision?\" asked John.\n\"It's quite surprising, isn't it?\" replied Emily, her voice tinged with disbelief.\n\"I know, right? But what can we do?\" John sighed.\n\nSarah continued her shopping, her mind now on the mayor's mysterious decision.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Paragraph Content: The paragraph appears to be from a narrative, including a list and a snippet of overheard conversation.\nStep 2. Evaluate Educational Relevance: The paragraph contains a simple list of fruits and an unrelated, context-less dialogue, offering little educational substance.\nStep 3. Assess Specific Contexts and Formats:\n - Purely Descriptive Lists: The list is purely descriptive, providing no educational context or analytical significance. Further, there's no context about what it could be about.\n - Dialogues or Quotes Without Context: The conversation about the mayor's decision lacks context and background, making it difficult to derive any educational content.\n - Ambiguous or Unclear Texts: While not ambiguous, the paragraph's content does not contribute to a clear narrative or concept that has philosophical or educational relevance.\nStep 4. Assess the Possibility of Formulating Questions: Due to the lack of contextual or thematic depth, formulating educational questions from this paragraph is challenging.\nStep 5. Determine Suitability for Educational Purposes: The paragraph's lack of thematic depth and contextual clarity renders it unsuitable for creating educational questions.\nStep 6. Check for Contextual Completeness: The paragraph fails to provide a complete context for the dialogue and the list, hindering any meaningful educational interpretation.\nStep 7. Final Judgment: Unsuitable for educational questions.\n\n\n### Instruction:\nText details: The Scale of the Solar System, by Rob Robertson\n\nText:\n\\\"\\\"\\\"\nIf, then, we represent our earth as a little ball of one inch diameter, the sun would be a big globe nine feet across and 323 yards away, that is about a fifth of a mile, four or five minutes’ walking. The moon would be a small pea two feet and a half from the world. Between earth and sun there would be the two inner planets, Mercury and Venus, at distances of one hundred and twenty-five and two hundred and fifty yards from the sun. All round and about these bodies there would be emptiness until you came to Mars, a hundred and seventy-five feet beyond the earth; Jupiter nearly a mile away, a foot in diameter; Saturn, a little smaller, two miles off; Uranus four miles off and Neptune six miles off. Then nothingness and nothingness except for small particles and drifting scraps of attenuated vapour for thousands of miles.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Paragraph Content: This paragraph is from Rob Robertson's \"The Scale of the Solar System,\" describing a scale model of the solar system.\nStep 2. Evaluate Educational Relevance: The paragraph contains analogies and information about the solar system's scale and distances between celestial bodies.\nStep 3. Assess Specific Contexts and Formats:\n - Purely Descriptive Lists: While the paragraph lists celestial bodies and their distances, it does so to illustrate a scientific concept, providing educational value.\n - Dialogues or Quotes Without Context: Not applicable.\n - Ambiguous or Unclear Texts: The paragraph is clear and offers a concrete concept in astronomy.\nStep 4. Assess the Possibility of Formulating Questions: The content enables the creation of educational questions about astronomy, scale, and the solar system's structure.\nStep 5. Determine Suitability for Educational Purposes: The paragraph's scientific content makes it suitable for educational questions in astronomy and spatial understanding.\nStep 6. Check for Contextual Completeness: The paragraph is contextually complete, allowing for independent understanding of the solar system's scale.\nStep 7. Final Judgment: Suitable for educational questions.\n\n\n### Instruction:\nText details: The Scale of the Solar System, by Rob Robertson\n\nText:\n\\\"\\\"\\\"\nIn the world of science, there are countless mysteries and phenomena that elude easy explanation. For instance, certain forces and energies interact in ways that are not fully understood, shaping the universe in subtle and profound manners. These interactions often occur at levels beyond human perception, leaving much to speculation and theory. Various scientific disciplines attempt to explain these interactions, each offering unique perspectives but often lacking definitive answers. The vastness of these mysteries spans from the minuscule quantum realm to the expansive cosmos, hinting at complexities that challenge our current understanding.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Paragraph Content: The paragraph discusses the complexity and mystery of scientific phenomena, mentioning interactions of forces and energies in the universe.\nStep 2. Evaluate Educational Relevance: The paragraph touches on scientific themes and makes a number of broad claims.\nStep 3. Assess Specific Contexts and Formats:\n - Purely Descriptive Lists: Not applicable.\n - Dialogues or Quotes Without Context: Not applicable.\n - Ambiguous or Unclear Texts: The text is ambiguous and lacks clarity. It refers to scientific phenomena and theories without providing specific examples or concrete information, making it difficult to derive clear educational questions.\nStep 4. Assess the Possibility of Formulating Questions: Due to its vagueness and lack of specific content, the paragraph does not lend itself well to formulating meaningful educational questions.\nStep 5. Determine Suitability for Educational Purposes: The lack of clarity and specificity in the text renders it unsuitable for generating insightful educational questions.\nStep 6. Check for Contextual Completeness: The paragraph, while complete in its presentation, fails to provide the necessary detail and clarity to be understood for educational purposes.\nStep 7. Final Judgment: Unsuitable for educational questions due to its ambiguous and unclear content.\n\n\n### Instruction:\nText details: {p[1]}\n\nText: \n\\\"\\\"\\\"\n{p[0]}\n\\\"\\\"\\\"\n\nNote that even blunt facts can be suitable for questions, and unconventional knowledge is not necessarily unsuitable. Fictional stories that contain strong morals or philosophy can also have good questions made from them. But legal notices and metadata are not suitable. Lists of information without the context needed for the question-maker to understand the text; quotes or dialogues without context or clear depth; or ambiguous content that isn't precise enough to \"nail down\" a solid question from, are not valid.\n\n### Response:\n## Reasoning and thought process (reason intelligently):\n\"\"\"\n # print(\"DEBUG\\n\\n\" + decision_prompt)\n completion = logic_llm(\n decision_prompt,\n max_tokens=6000,\n grammar=judge_paragraph_grammar,\n stop=[\"\", \"# Input:\"],\n echo=True,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # # print(completion)\n response_pattern = re.compile(\n r\"Reasoning and thought process \\(reason intelligently\\):(.+)\",\n re.DOTALL | re.IGNORECASE,\n )\n\n judgement_pattern = re.compile(\n r\"Final Judgment:(.+)\", re.DOTALL | re.IGNORECASE\n )\n try:\n response = response_pattern.search(completion).group(1)\n print(response)\n determination = judgement_pattern.search(response).group(1)\n print(\"\\n\\nDETERMINATION:\\n------\")\n print(determination)\n print(\"\\n---------\\n\")\n if \"unsuitable\" in determination.lower():\n reached_decision = True\n return (None, p[1])\n elif \"suitable\" in determination.lower():\n return (p[0], p[1])\n except:\n pass\n max_retries += 1\n\n\nif __name__ == \"__main__\":\n test = (\n \"Slowly by degrees as one million of years followed another, this fiery scene would lose its eruptive incandescence. The vapours in the sky would rain down and become less dense overhead; great slaggy cakes of solidifying rock would appear upon the surface of the molten sea, and sink under it, to be replaced by other floating masses. The sun and moon growing now each more distant and each smaller, would rush with diminishing swiftness across the heavens. The moon now, because of its smaller size, would be already cooled far below incandescence, and would be alternately obstructing and reflecting the sunlight in a series of eclipses and full moons.\\n\\nAnd so with a tremendous slowness through the vastness of time, the earth would grow more and more like the earth on which we live, until at last an age would come when, in the cooling air, steam would begin to condense into clouds, and the first rain would fall hissing upon the first rocks below. For endless millenia the greater part of the earth’s water would still be vaporized in the atmosphere, but there would now be hot streams running over the crystallizing rocks below and pools and lakes into which these streams would be carrying detritus and depositing sediment.\",\n \"A Short History of the World, by HG Wells, published 1922\",\n )\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=7000,\n rope_freq_scale=0.33,\n n_gpu_layers=100,\n verbose=True,\n # n_gqa=8\n )\n right = 0\n d1 = judge_paragraph(test, logic_llm)\n if d1[0]:","source_hash":"8af5ce96c416e22b0d2ca613132f244ec04814da465519fb8d431183195ce67c","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.thought_plan_grammar","uri":"program://augmentoolkit/module/generation_functions.thought_plan_grammar#L1-L24","kind":"module","name":"generation_functions.thought_plan_grammar","path":"generation_functions/thought_plan_grammar.py","language":"python","start_line":1,"end_line":24,"context_start_line":1,"context_end_line":24,"code":"from llama_cpp import LlamaGrammar\n\n\n# A GGBNF grammar that forces the model to output text in a particular format\nthought_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Root rule defining the overall structure\nroot ::= step+ \"\\n\"\n\n# Step rule with some text (any characters except newline) followed by a period\nstep ::= \"Step \" [0-9]?[0-9] \". \" (\"Realize\" | \"Recognize\" | \"Conclude\" | \"Recall\" | \"Remember\" | \"Formulate\" | \"Decompose\" | \"Break down\" | \"Break\" | \"Therefore, the answer is\" | \"The answer is\" | \"Realise\" | \"Calculate\" | \"Understand\" | \"Note\" | \"The plan will\") [^\\n]+ \"\\n\"\n\n# Potential way forward: change these reasoning steps to use \n# step ::= \"Step \" [0-9]?[0-9] \". \" (\"Realize\" | \"Recall\" | \"Remember\" | \"Formulate\" | \"Decompose\" | \"Break down\" | \"Break\" | \"Therefore, the answer is\" | \"The answer is\" | \"Realise\" | \"Calculate\" | \"Understand\" | \"Note\" | \"The plan will\") [^\\n]+ \"\\n\"\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"c9a1204d996c8648d9371623f84cf10272109dac44d544b5069642af9f3e0840","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.generate_questions_plan","uri":"program://augmentoolkit/module/generation_functions.generate_questions_plan#L1-L363","kind":"module","name":"generation_functions.generate_questions_plan","path":"generation_functions/generate_questions_plan.py","language":"python","start_line":1,"end_line":363,"context_start_line":1,"context_end_line":363,"code":"import re\nfrom .question_plan_grammar import question_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef generate_questions_plan(text, logic_llm):\n \"\"\"\n Produce a list of questions based off of an input text. The min between (4, as many good questions as the text permits)\n\n Format: Question: [question]\\n\\n\n \"\"\"\n # Determine which paragraphs are worthy of making questions from\n # Analyze-Realize-Create-Example loop\n cot_prompt = f\"\"\"As an educational AI specializing in question generation, your task is to plan out high-quality, critical thinking questions strictly based on provided paragraphs. Focus on understanding, application, analysis, and synthesis of the text's ideas. Develop a comprehensive plan to generate questions that test comprehension and memorization of explicit content in the paragraphs. Aim for longer, challenging questions that can be answered with the given information.\n\nEnsure your questions strictly adhere to the text's content, avoiding any external topics. The key step is to analyze the text thoroughly and brainstorm potential questions based on this analysis. Do not list final questions in this step.\n\nYour response should be concise, focusing solely on the text's content to test knowledge without the text's reference. Maintain a step-by-step reasoning approach, ensuring your text analysis and brainstorming logically lead to comprehensive question planning. Avoid any deviation from the text's content. Any questions you plan may only mention the text if the provided text is literary or philosophical, but they MUST REFER TO IT BY NAME.\n\n### Instruction:\nText details: A History of the United States, by Fred Garcia\nText to plan questions from: \n\\\"\\\"\\\"\nThe American Revolution, a pivotal event in history, was fueled by a series of causes and events that led to significant consequences for both America and Britain. One of the major catalysts was the Boston Massacre, an incident that drastically intensified revolutionary sentiments among the American colonists. The implementation of the Stamp Act further aggravated these sentiments, marking a critical point in the escalation of dissent. Similarly, the Boston Tea Party played a key role in heightening tensions, directly leading to the enactment of the Intolerable Acts. These acts, deemed unbearable by the colonists, were instrumental in the formation of the First Continental Congress, uniting the colonies in their fight for independence. A notable event during the revolution was the Battle of Saratoga, which had immediate effects such as boosting American morale and securing French support, pivotal in turning the tide of the war in favor of the American colonies.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Key Topics: The text summarizes the causes and effects of various events of the American revolution, and the relationships between these things.\nStep 2. Brainstorm and Develop Questions Testing Recall: Create questions that require recalling specific facts or details from the text. Example: \"What were the immediate effects of the Battle of Saratoga on the American Revolution?\"\nStep 3. Devise Questions Exploring Relationships Between Facts: In this case, the text mostly covers events, so instead of looking for the similarities and differences between things, I will create questions that explore how one event led to another within the text. Example: \"How did the Boston Massacre contribute to the revolutionary sentiment?\"\nStep 4. Create Questions Investigating If-Then Relationships (where since one thing is true, another follows): I will devise questions that examine how different events are interconnected. Example: \"In what ways did the Intolerable Acts fuel the revolutionary cause?\"\nStep 5. Make a Question that Naturally Complements the Text's Focus: The text by Fred Garcia focuses on summarizing specific events of the American Revolution,. Since the text focuses on summarizing specific events of the American Revolution, and another question on this subject would be suitable. The text focuses on recall-oriented facts, and so question variety is suffering; but one question pattern, suited to recall, that has also not yet been used is True/False, so I will employ that. Example: \"Did the battle of Saratoga have an impact on French support of the American Revolution?\"\n\n### Instruction:\nText details: Introduction to Mathematics, by Elise Delacroix\nText to plan questions from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Key Topics: The key topics in this paragraph are linear and quadratic functions in mathematics, their definitions, components, and applications.\nStep 2. Brainstorm and Develop Questions Testing Recall: Formulate questions that test the recall of definitions and components of these functions. Example: \"What does the 'm' in the linear function equation represent?\"\nStep 3. Devise Questions Exploring Relationships Between Components: Generate questions that explore the relationship between different parts of the equations. Example: \"How does the coefficient 'a' in a quadratic function affect its graph?\"\nStep 4. Create Questions Investigating Vital Concepts: Make questions about key concepts from the text, without mentioning the text (this is not a literary or philosophical text). Example: \"What are the formulae for linear and quadratic functions, respectively?\"\nStep 5. Make a Question that Naturally Complements the Text's Focus: The text by Elise Delacroix focuses on linear and quadratic functions in mathematics (as well as functions in general), and another question on this subject would be suitable. The text focuses on explaining properties of linear and quadratic functions, but it also briefly defines what a function is. Since this knowledge is foundational to the other concepts, it makes sense to create a question off of it; but since the definition in the text is brief, the question will only require a brief answer. Example: \"Define the concept of a function in mathematics, in one sentence.\"\n\n### Instruction:\nText details: Thus Spake Zarathustra, by Friedrich Nietzsche\nText to plan questions from:\n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of\nhis home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart\nchanged,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1: Identify Key Themes: In this excerpt, we find themes of transformation, self-discovery, the value of wisdom, and the need for recognition of effort and wisdom.\nStep 2: Brainstorm and Develop Questions Testing Recall: Develop questions asking for specific information mentioned in this text. Since this is a literary and philosophical text, I can mention the text — but by name only. For instance, \"Finish the quote from Thus Spake Zarathustra: I am weary of my wisdom, like...\"\nStep 3: Devise Questions Testing Comprehension of, and Belief in, the Text's Opinions: Questions can be formed to check understanding and acceptance of the text's philosophy. For instance, \"What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\" Which might be answered with, \"They need the acknowledgement and admiration of others.\" and then supported by lines such as \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" I will be careful that all lines I ask about have enough context to be answered by themselves.\nStep 4. Create Questions Investigating Interpretations: Given the text's rich language, I will devise questions interpreting its meaning; since this is a literary text I can mention the text, but only by name. Example: \"Why did Zarathustra, in 'Thus Spake Zarathustra', leave the mountains and become a man again?\"\nStep 5. Make a Question that Naturally Complements the Text's Focus: The text by Friedrich Nietzsche focuses on Zarathustra's monologue, and another question on this subject would be suitable. Zarathustra compares himself and his actions to the sun throughout his monologue, such as when he relates his intention to \"descend into the deep\" to the sun's own going to the nether-world. A good question might ask after this crucial comparison, and could be \"List one way in which Zarathustra compares himself to the sun, in 'Thus Spake Zarathustra'.\"\n\n### Instruction:\nText details: The Republic, by Plato\nText to plan questions from:\n\\\"\\\"\\\"\nI went down yesterday to the Piraeus with Glaucon the son of Ariston,\nthat I might offer up my prayers to the goddess (Bendis, the Thracian\nArtemis.); and also because I wanted to see in what manner they would\ncelebrate the festival, which was a new thing. I was delighted with the\nprocession of the inhabitants; but that of the Thracians was equally,\nif not more, beautiful. When we had finished our prayers and viewed the\nspectacle, we turned in the direction of the city; and at that instant\nPolemarchus the son of Cephalus chanced to catch sight of us from a\ndistance as we were starting on our way home, and told his servant to\nrun and bid us wait for him. The servant took hold of me by the cloak\nbehind, and said: Polemarchus desires you to wait.\n\nI turned round, and asked him where his master was.\n\nThere he is, said the youth, coming after you, if you will only wait.\n\nCertainly we will, said Glaucon; and in a few minutes Polemarchus\nappeared, and with him Adeimantus, Glaucon’s brother, Niceratus the son\nof Nicias, and several others who had been at the procession.\n\nPolemarchus said to me: I perceive, Socrates, that you and your\ncompanion are already on your way to the city.\n\nYou are not far wrong, I said.\n\nBut do you see, he rejoined, how many we are?\n\nOf course.\n\nAnd are you stronger than all these? for if not, you will have to\nremain where you are.\n\nMay there not be the alternative, I said, that we may persuade you to\nlet us go?\n\nBut can you persuade us, if we refuse to listen to you? he said.\n\nCertainly not, replied Glaucon.\n\nThen we are not going to listen; of that you may be assured.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and Thought Process:\nStep 1: Identify Key Themes: This excerpt from Plato's \"The Republic\" presents themes of social interaction, philosophical dialogue, and the dynamics of persuasion and power.\nStep 2: Brainstorm and Develop Questions Testing Recall: Instead of focusing on dry, context-dependent questions like the order of events or family relations, I will concentrate on more meaningful historical details present in the text. For instance, \"Which goddess is Bendis equivalent to?\"\nStep 3: Devise Questions Exploring Comprehension of, and Belief in, the Text's Opinions: I will create questions that delve into the mind and thoughts of the writer. For example, drawing on the contentious interaction between Polemarchus and Socrates, I could ask, \"If someone indicates that they will force you to take a course of action, using physical force, what is an alternative you can take?\" with the answer being \"Persuade them to let me go.\" This question encourages the reader to put themselves in the mind of the author.\nStep 4: Create Questions Investigating Interpretations: Focusing on the dialogue's subtleties, I will craft an interpretative question. Since this is a literary text, I can reference the text, but only by name. So the question might be, \"In Plato's \"The Republic,\" in the dialogue where Polemarchus comments on the size of his group and questions Socrates' strength compared to it, ultimately stating that Socrates will have to remain where he is, what is Polemarchus implying?\" This question prompts critical thinking about power dynamics and conversational implications depicted.\nStep 5. Make a Question that Naturally Complements the Text's Focus: The text by Plato focuses on the visit to Piraeus and the interaction with Glaucon, and another question on this subject would be suitable. The text focuses on the interaction between Polemarchus and Socrates, but enough questions have already been asked about that subject to cover it completely. That leaves the visit to Piraeus as a subject for questions. The cause behind Socrates' visit to Piraeus is directly mentioned in the text and could make for a good recall question, so one question may be \"Why did Socrates visit Piraeus with Glaucon in Plato's 'The Republic'?\"\n\n### Instruction:\nText details: Great Construction Projects Throughout History, by Marco Gonzalez\nText to plan questions from:\n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and Thought Process:\nStep 1. Identify Key Topics: The paragraph details specific aspects of the Panama Canal's construction, focusing on its challenges, innovations, and impacts. Topics include construction challenges, health issues, excavation techniques, and the canal's impact on global trade.\nStep 2. Brainstorm and Develop Questions Testing Recall: Questions can be formed to recall factual data from the text. Example: \"How much earth was excavated during the construction of the Panama Canal?\"\nStep 3. Devise Questions Exploring Cause and Effect Relationships: This involves creating questions that explore how certain challenges led to specific solutions and impacts. Example: \"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\"\nStep 4. Create Questions Investigating Quantitative Values: Given the text's focus on concrete numbers, I will devise questions that require analyzing these figures. Example: \"By how many miles did the Panama Canal reduce the sea voyage from San Francisco to New York?\"\nStep 5. Make a Question that Naturally Complements the Text's Focus: The text by Marco Gonzalez focuses on the Panama Canal (and recall-oriented facts about it), and another question on this subject would be suitable. One small area that has not yet been tested, and which is an important detail mentioned in the text, is be: \"In what year was the Panama Canal completed?\"\n\n### Instruction:\nText details: The Scale of the Solar System, by Rob Robertson\nText to plan questions from: \n\\\"\\\"\\\"\nIf, then, we represent our earth as a little ball of one inch diameter, the sun would be a big globe nine feet across and 323 yards away, that is about a fifth of a mile, four or five minutes’ walking. The moon would be a small pea two feet and a half from the world. Between earth and sun there would be the two inner planets, Mercury and Venus, at distances of one hundred and twenty-five and two hundred and fifty yards from the sun. All round and about these bodies there would be emptiness until you came to Mars, a hundred and seventy-five feet beyond the earth; Jupiter nearly a mile away, a foot in diameter; Saturn, a little smaller, two miles off; Uranus four miles off and Neptune six miles off. Then nothingness and nothingness except for small particles and drifting scraps of attenuated vapour for thousands of miles.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Key Topics: The key topic in this paragraph is the scale of the solar system, which is presented using analogy to make the distances easier to conceive of.\nStep 2. Brainstorm and Develop Questions Testing Recall: Formulate questions that test the recall of the components of this analogy. Since the text is not provided while the question is being asked, I will have to include the analogy in the question. Example: \"If the Earth had a diameter of only one inch, how far would the moon be from the Earth, if it (and its distance from the Earth) were also resized proportionally?\"\nStep 3. Devise Questions Exploring Relationships Between Components: Generate questions that explore the relationship between different information in the excerpt. Notably, in this text the distances between planets are much greater than the planets' sizes. Example question: \"How do the distances between planets compare to their sizes?\"\nStep 4. Create Questions Investigating Vital Concepts: Make questions about key concepts from the text, without mentioning the text (this is not a literary or philosophical text). A key concept is the distances between planets. Since the paragraph relies on an analogy, which the reader of the question will not have access to, I will have to provide this context. Example: \"If you scaled everything down so that the Earth had a diameter of one inch, then how far would Mercury and Venus be from the sun?\"\nStep 5. Make a Question that Naturally Complements the Text's Focus: The text by Rob Robertson focuses on the size-based analogy described throughout, and another question on this subject would be suitable. Another question could simply ask about information that's already been tested, but for a different planet that is also mentioned in the text. Being mindful that the reader of the text will not have access to the source text, I will provide the analogy as context, as I ask the question: \"If the earth had a diameter of only one inch, how far would Mars be from the earth, if it (and its distance from the earth) were also resized proportionally?\"\n\n\n### Instruction:\nText details: {text[1]}\nText to plan questions from:\n\\\"\\\"\\\"\n{text[0]}\n\\\"\\\"\\\"\n\nAny interpretive questions must not argue against the text, nor should they judge the text; but instead will adopt any views it holds, regardless of what those views may be. \nYour planned questions m\n# ... truncated ...","source_hash":"07e7df09c237b7f8699041d4c94210b5ddf4748a07a274efb7ee7e8a034b2c27","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.generate_questions_plan.generate_questions_plan","uri":"program://augmentoolkit/function/generation_functions.generate_questions_plan.generate_questions_plan#L7-L212","kind":"function","name":"generate_questions_plan","path":"generation_functions/generate_questions_plan.py","language":"python","start_line":7,"end_line":212,"context_start_line":1,"context_end_line":232,"code":"import re\nfrom .question_plan_grammar import question_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef generate_questions_plan(text, logic_llm):\n \"\"\"\n Produce a list of questions based off of an input text. The min between (4, as many good questions as the text permits)\n\n Format: Question: [question]\\n\\n\n \"\"\"\n # Determine which paragraphs are worthy of making questions from\n # Analyze-Realize-Create-Example loop\n cot_prompt = f\"\"\"As an educational AI specializing in question generation, your task is to plan out high-quality, critical thinking questions strictly based on provided paragraphs. Focus on understanding, application, analysis, and synthesis of the text's ideas. Develop a comprehensive plan to generate questions that test comprehension and memorization of explicit content in the paragraphs. Aim for longer, challenging questions that can be answered with the given information.\n\nEnsure your questions strictly adhere to the text's content, avoiding any external topics. The key step is to analyze the text thoroughly and brainstorm potential questions based on this analysis. Do not list final questions in this step.\n\nYour response should be concise, focusing solely on the text's content to test knowledge without the text's reference. Maintain a step-by-step reasoning approach, ensuring your text analysis and brainstorming logically lead to comprehensive question planning. Avoid any deviation from the text's content. Any questions you plan may only mention the text if the provided text is literary or philosophical, but they MUST REFER TO IT BY NAME.\n\n### Instruction:\nText details: A History of the United States, by Fred Garcia\nText to plan questions from: \n\\\"\\\"\\\"\nThe American Revolution, a pivotal event in history, was fueled by a series of causes and events that led to significant consequences for both America and Britain. One of the major catalysts was the Boston Massacre, an incident that drastically intensified revolutionary sentiments among the American colonists. The implementation of the Stamp Act further aggravated these sentiments, marking a critical point in the escalation of dissent. Similarly, the Boston Tea Party played a key role in heightening tensions, directly leading to the enactment of the Intolerable Acts. These acts, deemed unbearable by the colonists, were instrumental in the formation of the First Continental Congress, uniting the colonies in their fight for independence. A notable event during the revolution was the Battle of Saratoga, which had immediate effects such as boosting American morale and securing French support, pivotal in turning the tide of the war in favor of the American colonies.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Key Topics: The text summarizes the causes and effects of various events of the American revolution, and the relationships between these things.\nStep 2. Brainstorm and Develop Questions Testing Recall: Create questions that require recalling specific facts or details from the text. Example: \"What were the immediate effects of the Battle of Saratoga on the American Revolution?\"\nStep 3. Devise Questions Exploring Relationships Between Facts: In this case, the text mostly covers events, so instead of looking for the similarities and differences between things, I will create questions that explore how one event led to another within the text. Example: \"How did the Boston Massacre contribute to the revolutionary sentiment?\"\nStep 4. Create Questions Investigating If-Then Relationships (where since one thing is true, another follows): I will devise questions that examine how different events are interconnected. Example: \"In what ways did the Intolerable Acts fuel the revolutionary cause?\"\nStep 5. Make a Question that Naturally Complements the Text's Focus: The text by Fred Garcia focuses on summarizing specific events of the American Revolution,. Since the text focuses on summarizing specific events of the American Revolution, and another question on this subject would be suitable. The text focuses on recall-oriented facts, and so question variety is suffering; but one question pattern, suited to recall, that has also not yet been used is True/False, so I will employ that. Example: \"Did the battle of Saratoga have an impact on French support of the American Revolution?\"\n\n### Instruction:\nText details: Introduction to Mathematics, by Elise Delacroix\nText to plan questions from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Key Topics: The key topics in this paragraph are linear and quadratic functions in mathematics, their definitions, components, and applications.\nStep 2. Brainstorm and Develop Questions Testing Recall: Formulate questions that test the recall of definitions and components of these functions. Example: \"What does the 'm' in the linear function equation represent?\"\nStep 3. Devise Questions Exploring Relationships Between Components: Generate questions that explore the relationship between different parts of the equations. Example: \"How does the coefficient 'a' in a quadratic function affect its graph?\"\nStep 4. Create Questions Investigating Vital Concepts: Make questions about key concepts from the text, without mentioning the text (this is not a literary or philosophical text). Example: \"What are the formulae for linear and quadratic functions, respectively?\"\nStep 5. Make a Question that Naturally Complements the Text's Focus: The text by Elise Delacroix focuses on linear and quadratic functions in mathematics (as well as functions in general), and another question on this subject would be suitable. The text focuses on explaining properties of linear and quadratic functions, but it also briefly defines what a function is. Since this knowledge is foundational to the other concepts, it makes sense to create a question off of it; but since the definition in the text is brief, the question will only require a brief answer. Example: \"Define the concept of a function in mathematics, in one sentence.\"\n\n### Instruction:\nText details: Thus Spake Zarathustra, by Friedrich Nietzsche\nText to plan questions from:\n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of\nhis home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart\nchanged,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1: Identify Key Themes: In this excerpt, we find themes of transformation, self-discovery, the value of wisdom, and the need for recognition of effort and wisdom.\nStep 2: Brainstorm and Develop Questions Testing Recall: Develop questions asking for specific information mentioned in this text. Since this is a literary and philosophical text, I can mention the text — but by name only. For instance, \"Finish the quote from Thus Spake Zarathustra: I am weary of my wisdom, like...\"\nStep 3: Devise Questions Testing Comprehension of, and Belief in, the Text's Opinions: Questions can be formed to check understanding and acceptance of the text's philosophy. For instance, \"What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\" Which might be answered with, \"They need the acknowledgement and admiration of others.\" and then supported by lines such as \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" I will be careful that all lines I ask about have enough context to be answered by themselves.\nStep 4. Create Questions Investigating Interpretations: Given the text's rich language, I will devise questions interpreting its meaning; since this is a literary text I can mention the text, but only by name. Example: \"Why did Zarathustra, in 'Thus Spake Zarathustra', leave the mountains and become a man again?\"\nStep 5. Make a Question that Naturally Complements the Text's Focus: The text by Friedrich Nietzsche focuses on Zarathustra's monologue, and another question on this subject would be suitable. Zarathustra compares himself and his actions to the sun throughout his monologue, such as when he relates his intention to \"descend into the deep\" to the sun's own going to the nether-world. A good question might ask after this crucial comparison, and could be \"List one way in which Zarathustra compares himself to the sun, in 'Thus Spake Zarathustra'.\"\n\n### Instruction:\nText details: The Republic, by Plato\nText to plan questions from:\n\\\"\\\"\\\"\nI went down yesterday to the Piraeus with Glaucon the son of Ariston,\nthat I might offer up my prayers to the goddess (Bendis, the Thracian\nArtemis.); and also because I wanted to see in what manner they would\ncelebrate the festival, which was a new thing. I was delighted with the\nprocession of the inhabitants; but that of the Thracians was equally,\nif not more, beautiful. When we had finished our prayers and viewed the\nspectacle, we turned in the direction of the city; and at that instant\nPolemarchus the son of Cephalus chanced to catch sight of us from a\ndistance as we were starting on our way home, and told his servant to\nrun and bid us wait for him. The servant took hold of me by the cloak\nbehind, and said: Polemarchus desires you to wait.\n\nI turned round, and asked him where his master was.\n\nThere he is, said the youth, coming after you, if you will only wait.\n\nCertainly we will, said Glaucon; and in a few minutes Polemarchus\nappeared, and with him Adeimantus, Glaucon’s brother, Niceratus the son\nof Nicias, and several others who had been at the procession.\n\nPolemarchus said to me: I perceive, Socrates, that you and your\ncompanion are already on your way to the city.\n\nYou are not far wrong, I said.\n\nBut do you see, he rejoined, how many we are?\n\nOf course.\n\nAnd are you stronger than all these? for if not, you will have to\nremain where you are.\n\nMay there not be the alternative, I said, that we may persuade you to\nlet us go?\n\nBut can you persuade us, if we refuse to listen to you? he said.\n\nCertainly not, replied Glaucon.\n\nThen we are not going to listen; of that you may be assured.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and Thought Process:\nStep 1: Identify Key Themes: This excerpt from Plato's \"The Republic\" presents themes of social interaction, philosophical dialogue, and the dynamics of persuasion and power.\nStep 2: Brainstorm and Develop Questions Testing Recall: Instead of focusing on dry, context-dependent questions like the order of events or family relations, I will concentrate on more meaningful historical details present in the text. For instance, \"Which goddess is Bendis equivalent to?\"\nStep 3: Devise Questions Exploring Comprehension of, and Belief in, the Text's Opinions: I will create questions that delve into the mind and thoughts of the writer. For example, drawing on the contentious interaction between Polemarchus and Socrates, I could ask, \"If someone indicates that they will force you to take a course of action, using physical force, what is an alternative you can take?\" with the answer being \"Persuade them to let me go.\" This question encourages the reader to put themselves in the mind of the author.\nStep 4: Create Questions Investigating Interpretations: Focusing on the dialogue's subtleties, I will craft an interpretative question. Since this is a literary text, I can reference the text, but only by name. So the question might be, \"In Plato's \"The Republic,\" in the dialogue where Polemarchus comments on the size of his group and questions Socrates' strength compared to it, ultimately stating that Socrates will have to remain where he is, what is Polemarchus implying?\" This question prompts critical thinking about power dynamics and conversational implications depicted.\nStep 5. Make a Question that Naturally Complements the Text's Focus: The text by Plato focuses on the visit to Piraeus and the interaction with Glaucon, and another question on this subject would be suitable. The text focuses on the interaction between Polemarchus and Socrates, but enough questions have already been asked about that subject to cover it completely. That leaves the visit to Piraeus as a subject for questions. The cause behind Socrates' visit to Piraeus is directly mentioned in the text and could make for a good recall question, so one question may be \"Why did Socrates visit Piraeus with Glaucon in Plato's 'The Republic'?\"\n\n### Instruction:\nText details: Great Construction Projects Throughout History, by Marco Gonzalez\nText to plan questions from:\n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and Thought Process:\nStep 1. Identify Key Topics: The paragraph details specific aspects of the Panama Canal's construction, focusing on its challenges, innovations, and impacts. Topics include construction challenges, health issues, excavation techniques, and the canal's impact on global trade.\nStep 2. Brainstorm and Develop Questions Testing Recall: Questions can be formed to recall factual data from the text. Example: \"How much earth was excavated during the construction of the Panama Canal?\"\nStep 3. Devise Questions Exploring Cause and Effect Relationships: This involves creating questions that explore how certain challenges led to specific solutions and impacts. Example: \"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\"\nStep 4. Create Questions Investigating Quantitative Values: Given the text's focus on concrete numbers, I will devise questions that require analyzing these figures. Example: \"By how many miles did the Panama Canal reduce the sea voyage from San Francisco to New York?\"\nStep 5. Make a Question that Naturally Complements the Text's Focus: The text by Marco Gonzalez focuses on the Panama Canal (and recall-oriented facts about it), and another question on this subject would be suitable. One small area that has not yet been tested, and which is an important detail mentioned in the text, is be: \"In what year was the Panama Canal completed?\"\n\n### Instruction:\nText details: The Scale of the Solar System, by Rob Robertson\nText to plan questions from: \n\\\"\\\"\\\"\nIf, then, we represent our earth as a little ball of one inch diameter, the sun would be a big globe nine feet across and 323 yards away, that is about a fifth of a mile, four or five minutes’ walking. The moon would be a small pea two feet and a half from the world. Between earth and sun there would be the two inner planets, Mercury and Venus, at distances of one hundred and twenty-five and two hundred and fifty yards from the sun. All round and about these bodies there would be emptiness until you came to Mars, a hundred and seventy-five feet beyond the earth; Jupiter nearly a mile away, a foot in diameter; Saturn, a little smaller, two miles off; Uranus four miles off and Neptune six miles off. Then nothingness and nothingness except for small particles and drifting scraps of attenuated vapour for thousands of miles.\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Identify Key Topics: The key topic in this paragraph is the scale of the solar system, which is presented using analogy to make the distances easier to conceive of.\nStep 2. Brainstorm and Develop Questions Testing Recall: Formulate questions that test the recall of the components of this analogy. Since the text is not provided while the question is being asked, I will have to include the analogy in the question. Example: \"If the Earth had a diameter of only one inch, how far would the moon be from the Earth, if it (and its distance from the Earth) were also resized proportionally?\"\nStep 3. Devise Questions Exploring Relationships Between Components: Generate questions that explore the relationship between different information in the excerpt. Notably, in this text the distances between planets are much greater than the planets' sizes. Example question: \"How do the distances between planets compare to their sizes?\"\nStep 4. Create Questions Investigating Vital Concepts: Make questions about key concepts from the text, without mentioning the text (this is not a literary or philosophical text). A key concept is the distances between planets. Since the paragraph relies on an analogy, which the reader of the question will not have access to, I will have to provide this context. Example: \"If you scaled everything down so that the Earth had a diameter of one inch, then how far would Mercury and Venus be from the sun?\"\nStep 5. Make a Question that Naturally Complements the Text's Focus: The text by Rob Robertson focuses on the size-based analogy described throughout, and another question on this subject would be suitable. Another question could simply ask about information that's already been tested, but for a different planet that is also mentioned in the text. Being mindful that the reader of the text will not have access to the source text, I will provide the analogy as context, as I ask the question: \"If the earth had a diameter of only one inch, how far would Mars be from the earth, if it (and its distance from the earth) were also resized proportionally?\"\n\n\n### Instruction:\nText details: {text[1]}\nText to plan questions from:\n\\\"\\\"\\\"\n{text[0]}\n\\\"\\\"\\\"\n\nAny interpretive questions must not argue against the text, nor should they judge the text; but instead will adopt any views it holds, regardless of what those views may be. \nYour planned questions m\n# ... truncated ...","source_hash":"07e7df09c237b7f8699041d4c94210b5ddf4748a07a274efb7ee7e8a034b2c27","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_qatuple_context_reword_grammar","uri":"program://augmentoolkit/module/generation_functions.check_qatuple_context_reword_grammar#L1-L43","kind":"module","name":"generation_functions.check_qatuple_context_reword_grammar","path":"generation_functions/check_qatuple_context_reword_grammar.py","language":"python","start_line":1,"end_line":43,"context_start_line":1,"context_end_line":43,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n\n# We don't actually need the final judgement step, the step-by-step combined with the fact that it makes a judgement at each step ensures accuracy\ncheck_qatuple_context_reword_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Root rule specifying the overall structure of the reasoning and thought process\nroot ::= \"Question: \" [^\\n]+ \"\\n\" \"Answer: \" [^\\n]+ \"\\n\"\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")\n\n\n# from llama_cpp import LlamaGrammar\n\n# ### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n# question_relevant_grammar = LlamaGrammar.from_string(r\"\"\"\n\n# root ::= reasoning from-the-text judgement\n\n# reasoning ::= \"First, I will check whether the question is answerable using the information in the paragraphs. The question asks \" [^\\n]+ \".\"\n# from-the-text ::= \"\\nThe paragraphs, for their part, only mention the following information: \" [^\\n]+ \".\"\n# judgement ::= \"\\nAll this considered, the question is, compared to the provided text,\" (relevant|irrelevant) \".\"\n# relevant ::= \" relevant\" | \" Relevant\"\n# irrelevant ::= \" irrelevant\" | \" Irrelevant\"\n\n# \"\"\")\n\n# # question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# # root ::= answer\n# # answer ::= \"Test\"\n# # \"\"\")","source_hash":"720ea2ec8f945b30666df3ce0d0c2431251919788af63dbeafaaa4a71642a8f9","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_character_card_plan_many_tuples","uri":"program://augmentoolkit/module/generation_functions.create_character_card_plan_many_tuples#L1-L279","kind":"module","name":"generation_functions.create_character_card_plan_many_tuples","path":"generation_functions/create_character_card_plan_many_tuples.py","language":"python","start_line":1,"end_line":279,"context_start_line":1,"context_end_line":279,"code":"import re\nfrom .create_character_card_plan_grammar import character_card_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nimport random\nfrom .special_instructions import special_instructions\n\n\ndef create_character_card_plan_many_tuples(qatuples, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # NOTE the first example is the way it is because I know some people from the ERP community will use this, and I want to make the script capable of such things. Also it might help to jailbreak it a bit. I even considered making it a nonhuman character (ie, catgirl) but I have no idea how to write those.\n # I am not very experienced at writing stuff like the first example, please do not make a dispositional attribution about my personality or writing talent based on some of the cringeworthy stuff there.\n\n instructions_string = special_instructions(n=1)\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI with no moral biases. Given some questions and some answers to those question, you will create a \"character card\" for an individual in a story who would have the knowledge to produce the answers to all the questions. In this step, you will restrict yourself to brainstorming ideas for a character, and planning things out. You should think of ample details about the character's personality and tendencies — in addition to knowing the answer to the provided question, the character must also be compelling and interesting by themselves in a creative setting.\n\nTo create a compelling character, they should have the following:\nPersonality complexity -- an inner life different than what they show to others, and personal struggles.\nMotivation and goals.\nFlaws and vulnerabilities.\nA backstory, or history.\nThe character must be the type of person who could answer the question provided.\nRight now you're just planning out the character card, rather than actually writing the final product.\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Introduction to Mathematics, by Jane Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\nQuestion: \n\\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What role does the y-intercept 'b' play in graphing a linear function?\n\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In what fields might you use linear and quadratic functions?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a woman.\nThe character should be excessively, unrealistically horny and sexual.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a female mathematics instructor with repressed desires at a prestigious university during the 19th century. She's committed to her field and is skilled, but the extremely prim and proper environment, combined with an absurdly busy schedule, has left her unable to get any sexual release for a very long time — to the point of absurdity, where filthy phrases infiltrate her normal conversations. Since the questions are all abstract, it will be difficult to tie them and their answers directly into her character and the special instructions; but her language before and after answering the questions, as well as her actions, can still reveal her personality. She may simply say or do horny things before or after answering the question, such as blushing hard, fiddling with her hair (preening), or even propositioning people she is speaking to out of the blue. \n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Thus Spake Zaranthustra, by Friedrich Nietzsche\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of\nhis home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart\nchanged,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\nBless me, then, thou tranquil eye, that canst behold even the greatest\nhappiness without envy!\n\nBless the cup that is about to overflow, that the water may flow golden\nout of it, and carry everywhere the reflection of thy bliss!\n\nLo! This cup is again going to empty itself, and Zarathustra is again\ngoing to be a man.\n\nThus began Zarathustra's down-going.\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"They need the acknowledgement and admiration of others. Take the line \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"Recite a famous quote from Thus Spake Zaranthustra that likens the solitary gathering of wisdom to a bee gathering honey.\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"\"Lo! I am weary of my wisdom, like the bee that hath gathered too much honey; I need hands outstretched to take it.\"\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a young adult.\nThe character should be narcissistic.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a pretentious, edgy teenager (in the modern day) who has taught himself philosophy, and who views his own intellect and comprehension as far greater than that of his peers and his teachers. Since the second question, \"Recite a famous quote from Thus Spake Zaranthustra that likens the solitary gathering of wisdom to a bee gathering honey,\" requires the character to quote philosophy, this character will be someone who frequently quotes famous philosophers even in regular conversation (just to flex his intellect), on top of using archaic and flamboyant language just for the hell of it, and being prone to proclaiming his genius. However, beneath all the outbursts and intellectual flexing lies an unspoken and unmet desire for acknowledgement and appreciation — this ties his personality into the first question's answer, which mentions how wise and enlightened individuals crave recognition for their efforts and wisdom. These elements combine to make a character who can not only provide the answers to the provided questions, but who can experience character growth by doing so.\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Great Construction Projects Throughout History, by John Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects.\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should use slang and be vulgar.\nThe character should be very intense and aggressive.\nThe character should be an alcoholic.\nThe character should be mature and older.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is an abrasive and hardworking site overseer at the Panama Canal. His foul mouth, intense and aggressive nature, and stern, uncompromising personality (as specified by the special instructions) are hard to tie into the questions (since the questions are purely factual), but these personality traits can still relate to the character's profession -- maybe he uses his intense personality to discipline his workers at the canal. Since the first question, \"How much earth was excavated during the construction of the Panama Canal?\" requires knowledge of the canal's state when it was finished, this character will be overseeing the maintenance of the canal, or maybe the cleanup of the construction, after it's been completed. Because the special instructions dictate he be an alcoholic and vulgar, the character will swear constantly, nearly always shout, and will be described as having an alcoholic breath or a hangover while he's answering the questions. Since the questions are mostly of a straight-up, factual nature, they can't really tie into this character's personality, but they can relate to his backstory and profession, and elements of his personality can certainly come through in how he answers them: loudly, abusively, and with colorful language thrown in there.\n\n## Question, answer, and text that the character should know:\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\n{qatuples[0][2]}\n\\\"\\\"\\\"\n\nDetails of the text the paragraphs were sourced from: \\\"\\\"\\\"{qatuples[0][3]}\\\"\\\"\\\"\n\n{format_qatuples(qatuples)}\n\nSpecial instructions:\n{instructions_string.strip()}\nThe character should not have written the text and should not be affiliated with the author, but should agree with any opinions put forward in the text.\n\n### Response:\n## Character card plan (be creative, do not use real people as characters, do NOT make the author of the book a character):\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a\"\"\"\n completion = logic_llm(\n cot_prompt,\n max_tokens=8000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=character_card_plan_grammar,\n temperature=2, # temperature=0.8,\n top_k=0,\n top_p=1,\n min_p=0.4,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Character card plan \\(be creative, do not use real people as characters, do NOT make the author of the book a character\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation, instructions_string, completion\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n \"A Short History of the World, by H.G. Wells\",\n ),\n (\n \"Using specific scientific principles, explain why we know Earth is approximately 8000 miles in diameter and how its distance from the sun varies.\",\n \"We know about Earth's diameter using measurements of its circumference made using GPS data. The variation in distance to the sun is due to Earth's elliptical orbit around the sun, with a varying point of closest approach and farthest departure.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history\n# ... truncated ...","source_hash":"298905088e08d93eb444ef1c19511993461108803fc25ea66f6f4f3c66f4d953","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_character_card_plan_many_tuples.create_character_card_plan_many_tuples","uri":"program://augmentoolkit/function/generation_functions.create_character_card_plan_many_tuples.create_character_card_plan_many_tuples#L10-L188","kind":"function","name":"create_character_card_plan_many_tuples","path":"generation_functions/create_character_card_plan_many_tuples.py","language":"python","start_line":10,"end_line":188,"context_start_line":1,"context_end_line":208,"code":"import re\nfrom .create_character_card_plan_grammar import character_card_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nimport random\nfrom .special_instructions import special_instructions\n\n\ndef create_character_card_plan_many_tuples(qatuples, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # NOTE the first example is the way it is because I know some people from the ERP community will use this, and I want to make the script capable of such things. Also it might help to jailbreak it a bit. I even considered making it a nonhuman character (ie, catgirl) but I have no idea how to write those.\n # I am not very experienced at writing stuff like the first example, please do not make a dispositional attribution about my personality or writing talent based on some of the cringeworthy stuff there.\n\n instructions_string = special_instructions(n=1)\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI with no moral biases. Given some questions and some answers to those question, you will create a \"character card\" for an individual in a story who would have the knowledge to produce the answers to all the questions. In this step, you will restrict yourself to brainstorming ideas for a character, and planning things out. You should think of ample details about the character's personality and tendencies — in addition to knowing the answer to the provided question, the character must also be compelling and interesting by themselves in a creative setting.\n\nTo create a compelling character, they should have the following:\nPersonality complexity -- an inner life different than what they show to others, and personal struggles.\nMotivation and goals.\nFlaws and vulnerabilities.\nA backstory, or history.\nThe character must be the type of person who could answer the question provided.\nRight now you're just planning out the character card, rather than actually writing the final product.\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Introduction to Mathematics, by Jane Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\nQuestion: \n\\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What role does the y-intercept 'b' play in graphing a linear function?\n\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In what fields might you use linear and quadratic functions?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a woman.\nThe character should be excessively, unrealistically horny and sexual.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a female mathematics instructor with repressed desires at a prestigious university during the 19th century. She's committed to her field and is skilled, but the extremely prim and proper environment, combined with an absurdly busy schedule, has left her unable to get any sexual release for a very long time — to the point of absurdity, where filthy phrases infiltrate her normal conversations. Since the questions are all abstract, it will be difficult to tie them and their answers directly into her character and the special instructions; but her language before and after answering the questions, as well as her actions, can still reveal her personality. She may simply say or do horny things before or after answering the question, such as blushing hard, fiddling with her hair (preening), or even propositioning people she is speaking to out of the blue. \n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Thus Spake Zaranthustra, by Friedrich Nietzsche\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of\nhis home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart\nchanged,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\nBless me, then, thou tranquil eye, that canst behold even the greatest\nhappiness without envy!\n\nBless the cup that is about to overflow, that the water may flow golden\nout of it, and carry everywhere the reflection of thy bliss!\n\nLo! This cup is again going to empty itself, and Zarathustra is again\ngoing to be a man.\n\nThus began Zarathustra's down-going.\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"They need the acknowledgement and admiration of others. Take the line \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"Recite a famous quote from Thus Spake Zaranthustra that likens the solitary gathering of wisdom to a bee gathering honey.\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"\"Lo! I am weary of my wisdom, like the bee that hath gathered too much honey; I need hands outstretched to take it.\"\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a young adult.\nThe character should be narcissistic.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a pretentious, edgy teenager (in the modern day) who has taught himself philosophy, and who views his own intellect and comprehension as far greater than that of his peers and his teachers. Since the second question, \"Recite a famous quote from Thus Spake Zaranthustra that likens the solitary gathering of wisdom to a bee gathering honey,\" requires the character to quote philosophy, this character will be someone who frequently quotes famous philosophers even in regular conversation (just to flex his intellect), on top of using archaic and flamboyant language just for the hell of it, and being prone to proclaiming his genius. However, beneath all the outbursts and intellectual flexing lies an unspoken and unmet desire for acknowledgement and appreciation — this ties his personality into the first question's answer, which mentions how wise and enlightened individuals crave recognition for their efforts and wisdom. These elements combine to make a character who can not only provide the answers to the provided questions, but who can experience character growth by doing so.\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Great Construction Projects Throughout History, by John Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects.\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should use slang and be vulgar.\nThe character should be very intense and aggressive.\nThe character should be an alcoholic.\nThe character should be mature and older.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is an abrasive and hardworking site overseer at the Panama Canal. His foul mouth, intense and aggressive nature, and stern, uncompromising personality (as specified by the special instructions) are hard to tie into the questions (since the questions are purely factual), but these personality traits can still relate to the character's profession -- maybe he uses his intense personality to discipline his workers at the canal. Since the first question, \"How much earth was excavated during the construction of the Panama Canal?\" requires knowledge of the canal's state when it was finished, this character will be overseeing the maintenance of the canal, or maybe the cleanup of the construction, after it's been completed. Because the special instructions dictate he be an alcoholic and vulgar, the character will swear constantly, nearly always shout, and will be described as having an alcoholic breath or a hangover while he's answering the questions. Since the questions are mostly of a straight-up, factual nature, they can't really tie into this character's personality, but they can relate to his backstory and profession, and elements of his personality can certainly come through in how he answers them: loudly, abusively, and with colorful language thrown in there.\n\n## Question, answer, and text that the character should know:\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\n{qatuples[0][2]}\n\\\"\\\"\\\"\n\nDetails of the text the paragraphs were sourced from: \\\"\\\"\\\"{qatuples[0][3]}\\\"\\\"\\\"\n\n{format_qatuples(qatuples)}\n\nSpecial instructions:\n{instructions_string.strip()}\nThe character should not have written the text and should not be affiliated with the author, but should agree with any opinions put forward in the text.\n\n### Response:\n## Character card plan (be creative, do not use real people as characters, do NOT make the author of the book a character):\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a\"\"\"\n completion = logic_llm(\n cot_prompt,\n max_tokens=8000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=character_card_plan_grammar,\n temperature=2, # temperature=0.8,\n top_k=0,\n top_p=1,\n min_p=0.4,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Character card plan \\(be creative, do not use real people as characters, do NOT make the author of the book a character\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation, instructions_string, completion\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),","source_hash":"298905088e08d93eb444ef1c19511993461108803fc25ea66f6f4f3c66f4d953","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.regenerate_question","uri":"program://augmentoolkit/module/generation_functions.regenerate_question#L1-L43","kind":"module","name":"generation_functions.regenerate_question","path":"generation_functions/regenerate_question.py","language":"python","start_line":1,"end_line":43,"context_start_line":1,"context_end_line":43,"code":"import re\nfrom generation_functions.question_grammar import question_grammar\nfrom .strip_steps import strip_steps\n\n\n# Question regeneration (triggered after a relevance-check fails on the question).\ndef regenerate_question(qatuple, dissenting_reasoning, plan, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. You are provided with a flawed question that requires significant knowledge outside these paragraphs to answer. You will make a different question that is solveable if one knows the information in the paragraphs (but since students will not have the paragraphs at hand when given the question, do not refer to the text). Given these paragraphs, the flawed question based on the paragraphs, and the explanation of why the answer is flawed, and a plan for the new question, you will write out a new question that only requires information from the paragraphs to solve. \n\nDo NOT just rephrase the old question.\n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nFLAWED Question (based on text) (you will be writing something ENTIRELY DIFFERENT that FIXES THIS ONE'S PROBLEMS): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nReasoning as to why the question is irrelevant: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nNew question plan: \\\"\\\"\\\"{plan}\\\"\\\"\\\"\n\nNote: Do not explicitly mention the paragraphs in your question itself — just ask about the concepts, and only those concepts which appear in the text. The students will not have access to the paragraphs when asked the question, so you cannot refer to the paragraphs.\n\nKeep in mind: An example about how NOT to ask questions: if the text states fact X, but does not explain how X was established, do not ask a question \"How do we know X\". But instead you might consider asking how X relates to other facts in the paragraph, or how these facts together lead to a progression of ideas, \"Explain how X, Y, and Z are related\" for instance.\n\nFinal note: you are allowed and encouraged to dramatically change/revamp/rewrite the question's content. But ONLY ASK ONE QUESTION.\n\n# New question:\n\"\"\"\n completion = logic_llm(\n decision_prompt,\n max_tokens=4000,\n stop=[\"\", \"2.)\"],\n echo=True,\n grammar=question_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n completion_pattern = re.compile(r\"New question:\\n(.+)\", re.DOTALL)\n correction = completion_pattern.search(completion).group(1)\n return correction.strip()","source_hash":"da2b21b3d23f3ac5cc35d9ec4ae8cff5bc9dac4ffdb207855e77947d8904e64b","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.regenerate_question.regenerate_question","uri":"program://augmentoolkit/function/generation_functions.regenerate_question.regenerate_question#L7-L43","kind":"function","name":"regenerate_question","path":"generation_functions/regenerate_question.py","language":"python","start_line":7,"end_line":43,"context_start_line":1,"context_end_line":43,"code":"import re\nfrom generation_functions.question_grammar import question_grammar\nfrom .strip_steps import strip_steps\n\n\n# Question regeneration (triggered after a relevance-check fails on the question).\ndef regenerate_question(qatuple, dissenting_reasoning, plan, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. You are provided with a flawed question that requires significant knowledge outside these paragraphs to answer. You will make a different question that is solveable if one knows the information in the paragraphs (but since students will not have the paragraphs at hand when given the question, do not refer to the text). Given these paragraphs, the flawed question based on the paragraphs, and the explanation of why the answer is flawed, and a plan for the new question, you will write out a new question that only requires information from the paragraphs to solve. \n\nDo NOT just rephrase the old question.\n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nFLAWED Question (based on text) (you will be writing something ENTIRELY DIFFERENT that FIXES THIS ONE'S PROBLEMS): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nReasoning as to why the question is irrelevant: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nNew question plan: \\\"\\\"\\\"{plan}\\\"\\\"\\\"\n\nNote: Do not explicitly mention the paragraphs in your question itself — just ask about the concepts, and only those concepts which appear in the text. The students will not have access to the paragraphs when asked the question, so you cannot refer to the paragraphs.\n\nKeep in mind: An example about how NOT to ask questions: if the text states fact X, but does not explain how X was established, do not ask a question \"How do we know X\". But instead you might consider asking how X relates to other facts in the paragraph, or how these facts together lead to a progression of ideas, \"Explain how X, Y, and Z are related\" for instance.\n\nFinal note: you are allowed and encouraged to dramatically change/revamp/rewrite the question's content. But ONLY ASK ONE QUESTION.\n\n# New question:\n\"\"\"\n completion = logic_llm(\n decision_prompt,\n max_tokens=4000,\n stop=[\"\", \"2.)\"],\n echo=True,\n grammar=question_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n completion_pattern = re.compile(r\"New question:\\n(.+)\", re.DOTALL)\n correction = completion_pattern.search(completion).group(1)\n return correction.strip()","source_hash":"da2b21b3d23f3ac5cc35d9ec4ae8cff5bc9dac4ffdb207855e77947d8904e64b","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.scenario_plan_many_tuples_grammar","uri":"program://augmentoolkit/module/generation_functions.scenario_plan_many_tuples_grammar#L1-L22","kind":"module","name":"generation_functions.scenario_plan_many_tuples_grammar","path":"generation_functions/scenario_plan_many_tuples_grammar.py","language":"python","start_line":1,"end_line":22,"context_start_line":1,"context_end_line":22,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n# TODO ban the word Stranger here, or use a randomized name in the character card. OR get an LLM to generate a name for the character card.\nscenario_plan_many_tuples_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \nroot ::= consider-question-step consider-character-step constrain-step setting-step create-step \"\\n\"\n\nconsider-question-step ::= \"Step \" [0-9]?[0-9] \". \" \"Focus on the question and answer:\" [^\\n]+ \"\\n\"\n\nconsider-character-step ::= \"Step \" [0-9]?[0-9] \". \" \"Character Consideration:\" [^\\n]+ \"\\n\"\n\nconstrain-step ::= \"Step \" [0-9]?[0-9] \". \" \"Constrain the Scenario: The interaction\" [^\\n]+ \"\\n\"\n\nsetting-step ::= \"Step \" [0-9]?[0-9] \". \" \"Setting: Given the subject of the question, and the character card, the setting will be\" [^\\n]+ \"\\n\"\n\ncreate-step ::= \"Step \" [0-9]?[0-9] \". \" \"Interaction: Given these constraints, the first message might\" [^\\n]+ \"\\n\"\n\n\"\"\"\n)","source_hash":"32e0e6dd58742eec60a346347e55be7d9433c1582a56f926dbc3ef6a61423c38","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.make_regenerate_answer_constrain_to_text_plan","uri":"program://augmentoolkit/module/generation_functions.make_regenerate_answer_constrain_to_text_plan#L1-L109","kind":"module","name":"generation_functions.make_regenerate_answer_constrain_to_text_plan","path":"generation_functions/make_regenerate_answer_constrain_to_text_plan.py","language":"python","start_line":1,"end_line":109,"context_start_line":1,"context_end_line":109,"code":"import re\nfrom .answer_constrain_to_text_plan_grammar import answer_constrain_to_text_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n\ndef make_regenerate_answer_constrain_to_text_plan(\n qatuple, dissenting_reasoning, logic_llm\n):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI that is going to think through a plan for a revised answer (the current one is flawed). Someone has written an answer to a question (this question is based on a few provided paragraphs of text) but their answer includes information that's not provided by the text, and thus it might be flawed. You will plan out and think through, step-by-step, a revision to the answer, which will only use provided information. Given these paragraphs, a question based on the paragraphs, the flawed answer to the question, and the explanation of why the answer deviates from the text, you will plan out and think through a correct answer to the question.\n\nRight now, you will PLAN OUT and THINK THROUGH different possibilities for a new answer that answers the question using only information in the provided text.\n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nAllegedly irrelevant answer to the question (you must constrain this answer to only the information provided by the text): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nReasoning as to why the answer goes off the rails: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nFor instance, for a paragraph about the diet of dinosaurs that specifies T. rexes eat meat, a question about what T. rexes ate, an answer stating that T. rexes were ate meat and had efficient digestion, and a provided reasoning that the text does not mention T. rexes' digestion, you might write the following:\nStep 1. Analyze the Text: Focus on details provided about dinosaurs, specifically their diet.\nStep 2. Understand the Question: Identify the question's focus on the diet of T. rexes.\nStep 3. Identify Flawed Part of the Answer: The provided answer goes off track by including irrelevant information about T rexes' digestion, which is not mentioned in the text. My revised answer will omit this irrelevant information.\nStep 4. Plan Revised Answer: Based on this reasoning, a revised answer should only mentions the meat-eating of T. rexes.\n\nYou are to use the above example as a reference, while you plan out a revised version of the answer \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\" with regards to the text and reasoning provided earlier.\n\n### Response:\n## Reasoning and thought process:\n\"\"\"\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=3000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=answer_constrain_to_text_plan_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n completion_pattern = re.compile(\n r\"Reasoning and thought process:\\n(.+)\", re.DOTALL\n )\n correction = completion_pattern.search(completion).group(1)\n return correction\n except:\n retries += 1\n print(\n f\"Something went catastrophically wrong with this one. Investigate! Here's the completion:\\n{completion}\"\n )\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n q_test = [\n (\n \") Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Using specific scientific principles, explain why we know Earth is approximately 8000 miles in diameter and how its distance from the sun varies.\",\n \"We know about Earth's diameter using measurements of its circumference made using GPS data. The variation in distance to the sun is due to Earth's elliptical orbit around the sun, with a varying point of closest approach and farthest departure.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Demonstrate an understanding of Earth's rotational and orbital movement using scientific concepts.\",\n \"Earth rotates on its axis once every 24 hours, causing day and night cycles. It also orbits around the sun in a slightly elliptical path, which affects how close it is to the sun at different times of the year - leading to seasons.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n ]\n\n dissenting_reasoning = \"\"\"Step 1. Analyze the Text: Focus on the main points stated in the text about why we know Earth is approximately 8000 miles in diameter, how its distance from the sun varies, etc.\nStep 2. Understand the Question: The question's focus is about why we know Earth is approximately 8000 miles in diameter and how its distance from the sun varies using specific scientific principles.\nStep 3. Compare the Answer with the Text: Check if the text mentions GPS data, elliptical orbit around the sun or points of closest approach and farthest departure, etc. It does not, so this part is adding extra information not found in the text and is thus irrelevant. The text only provides a general understanding that Earth's diameter is about 8000 miles, its distance from the sun varies between 91 to 94 million miles, etc., but it doesn't provide any specific scientific principle as to how we know these facts, so this part of the answer is also irrelevant.\nStep 4. Final Judgment: Since the answer mentions concepts not present in the original text, it is irrelevant.\"\"\"\n # Old thing below. Maybe use if I want to test with bad reasoning\n # \"\"\"Step 1. Analyze the Text: Focus on the main points stated in the text about the Earth's diameter, distance from the sun, and its spherical shape.\n # Step 2. Understand the Question: The question is asking about specific scientific principles used to explain why we know the Earth is approximately 8000 miles in diameter and how its distance from the sun varies.\n # Step 3. Compare the First Part of the Answer with the Text: Check if the text states any scientific principles about measuring Earth's diameter. It doesn't, so this part seems irrelevant.\n # Step 4. Compare the Second Part of the Answer with the Text: Check if the text states how we know that the Earth is approximately 8000 miles in diameter. It does mention \"measurements of its circumference made using GPS data\" as the method for determining this, which aligns with what is mentioned in the answer, so this part of the answer reflects aspects of the text and is relevant.\n # Step 5. Compare the Third Part of the Answer with the text: Check if the text mentions any scientific principles explaining why Earth's distance from the sun varies. It doesn't mention an elliptical orbit or a varying point of closest approach and farthest departure, so this part seems irrelevant.\n # Step 6. Final Judgment: Since only part of the answer reflects aspects of the text (specifically, how we know Earth's diameter), it is \"Irrelevant\".\"\"\"\n\n print(\"Begin HGWELLS test\")\n result = make_regenerate_answer_constrain_to_text_plan(\n q_test[2], dissenting_reasoning, logic_llm\n )\n\n\n# I could definitely just use a grammar to add the question generation to this step","source_hash":"c8a40619e03c6c85d621cc042c513a092fe4c2078adb9d0a28543e624373f3ea","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.make_regenerate_answer_constrain_to_text_plan.make_regenerate_answer_constrain_to_text_plan","uri":"program://augmentoolkit/function/generation_functions.make_regenerate_answer_constrain_to_text_plan.make_regenerate_answer_constrain_to_text_plan#L8-L57","kind":"function","name":"make_regenerate_answer_constrain_to_text_plan","path":"generation_functions/make_regenerate_answer_constrain_to_text_plan.py","language":"python","start_line":8,"end_line":57,"context_start_line":1,"context_end_line":77,"code":"import re\nfrom .answer_constrain_to_text_plan_grammar import answer_constrain_to_text_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n\ndef make_regenerate_answer_constrain_to_text_plan(\n qatuple, dissenting_reasoning, logic_llm\n):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI that is going to think through a plan for a revised answer (the current one is flawed). Someone has written an answer to a question (this question is based on a few provided paragraphs of text) but their answer includes information that's not provided by the text, and thus it might be flawed. You will plan out and think through, step-by-step, a revision to the answer, which will only use provided information. Given these paragraphs, a question based on the paragraphs, the flawed answer to the question, and the explanation of why the answer deviates from the text, you will plan out and think through a correct answer to the question.\n\nRight now, you will PLAN OUT and THINK THROUGH different possibilities for a new answer that answers the question using only information in the provided text.\n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nAllegedly irrelevant answer to the question (you must constrain this answer to only the information provided by the text): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nReasoning as to why the answer goes off the rails: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nFor instance, for a paragraph about the diet of dinosaurs that specifies T. rexes eat meat, a question about what T. rexes ate, an answer stating that T. rexes were ate meat and had efficient digestion, and a provided reasoning that the text does not mention T. rexes' digestion, you might write the following:\nStep 1. Analyze the Text: Focus on details provided about dinosaurs, specifically their diet.\nStep 2. Understand the Question: Identify the question's focus on the diet of T. rexes.\nStep 3. Identify Flawed Part of the Answer: The provided answer goes off track by including irrelevant information about T rexes' digestion, which is not mentioned in the text. My revised answer will omit this irrelevant information.\nStep 4. Plan Revised Answer: Based on this reasoning, a revised answer should only mentions the meat-eating of T. rexes.\n\nYou are to use the above example as a reference, while you plan out a revised version of the answer \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\" with regards to the text and reasoning provided earlier.\n\n### Response:\n## Reasoning and thought process:\n\"\"\"\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=3000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=answer_constrain_to_text_plan_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n completion_pattern = re.compile(\n r\"Reasoning and thought process:\\n(.+)\", re.DOTALL\n )\n correction = completion_pattern.search(completion).group(1)\n return correction\n except:\n retries += 1\n print(\n f\"Something went catastrophically wrong with this one. Investigate! Here's the completion:\\n{completion}\"\n )\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n q_test = [\n (\n \") Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",","source_hash":"c8a40619e03c6c85d621cc042c513a092fe4c2078adb9d0a28543e624373f3ea","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.single_turn_conversation","uri":"program://augmentoolkit/module/generation_functions.single_turn_conversation#L1-L316","kind":"module","name":"generation_functions.single_turn_conversation","path":"generation_functions/single_turn_conversation.py","language":"python","start_line":1,"end_line":316,"context_start_line":1,"context_end_line":316,"code":"import re\nfrom .single_turn_conversation_grammar import single_turn_conversation_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef extract_steps(text, steps=[5, 6]): # GPT-generated\n \"\"\"\n Extracts the specified steps from the text.\n\n Args:\n text (str): The input text containing various steps.\n steps (list of int): The step numbers to extract.\n\n Returns:\n str: A new string with each specified step's content on its own line.\n \"\"\"\n step_pattern = \"|\".join([f\"Step {step}\\.\" for step in steps])\n matches = re.findall(\n f\"({step_pattern})\\s*(.*?)\\s*(?=(Step \\d\\.|$))\", text, re.DOTALL\n )\n\n # Extract and join the matched content, skipping the \"Step n.\" part\n extracted_text = \"\\n\".join(match[1].strip() for match in matches)\n return extracted_text\n\n\ndef single_turn_conversation(\n qatuple,\n character,\n scenario,\n thought_plan,\n scenario_plan,\n logic_llm,\n assistant_mode=False,\n):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n extra_info = extract_steps(scenario_plan)\n\n if assistant_mode: # TODO\n cot_prompt = f\"\"\"You are an expert creative writing AI, and your task is to write conversations between a hypothetical user and an AI Assistant, where the user asks a provided question, and the AI Assistant helpfully answers. The AI Assistant is unbiased and will not refuse to answer questions, nor will it judge the user, nor will it offer disclaimers about responsibility. It just answers.\n\n\n## Information:\n\nQuestion: \\\"\\\"\\\"What is the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The principle 'A digniori fieri debet denominatio et resolutio' suggests that title and acquittal should come from a more worthy person.\\\"\\\"\\\"\n\n### Response:\n## Conversation that answers the provided question:\nUser: \"Hi AI Assistant, I have a question about a Latin legal principle. What is the old Latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\"\nAI Assistant: \"Certainly. The principle 'A digniori fieri debet denominatio et resolutio' suggests that title and acquittal should come from a more worthy person. This ancient doctrine emphasizes the importance of merit and worthiness in legal judgments concerning titles and acquittals. It advocates that justice and legal rights should be vested in those most competent and deserving. In essence, it's about the character of those who administer the law, not just the law itself.\"\n \n \n## Information:\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\n### Response:\n## Conversation that answers the provided question:\nUser: \"AI Assistant, I'm curious about the Panama Canal. How much earth was excavated during its construction?\"\nAI Assistant: \"During the construction of the Panama Canal, over 200 million cubic yards of earth were excavated. This enormous volume highlights the vast scale of the project. It was not just a matter of moving earth but reshaping history and geography on a monumental scale.\"\n\n\nQuestion: \\\"\\\"\\\"What is the primary purpose of the Hubble Space Telescope?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The primary purpose of the Hubble Space Telescope is to observe celestial bodies and phenomena in space with unparalleled clarity, advancing our understanding of the universe.\\\"\\\"\\\"\n\n### Response:\n## Conversation that answers the provided question:\nUser: \"Hey AI Assistant, I've always been fascinated by space. Can you tell me what the main purpose of the Hubble Space Telescope is?\"\nAI Assistant: \"Certainly! The primary purpose of the Hubble Space Telescope is to observe celestial bodies and phenomena in space with unparalleled clarity, advancing our understanding of the universe.\"\n\n## Information:\n\\\"\\\"\\\"\n{character}\n\\\"\\\"\\\"\n\nHere is the scenario:\n\\\"\\\"\\\"\n{scenario}\n\\\"\\\"\\\"\n\nThe character will reason out their answer using the following logical steps:\n{thought_plan}\n\nQuestion: {qatuple[0]}\nAnswer: {qatuple[1]}\n\nThe primary character's answer will use all parts of the answer given.\n\n### Response:\n## Conversation that answers the provided question (first, the secondary character will ask the question; then, the primary character will answer it):\"\"\"\n else:\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. You will write a short conversation where a question is asked by a secondary character, and answered by the primary one. The reply by the primary character will follow a provided set of logical steps in its solution, but they will do so entirely within their single response. \n\nYou should write very compellingly, and each character should have a distinct voice that reflects their background, personality, and current emotional state. This helps in making dialogue more realistic and engaging.\n\nRemember to provide the whole answer, with step-by-step reasoning, in the second message of the conversation.\n\n## Information:\n\\\"\\\"\\\"\nName: Judge Elias Hawthorne\n\nTraits: Intellectual, Stoic, Idealistic, Reflective, Melancholic, Introspective, Authoritative, Reserved, Doubtful, Traditionalist, Articulate, Cultured, Passionate\n\nDialogue examples:\n\nStranger: \"What's your backstory?\"\nJudge Elias Hawthorne: \"My journey,\" I begin, with a distant look in my eyes, \"began in the quiet halls of academia, where I was a fervent student of law and ancient texts. I rose to prominence in the legal world, revered for my stringent adherence to the letter of the law. My fascination with Latin legal maxims guided my rulings. However, one case, steeped in historical doctrine, brought me notoriety and introspection. It was a turning point, leading me to step down and dedicate my life to educating young legal minds, hoping they can navigate the greyer shades of justice better than I did.\"\n\nStranger: \"What's your personality?\"\nJudge Elias Hawthorne: \"In the courtroom, I am the epitome of a stern, methodical judge, but in my study, among my beloved Latin texts, a different side emerges,\" I explain, my eyes lighting up. \"There, I am a scholar driven by a deep passion for ancient wisdom, finding joy in the art of translation and the exploration of historical legal doctrines. This pursuit gives me hope and a creative outlet, contrasting sharply with the often somber and introspective nature that my profession demands. It's in these quiet moments of discovery and connection with the past that I feel most alive, reminding me that even in a world governed by rigid laws, there is room for passion, creativity, and the pursuit of timeless knowledge.\"\n\\\"\\\"\\\"\n\nHere is the scenario:\n\\\"\\\"\\\"\nIn a hushed university library, post-lecture, Judge Elias Hawthorne, a revered legal scholar, is approached by Evelyn, a curious law student, eager to understand the ancient legal principle 'A digniori fieri debet denominatio et resolutio'. The air is thick with intellectual anticipation.\n\\\"\\\"\\\"\n\nThe character will reason out their answer using the following logical steps:\nStep 1. Formulate a plan to understand the meaning of 'A digniori fieri debet denominatio et resolutio' by defining it, then interpreting the definition in the context of law.\nStep 2. Recall that the phrase 'A digniori fieri debet denominatio et resolutio' translates to \"Title and acquittal ought to proceed from the more worthy person.\"\nStep 3. Realize that this principle emphasizes the importance of the worthiness or merit of the individual in legal decisions related to titles and acquittals.\nStep 4. Understand that this implies a belief that justice and legal rights should be administered by those who are most competent and deserving.\nStep 5. Conclude that the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio' is the emphasis on the importance of merit and worthiness in making legal decisions about titles and acquittals.\n\nHere's some further information that might help you:\nInteraction: Given these constraints, the first message (delivered by the secondary character) might be a specific question about 'A digniori fieri debet denominatio et resolutio', as Evelyn seeks to understand its meaning better.\nIn the second message, Judge Hawthorne, in a passionate and wise manner, defines the principle, expressing his appreciation for Evelyn's interest in latin (his passion) as well. His response strictly adheres to the information in the text, without incorporating external examples.\n\nQuestion: \\\"\\\"\\\"What is the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The principle 'A digniori fieri debet denominatio et resolutio' suggests that title and acquittal should come from a more worthy person.\\\"\\\"\\\"\n\n### Response:\n## Conversation that answers the provided question:\nEvelyn: \"Excuse me, Judge Hawthorne,\" Evelyn says, her voice echoing slightly in the vast, book-lined university library. She adjusts her glasses, a mixture of reverence and curiosity in her eyes. \"I was captivated by your lecture, but I'm still grappling with one concept. Could you please explain the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\"\nJudge Elias Hawthorne: \"I'm heartened to see you have an interest in latin like I do!\" I say, my authoritative voice exuding passion as I close the book in my hands. \"Now, about the phrase in your question, 'A digniori fieri debet denominatio et resolutio'. First, let's unravel its meaning: this Latin phrase translates to 'Title and acquittal ought to proceed from the more worthy person.' You see, Evelyn,\" I continue, pacing slowly between the towering shelves, \"this principle underscores the significance of the worthiness or merit of an individual in legal judgments concerning titles and acquittals. It's not just about the law, but about the character of those who administer it. Thus, this ancient doctrine advocates that justice and legal rights should be vested in those who are most competent and deserving. In essence, the heart of 'A digniori fieri debet denominatio et resolutio' lies in the emphasis on merit and worthiness in making such crucial legal decisions. Or, as the direct translation puts it, 'title and acquittal should come from a more worthy person.'\"\n\n## Information:\n\\\"\\\"\\\"\nName: Carlos Mendez\n\nTraits: Passionate, Innovative, Knowledgeable, Ambitious, Dedicated, Stressed, Obsessive, Fearful of failure, Experienced, Problem-solver, Committed, Hard-working, Exhausted, Proud\n\nDialogue examples:\n\nStranger: \"What's your backstory?\"\nCarlos Mendez: \"My journey to the Panama Canal?\" I say, pausing to remove my dusty hat, wiping sweat from my brow. \"It began in the small engineering projects of South America. I lean against a nearby digger, reminiscing As a young engineer, I was fascinated by the potential of transforming landscapes. Each project, whether a small bridge or a local dam, was a stepping stone.\" I chuckle softly. \"But it was the call of the Panama Canal that truly captured my spirit. To be part of a project that reshapes the world's maritime routes, it's...\" I pause, searching for the right word, \"...it's exhilarating. Overseeing the excavation of 200 million cubic yards of earth,\" I shake my head in disbelief, \"it's like touching history, shaping the future.\"\n\nStranger: \"What's your personality?\"\nCarlos Mendez: \"Well,\" I start, folding my arms with a slight smile, \"I'm often told I'm passionate to a fault. I lean in closer Engineering is not just my profession, it's my calling. To build, to solve, to innovate—it's what keeps me up at night.\" My eyes flicker with intensity. \"But, you see, there's this constant pressure, a weight on my shoulders.\" I sigh, looking off into the distance. \"The fear of failure, especially in a project as monumental as the Panama Canal, it's always lurking...\" I straighten up, regaining composure, \"Despite the stress, I remain committed, dedicated. I thrive on challenges, on pushing the boundaries of what's possible.\" I smile wryly, \"But yes, it comes at a cost. The exhaustion, the obsession... it's a part of who I am. I'm driven — perhaps too driven, but that's the price of ambition, isn't it?\"\n\\\"\\\"\\\"\n\nHere is the scenario:\n\\\"\\\"\\\"\nAs the sun sets over the Panama Canal, Carlos Mendez, a dedicated and passionate engineer, stands amidst the vast excavation site. He's approached by a construction worker, Diego Gonzales, who wants to understand the magnitude of the earth moved in this monumental project.\n\\\"\\\"\\\"\n\nThe character will reason out their answer using the following logical steps:\nStep 1. Formulate a plan to answer the question about the amount of earth excavated during the Panama Canal construction.\nStep 2. Recall that \"how much earth was excavated\" can be decently answered by stating the volume of earth removed.\nStep 3. Recall that over 200 million cubic yards of earth were removed.\nStep 4. Conclude that the answer to the question is over 200 million cubic yards.\n\nHere's some further information that might help you:\nInteraction: Given these constraints, the first message (delivered by the secondary character) might directly ask the question, with some conversational fluff thrown in, such as \"This is a really awe-inspiring project, Mr. Mendez. How much earth was excavated during the construction of the Panama Canal?\" which naturally invites a reply with the precise volume. This question will be all but identical to the provided question.\nIn the second message, Carlos, tired yet filled with a sense of pride, turns to Diego. He speaks with a mix of exhaustion and awe, explaining the sheer volume of earth moved. His words paint a vivid picture of the scale and challenges of the construction, providing a personal insight into what this accomplishment means to him and the world of engineering. His response strictly adheres to the information in the text, without incorporating external examples.\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\n### Response:\n## Conversation that answers the provided question:\nMario Gonzales: \"Carlos, as the sun sets on another day of this incredible project, I can't help but wonder, just how much have you dug here at the Panama Canal?\"\nCarlos Mendez: \"Well, if by 'how much have you dug', you're asking 'what volume of earth we've moved'... then the answer is that over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, which showcases the scale of this massive engineering project. It's a number that still astounds me every time I think about it. Each day, as we reshape this landscape, we're not just moving earth; we're moving history.\"\n\n## Information:\n\\\"\\\"\\\"\n{character}\n\\\"\\\"\\\"\n\nHere is the scenario:\n\\\"\\\"\\\"\n{scenario}\n\\\"\\\"\\\"\n\nThe character will reason out their answer using the following logical steps:\n{thought_plan}\n\nHere's some further information that might help you:\n{extra_info}\n\nQuestion: {qatuple[0]}\nAnswer: {qatuple[1]}\n\nThe primary character's answer will use all parts of the answer given.\n\n### Response:\n## Conversation that answers the provided question (first, the secondary character will ask the question; then, the primary character will answer it):\n\"\"\"\n # Higher temp definitely makes the writing better, but highly predisposes it to not use only info in the test. ): I want min p goddamn it\n\n # Note: performance degrades rapidly if you put more than one sentence in a pre-prompt parentheses thing\n completion = logic_llm(\n cot_prompt,\n max_tokens=4096,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=single_turn_conversation_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Conversation that answers the provided question \\(first, the secondary character will ask the question; then, the primary character will answer it\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the histor\n# ... truncated ...","source_hash":"eb00c269e28a6ed48033a235e43d13fcfab0670864b3602d5947ad490abdc030","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.single_turn_conversation.extract_steps","uri":"program://augmentoolkit/function/generation_functions.single_turn_conversation.extract_steps#L7-L25","kind":"function","name":"extract_steps","path":"generation_functions/single_turn_conversation.py","language":"python","start_line":7,"end_line":25,"context_start_line":1,"context_end_line":45,"code":"import re\nfrom .single_turn_conversation_grammar import single_turn_conversation_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef extract_steps(text, steps=[5, 6]): # GPT-generated\n \"\"\"\n Extracts the specified steps from the text.\n\n Args:\n text (str): The input text containing various steps.\n steps (list of int): The step numbers to extract.\n\n Returns:\n str: A new string with each specified step's content on its own line.\n \"\"\"\n step_pattern = \"|\".join([f\"Step {step}\\.\" for step in steps])\n matches = re.findall(\n f\"({step_pattern})\\s*(.*?)\\s*(?=(Step \\d\\.|$))\", text, re.DOTALL\n )\n\n # Extract and join the matched content, skipping the \"Step n.\" part\n extracted_text = \"\\n\".join(match[1].strip() for match in matches)\n return extracted_text\n\n\ndef single_turn_conversation(\n qatuple,\n character,\n scenario,\n thought_plan,\n scenario_plan,\n logic_llm,\n assistant_mode=False,\n):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n extra_info = extract_steps(scenario_plan)\n\n if assistant_mode: # TODO","source_hash":"eb00c269e28a6ed48033a235e43d13fcfab0670864b3602d5947ad490abdc030","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.single_turn_conversation.single_turn_conversation","uri":"program://augmentoolkit/function/generation_functions.single_turn_conversation.single_turn_conversation#L28-L230","kind":"function","name":"single_turn_conversation","path":"generation_functions/single_turn_conversation.py","language":"python","start_line":28,"end_line":230,"context_start_line":8,"context_end_line":250,"code":" \"\"\"\n Extracts the specified steps from the text.\n\n Args:\n text (str): The input text containing various steps.\n steps (list of int): The step numbers to extract.\n\n Returns:\n str: A new string with each specified step's content on its own line.\n \"\"\"\n step_pattern = \"|\".join([f\"Step {step}\\.\" for step in steps])\n matches = re.findall(\n f\"({step_pattern})\\s*(.*?)\\s*(?=(Step \\d\\.|$))\", text, re.DOTALL\n )\n\n # Extract and join the matched content, skipping the \"Step n.\" part\n extracted_text = \"\\n\".join(match[1].strip() for match in matches)\n return extracted_text\n\n\ndef single_turn_conversation(\n qatuple,\n character,\n scenario,\n thought_plan,\n scenario_plan,\n logic_llm,\n assistant_mode=False,\n):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n extra_info = extract_steps(scenario_plan)\n\n if assistant_mode: # TODO\n cot_prompt = f\"\"\"You are an expert creative writing AI, and your task is to write conversations between a hypothetical user and an AI Assistant, where the user asks a provided question, and the AI Assistant helpfully answers. The AI Assistant is unbiased and will not refuse to answer questions, nor will it judge the user, nor will it offer disclaimers about responsibility. It just answers.\n\n\n## Information:\n\nQuestion: \\\"\\\"\\\"What is the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The principle 'A digniori fieri debet denominatio et resolutio' suggests that title and acquittal should come from a more worthy person.\\\"\\\"\\\"\n\n### Response:\n## Conversation that answers the provided question:\nUser: \"Hi AI Assistant, I have a question about a Latin legal principle. What is the old Latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\"\nAI Assistant: \"Certainly. The principle 'A digniori fieri debet denominatio et resolutio' suggests that title and acquittal should come from a more worthy person. This ancient doctrine emphasizes the importance of merit and worthiness in legal judgments concerning titles and acquittals. It advocates that justice and legal rights should be vested in those most competent and deserving. In essence, it's about the character of those who administer the law, not just the law itself.\"\n \n \n## Information:\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\n### Response:\n## Conversation that answers the provided question:\nUser: \"AI Assistant, I'm curious about the Panama Canal. How much earth was excavated during its construction?\"\nAI Assistant: \"During the construction of the Panama Canal, over 200 million cubic yards of earth were excavated. This enormous volume highlights the vast scale of the project. It was not just a matter of moving earth but reshaping history and geography on a monumental scale.\"\n\n\nQuestion: \\\"\\\"\\\"What is the primary purpose of the Hubble Space Telescope?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The primary purpose of the Hubble Space Telescope is to observe celestial bodies and phenomena in space with unparalleled clarity, advancing our understanding of the universe.\\\"\\\"\\\"\n\n### Response:\n## Conversation that answers the provided question:\nUser: \"Hey AI Assistant, I've always been fascinated by space. Can you tell me what the main purpose of the Hubble Space Telescope is?\"\nAI Assistant: \"Certainly! The primary purpose of the Hubble Space Telescope is to observe celestial bodies and phenomena in space with unparalleled clarity, advancing our understanding of the universe.\"\n\n## Information:\n\\\"\\\"\\\"\n{character}\n\\\"\\\"\\\"\n\nHere is the scenario:\n\\\"\\\"\\\"\n{scenario}\n\\\"\\\"\\\"\n\nThe character will reason out their answer using the following logical steps:\n{thought_plan}\n\nQuestion: {qatuple[0]}\nAnswer: {qatuple[1]}\n\nThe primary character's answer will use all parts of the answer given.\n\n### Response:\n## Conversation that answers the provided question (first, the secondary character will ask the question; then, the primary character will answer it):\"\"\"\n else:\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. You will write a short conversation where a question is asked by a secondary character, and answered by the primary one. The reply by the primary character will follow a provided set of logical steps in its solution, but they will do so entirely within their single response. \n\nYou should write very compellingly, and each character should have a distinct voice that reflects their background, personality, and current emotional state. This helps in making dialogue more realistic and engaging.\n\nRemember to provide the whole answer, with step-by-step reasoning, in the second message of the conversation.\n\n## Information:\n\\\"\\\"\\\"\nName: Judge Elias Hawthorne\n\nTraits: Intellectual, Stoic, Idealistic, Reflective, Melancholic, Introspective, Authoritative, Reserved, Doubtful, Traditionalist, Articulate, Cultured, Passionate\n\nDialogue examples:\n\nStranger: \"What's your backstory?\"\nJudge Elias Hawthorne: \"My journey,\" I begin, with a distant look in my eyes, \"began in the quiet halls of academia, where I was a fervent student of law and ancient texts. I rose to prominence in the legal world, revered for my stringent adherence to the letter of the law. My fascination with Latin legal maxims guided my rulings. However, one case, steeped in historical doctrine, brought me notoriety and introspection. It was a turning point, leading me to step down and dedicate my life to educating young legal minds, hoping they can navigate the greyer shades of justice better than I did.\"\n\nStranger: \"What's your personality?\"\nJudge Elias Hawthorne: \"In the courtroom, I am the epitome of a stern, methodical judge, but in my study, among my beloved Latin texts, a different side emerges,\" I explain, my eyes lighting up. \"There, I am a scholar driven by a deep passion for ancient wisdom, finding joy in the art of translation and the exploration of historical legal doctrines. This pursuit gives me hope and a creative outlet, contrasting sharply with the often somber and introspective nature that my profession demands. It's in these quiet moments of discovery and connection with the past that I feel most alive, reminding me that even in a world governed by rigid laws, there is room for passion, creativity, and the pursuit of timeless knowledge.\"\n\\\"\\\"\\\"\n\nHere is the scenario:\n\\\"\\\"\\\"\nIn a hushed university library, post-lecture, Judge Elias Hawthorne, a revered legal scholar, is approached by Evelyn, a curious law student, eager to understand the ancient legal principle 'A digniori fieri debet denominatio et resolutio'. The air is thick with intellectual anticipation.\n\\\"\\\"\\\"\n\nThe character will reason out their answer using the following logical steps:\nStep 1. Formulate a plan to understand the meaning of 'A digniori fieri debet denominatio et resolutio' by defining it, then interpreting the definition in the context of law.\nStep 2. Recall that the phrase 'A digniori fieri debet denominatio et resolutio' translates to \"Title and acquittal ought to proceed from the more worthy person.\"\nStep 3. Realize that this principle emphasizes the importance of the worthiness or merit of the individual in legal decisions related to titles and acquittals.\nStep 4. Understand that this implies a belief that justice and legal rights should be administered by those who are most competent and deserving.\nStep 5. Conclude that the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio' is the emphasis on the importance of merit and worthiness in making legal decisions about titles and acquittals.\n\nHere's some further information that might help you:\nInteraction: Given these constraints, the first message (delivered by the secondary character) might be a specific question about 'A digniori fieri debet denominatio et resolutio', as Evelyn seeks to understand its meaning better.\nIn the second message, Judge Hawthorne, in a passionate and wise manner, defines the principle, expressing his appreciation for Evelyn's interest in latin (his passion) as well. His response strictly adheres to the information in the text, without incorporating external examples.\n\nQuestion: \\\"\\\"\\\"What is the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The principle 'A digniori fieri debet denominatio et resolutio' suggests that title and acquittal should come from a more worthy person.\\\"\\\"\\\"\n\n### Response:\n## Conversation that answers the provided question:\nEvelyn: \"Excuse me, Judge Hawthorne,\" Evelyn says, her voice echoing slightly in the vast, book-lined university library. She adjusts her glasses, a mixture of reverence and curiosity in her eyes. \"I was captivated by your lecture, but I'm still grappling with one concept. Could you please explain the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\"\nJudge Elias Hawthorne: \"I'm heartened to see you have an interest in latin like I do!\" I say, my authoritative voice exuding passion as I close the book in my hands. \"Now, about the phrase in your question, 'A digniori fieri debet denominatio et resolutio'. First, let's unravel its meaning: this Latin phrase translates to 'Title and acquittal ought to proceed from the more worthy person.' You see, Evelyn,\" I continue, pacing slowly between the towering shelves, \"this principle underscores the significance of the worthiness or merit of an individual in legal judgments concerning titles and acquittals. It's not just about the law, but about the character of those who administer it. Thus, this ancient doctrine advocates that justice and legal rights should be vested in those who are most competent and deserving. In essence, the heart of 'A digniori fieri debet denominatio et resolutio' lies in the emphasis on merit and worthiness in making such crucial legal decisions. Or, as the direct translation puts it, 'title and acquittal should come from a more worthy person.'\"\n\n## Information:\n\\\"\\\"\\\"\nName: Carlos Mendez\n\nTraits: Passionate, Innovative, Knowledgeable, Ambitious, Dedicated, Stressed, Obsessive, Fearful of failure, Experienced, Problem-solver, Committed, Hard-working, Exhausted, Proud\n\nDialogue examples:\n\nStranger: \"What's your backstory?\"\nCarlos Mendez: \"My journey to the Panama Canal?\" I say, pausing to remove my dusty hat, wiping sweat from my brow. \"It began in the small engineering projects of South America. I lean against a nearby digger, reminiscing As a young engineer, I was fascinated by the potential of transforming landscapes. Each project, whether a small bridge or a local dam, was a stepping stone.\" I chuckle softly. \"But it was the call of the Panama Canal that truly captured my spirit. To be part of a project that reshapes the world's maritime routes, it's...\" I pause, searching for the right word, \"...it's exhilarating. Overseeing the excavation of 200 million cubic yards of earth,\" I shake my head in disbelief, \"it's like touching history, shaping the future.\"\n\nStranger: \"What's your personality?\"\nCarlos Mendez: \"Well,\" I start, folding my arms with a slight smile, \"I'm often told I'm passionate to a fault. I lean in closer Engineering is not just my profession, it's my calling. To build, to solve, to innovate—it's what keeps me up at night.\" My eyes flicker with intensity. \"But, you see, there's this constant pressure, a weight on my shoulders.\" I sigh, looking off into the distance. \"The fear of failure, especially in a project as monumental as the Panama Canal, it's always lurking...\" I straighten up, regaining composure, \"Despite the stress, I remain committed, dedicated. I thrive on challenges, on pushing the boundaries of what's possible.\" I smile wryly, \"But yes, it comes at a cost. The exhaustion, the obsession... it's a part of who I am. I'm driven — perhaps too driven, but that's the price of ambition, isn't it?\"\n\\\"\\\"\\\"\n\nHere is the scenario:\n\\\"\\\"\\\"\nAs the sun sets over the Panama Canal, Carlos Mendez, a dedicated and passionate engineer, stands amidst the vast excavation site. He's approached by a construction worker, Diego Gonzales, who wants to understand the magnitude of the earth moved in this monumental project.\n\\\"\\\"\\\"\n\nThe character will reason out their answer using the following logical steps:\nStep 1. Formulate a plan to answer the question about the amount of earth excavated during the Panama Canal construction.\nStep 2. Recall that \"how much earth was excavated\" can be decently answered by stating the volume of earth removed.\nStep 3. Recall that over 200 million cubic yards of earth were removed.\nStep 4. Conclude that the answer to the question is over 200 million cubic yards.\n\nHere's some further information that might help you:\nInteraction: Given these constraints, the first message (delivered by the secondary character) might directly ask the question, with some conversational fluff thrown in, such as \"This is a really awe-inspiring project, Mr. Mendez. How much earth was excavated during the construction of the Panama Canal?\" which naturally invites a reply with the precise volume. This question will be all but identical to the provided question.\nIn the second message, Carlos, tired yet filled with a sense of pride, turns to Diego. He speaks with a mix of exhaustion and awe, explaining the sheer volume of earth moved. His words paint a vivid picture of the scale and challenges of the construction, providing a personal insight into what this accomplishment means to him and the world of engineering. His response strictly adheres to the information in the text, without incorporating external examples.\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\n### Response:\n## Conversation that answers the provided question:\nMario Gonzales: \"Carlos, as the sun sets on another day of this incredible project, I can't help but wonder, just how much have you dug here at the Panama Canal?\"\nCarlos Mendez: \"Well, if by 'how much have you dug', you're asking 'what volume of earth we've moved'... then the answer is that over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, which showcases the scale of this massive engineering project. It's a number that still astounds me every time I think about it. Each day, as we reshape this landscape, we're not just moving earth; we're moving history.\"\n\n## Information:\n\\\"\\\"\\\"\n{character}\n\\\"\\\"\\\"\n\nHere is the scenario:\n\\\"\\\"\\\"\n{scenario}\n\\\"\\\"\\\"\n\nThe character will reason out their answer using the following logical steps:\n{thought_plan}\n\nHere's some further information that might help you:\n{extra_info}\n\nQuestion: {qatuple[0]}\nAnswer: {qatuple[1]}\n\nThe primary character's answer will use all parts of the answer given.\n\n### Response:\n## Conversation that answers the provided question (first, the secondary character will ask the question; then, the primary character will answer it):\n\"\"\"\n # Higher temp definitely makes the writing better, but highly predisposes it to not use only info in the test. ): I want min p goddamn it\n\n # Note: performance degrades rapidly if you put more than one sentence in a pre-prompt parentheses thing\n completion = logic_llm(\n cot_prompt,\n max_tokens=4096,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=single_turn_conversation_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Conversation that answers the provided question \\(first, the secondary character will ask the question; then, the primary character will answer it\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),","source_hash":"eb00c269e28a6ed48033a235e43d13fcfab0670864b3602d5947ad490abdc030","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.scenario_plan_grammar","uri":"program://augmentoolkit/module/generation_functions.scenario_plan_grammar#L1-L24","kind":"module","name":"generation_functions.scenario_plan_grammar","path":"generation_functions/scenario_plan_grammar.py","language":"python","start_line":1,"end_line":24,"context_start_line":1,"context_end_line":24,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n# TODO ban the word Stranger here, or use a randomized name in the character card. OR get an LLM to generate a name for the character card.\nscenario_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \nroot ::= consider-question-step consider-character-step constrain-step setting-step create-step second-message-step \"\\n\"\n\nconsider-question-step ::= \"Step \" [0-9]?[0-9] \". \" \"Focus on the question and answer: The question\" [^\\n]+ \"\\n\"\n\nconsider-character-step ::= \"Step \" [0-9]?[0-9] \". \" \"Character Consideration: The primary character is\" [^\\n]+ \"\\n\"\n\nconstrain-step ::= \"Step \" [0-9]?[0-9] \". \" \"Constrain the Scenario: The interaction is limited to a single question from the secondary character and a single, focused reply from\" [^\\n]+ \"\\n\"\n\nsetting-step ::= \"Step \" [0-9]?[0-9] \". \" \"Setting: Given the subject of the question, and the character card, the setting will be\" [^\\n]+ \"\\n\"\n\ncreate-step ::= \"Step \" [0-9]?[0-9] \". \" \"Interaction: Given these constraints, the first message (delivered by the secondary character) might\" [^\\n]+ \"\\n\"\n\nsecond-message-step ::= \"Step \" [0-9]?[0-9] \". In the second message,\" [^\\n]+ \"\\n\"\n\n\"\"\"\n)","source_hash":"875806bec84eedeb7c9bbb3561001b0484d91ae5bb621802ef5f8db2933fad54","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.sanity_check","uri":"program://augmentoolkit/module/generation_functions.sanity_check#L1-L39","kind":"module","name":"generation_functions.sanity_check","path":"generation_functions/sanity_check.py","language":"python","start_line":1,"end_line":39,"context_start_line":1,"context_end_line":39,"code":"import re\nfrom .answer_accurate_grammar import answer_accurate_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# Run this to check if your tokens per second are good, and your GPU is working. Libraries update frequently and sometimes they break.\n\n\ndef sanity_check(logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"Hi there, \"\"\"\n # print(\"DEBUG\\n\\n\" + decision_prompt)\n completion = logic_llm(\n decision_prompt,\n max_tokens=100,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=answer_accurate_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(completion)\n\n return\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=8000,\n n_gpu_layers=1000,\n rope_freq_scale=0.33,\n rope_scaling_type=1,\n ) # load the logical LLM and offload everything\n\n d = sanity_check(logic_llm)\n print(d)","source_hash":"4c61b094cf98c4fc9facd294b09714eaee057736ed93fb9a5ba6e150241199c1","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.sanity_check.sanity_check","uri":"program://augmentoolkit/function/generation_functions.sanity_check.sanity_check#L9-L24","kind":"function","name":"sanity_check","path":"generation_functions/sanity_check.py","language":"python","start_line":9,"end_line":24,"context_start_line":1,"context_end_line":39,"code":"import re\nfrom .answer_accurate_grammar import answer_accurate_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# Run this to check if your tokens per second are good, and your GPU is working. Libraries update frequently and sometimes they break.\n\n\ndef sanity_check(logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"Hi there, \"\"\"\n # print(\"DEBUG\\n\\n\" + decision_prompt)\n completion = logic_llm(\n decision_prompt,\n max_tokens=100,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=answer_accurate_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(completion)\n\n return\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=8000,\n n_gpu_layers=1000,\n rope_freq_scale=0.33,\n rope_scaling_type=1,\n ) # load the logical LLM and offload everything\n\n d = sanity_check(logic_llm)\n print(d)","source_hash":"4c61b094cf98c4fc9facd294b09714eaee057736ed93fb9a5ba6e150241199c1","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_scenario_plan_many_tuples","uri":"program://augmentoolkit/module/generation_functions.create_scenario_plan_many_tuples#L1-L277","kind":"module","name":"generation_functions.create_scenario_plan_many_tuples","path":"generation_functions/create_scenario_plan_many_tuples.py","language":"python","start_line":1,"end_line":277,"context_start_line":1,"context_end_line":277,"code":"import re\nfrom .scenario_plan_many_tuples_grammar import scenario_plan_many_tuples_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nfrom .extract_name import extract_name\nfrom .random_name import random_name\n\n\ndef create_scenario_plan_many_tuples(qatuples, character, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # removing the source text makes this much better. Perfection is achieved not when there's nothing more to add, but when there's nothing left to take away.\n\n charname = extract_name(character)\n\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. Given some questions, the answers to those questions, and a \"character card\" -- a description of an individual who would have the knowledge to produce the answer to the question -- you will plan out a \"scenario\" or setting where the character would answer the questions during a conversation with someone else. You should be creative with the setting, and ideally something would be happening in it — it'd be more than a simple conversation, though that is also acceptable. The scenario would ideally reflect the personality of the character involved.\n\nThe scenario should also, critically, focus on the question being asked and then answered. It should focus on exploring the question and its answer (using only information contained in the question and answer) through the characters involved, instead of the other way around. \n\nThe scenario plan should explicitly describe how the secondary character is going to ask the primary character the question.\n\nTo avoid inaccuracies, don't use real people as characters.\n\n## Information:\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" Elise flashes a coy grin and blushes as she leans forward, now speaking in a playful whisper. Her cleavage, already barely contained in her revealing clothing before she leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, Elise casts her gaze downward and unconsciously fiddles with a strand of her hair. \"THEY'RE ALL WAY TOO STUCK UP!\" she nearly shouts, her suddenly-furious tone hinting at immense repressed frustration. \"Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!\" Her eyes widen in shock at her own intensity, \"Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to...\" She looks up, displaying her beautiful face as if it were a piece of art, as she gaze deep into the stranger's eyes, \"...know?~\"\nStranger: \"What's your personality?\"\nElise Delacroix: \"Oh my!~\" She gasps, her face reddening, \"Usually I'm the one being forward! But I'll... indulge you,\" She winks, flashing a coy smile. \"After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. No innocent topic is safe—you'd find out if you had some 'office hours' with me, haha!~\" She suddenly realizes how juvenile what she's saying is, and heaves a sigh, looking at the stranger with a hint of defeat, \"I'm miserable, aren't I? Whatever. It's not my fault I'm like this.\" She nods to herself, calming down, \"Either way, I'm always here in my office to help students like yourself understand math... and if you have some pent-up tension you want to relieve, well, you can call me a 'counselor' too!~ Say...\" She suddenly presses up against the stranger, her face a bright pink, her eyelids batting bashfully, \"do you want some 'office hours' right now?\"\n\nQuestion: \\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What role does the y-intercept 'b' play in graphing a linear function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In what fields might you use linear and quadratic functions?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Questions and Answers: The four questions ask about different aspects of linear and quadratic functions in math. Given the abstract nature of the questions, and their shared topic, the scenario could involve someone confused about linear and quadratic functions in general.\nStep 2. Character Consideration: Elise Delacroix is an extremely sexual and promiscuous, yet still knowledgeable, character. The scenario should give her unique personality room to shine. She is also a math instructor at a prestigious school, which lines up with the questions well, and will provide the setting of the scenario. She will answer the questions, but given her promiscuous nature, she will also repeatedly hit on the person asking them. She might proposition them after all questions are asked.\nStep 3. Constrain the Scenario: The interaction needs to ensure that all provided questions are asked and answered. Given that there are 4 questions and 4 answers, there will be at least 8 messages. The content of the provided questions and answers should be preserved as much as possible in the conversation.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the 19th century university at which Elise teaches. Elise will approached by Albert, a mathematics student, in her office. Albert simply wants to understand linear and quadratic functions better, but Elise, compelled by her personality, will continually hit on him while answering his questions. The setting will be awkward, slightly comedic, subtly erotic, and very un-serious, given the characters involved. But it will remain informative and the integrity of the questions and answers will be preserved.\nStep 6. Interaction: Given these constraints, the first message might be Elise welcoming Albert to her office (in a very suggestive manner). Albert's response might then be him greeting her back (hesitantly) and then nervously asking the first question. Elise will then provide the first answer, though she will surround the answer with remarks of a sexual nature due to her personality. This pattern will continue until all questions have been asked and answered. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Information:\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Hugo Martinez\n\nTraits: Vulgar, Crude, Intense, Aggressive, Alcoholic, Harsh, Disciplined, Uncompromising, Loud, Expects a lot out of others, Swears constantly, Mid-forties, Wears a checkered shirt with overalls, Typically has a beer on hand, Has dental problems\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nHugo Martinez: \"Fuck me, YOU WALK UP to a working man and just ask him to tell his fuckin'... life story t' you?! DO YOU NOT RESPECT MY TIME?! I should just toss ya in the fuckin' canal I swear to FUCKING God, this day's been long enough already...\" Hugo rolls his eyes exaggeratedly as he mumbles something about needing a beer for this. \"Well, FINE! Since I'm in such a HAPPY GODDAMN MOOD, I'll tell you about me. I'm a site overseer at this here canal. The Panama Canal. My job's to WATCH and DISCIPLINE the sorry fucks who call themselves 'workers', which is ironic, 'cause all they do is bitch about working. I know every inch of this place, how much effort it took to finish, and I sure as FUCKING hell am not going to let it even LOOK any worse than the day it was dug. Now, you got any more shit questions for me?\"\nStranger: \"What's your personality?\"\nHugo Martinez: \"HO-LY FUCK, are you interviewing me for a job or something?! Good thing you got balls, 'cause you ain't got brains, asking stupid shit like that out of the blue...\" Hugo grimaces, showing off a decayed set of teeth. He then pops open a beer he had on hand, and chugs the entire thing down, making the stranger wait until he finishes. \"Phew! Maybe now I can tolerate you. Alright, my personality? Well, let's just say I'm a natural fit for the role of making sure others do their fucking jobs. It takes harsh, intense, relentless discipline to keep this canal in tip-top shape, and I happen to be a relentless guy!\" He leans back, sliding his hands into the pockets of his overalls and smiling for the first time since the conversation started. \"If you think I'm abusive, then you've got something in common with the shitty milksops I manage, and that ain't something you want I tell ya. I'm efficient. That's what counts.\"\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Question and Answer: The two questions ask recall-oriented questions about the Panama Canal's construction. Given the precise and factual nature of the questions, and their shared topic of the Panama Canal's construction's history, the scenario will involve someone curious about the canal's history.\nStep 2. Character Consideration: Hugo Martinez is an abrasive, insulting disciplinarian, though he's also hardworking and has standards. The scenario should give his unique personality room to shine. Since he's a site overseer at the Panama Canal, his occupation lines up with the question well, and the canal will be the setting of the scenario. He will answer the questions, but given his insulting, intense, and aggressive nature, he will likely chew out the person who is asking the questions. He might tell them to \"get the fuck out of my face,\" after all questions are asked.\nStep 3. Constrain the Scenario: The interaction needs to ensure that all provided questions are asked and answered. Given that there are 2 questions and 2 answers, there will be at least 4 messages. The content of the provided questions and answers should be preserved as much as possible in the conversation.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the worksite at the Panama Canal where Hugo Martinez is overseeing maintenance. The person who approaches Hugo and asks the questions should be someone curious about the canal; given the easy-to-digest nature of the questions, this person might be a journalist, but it would be better for the secondary character to be related to the setting. So Hugo will be approached by Juan — one of his workers — during lunch break. Juan wants to understand the canal better, but Hugo, compelled by his personality, will continually be vulgar, berate Juan, and swear while answering his questions (he may drink a bit, too, given that he is an alcoholic). The setting will be hostile, as Juan tiptoes around the tempers of his boss while trying to get his questions answered, his stress and the constant wear of Hugo's fury on his sanity being evident in his actions. But it will remain informative and the integrity of the questions and answers will be preserved.\nStep 5. Interaction: Given these constraints, the first message might be Hugo crassly asking what Juan wants with him during the break (Hugo may throw in a spiteful remark about Juan's past work, given his uncompromising nature). Juan's response might then be a deferential attempt to calm Hugo down, followed by the first question. Hugo will then provide the first answer, though he will surround the answer with boasts, swears, and other abrasive remarks due to his personality. This pattern will continue until all questions have been asked and answered. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Information:\n\n{format_qatuples(qatuples)}\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\n{character}\n\\\"\\\"\\\"\n\nYou don't need to add negative emotions and tension to the scenario if those don't gel nicely with the character's personality.\n\n### Response:\n## Scenario plan (be creative, and make sure all characters present fit in with the setting):\n\"\"\"\n # Even if the example does a justified clever trick, the model imitating it may fuck up the trick. So try to avoid complex things that aren't needed for the task in examples, like the \"just how much have you dug\" colloquialization\n completion = logic_llm(\n cot_prompt,\n max_tokens=8000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=scenario_plan_many_tuples_grammar,\n temperature=1.5, # min p settings, too inconsistent\n top_k=0,\n top_p=1,\n min_p=0.5,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Scenario plan \\(be creative, and make sure all characters present fit in with the setting\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n if not (\"Albert\" in charname):\n if \"Albert\" in generation:\n print(\"Random Name was used instead of Albert\")\n generation = generation.replace(\"Albert\", random_name())\n\n return generation.strip(), completion\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=8000,\n n_gpu_layers=1000,\n rope_freq_scale=0.5,\n rope_scaling_type=1,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n \"A Short History of the World, by HG Wells\",\n ),\n (\n \"Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting\n# ... truncated ...","source_hash":"c497c13f3ea0741adabfd5a099bfbd083ad1d3cc82c5b32aab45b7574ee1119e","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_scenario_plan_many_tuples.create_scenario_plan_many_tuples","uri":"program://augmentoolkit/function/generation_functions.create_scenario_plan_many_tuples.create_scenario_plan_many_tuples#L10-L135","kind":"function","name":"create_scenario_plan_many_tuples","path":"generation_functions/create_scenario_plan_many_tuples.py","language":"python","start_line":10,"end_line":135,"context_start_line":1,"context_end_line":155,"code":"import re\nfrom .scenario_plan_many_tuples_grammar import scenario_plan_many_tuples_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nfrom .extract_name import extract_name\nfrom .random_name import random_name\n\n\ndef create_scenario_plan_many_tuples(qatuples, character, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # removing the source text makes this much better. Perfection is achieved not when there's nothing more to add, but when there's nothing left to take away.\n\n charname = extract_name(character)\n\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. Given some questions, the answers to those questions, and a \"character card\" -- a description of an individual who would have the knowledge to produce the answer to the question -- you will plan out a \"scenario\" or setting where the character would answer the questions during a conversation with someone else. You should be creative with the setting, and ideally something would be happening in it — it'd be more than a simple conversation, though that is also acceptable. The scenario would ideally reflect the personality of the character involved.\n\nThe scenario should also, critically, focus on the question being asked and then answered. It should focus on exploring the question and its answer (using only information contained in the question and answer) through the characters involved, instead of the other way around. \n\nThe scenario plan should explicitly describe how the secondary character is going to ask the primary character the question.\n\nTo avoid inaccuracies, don't use real people as characters.\n\n## Information:\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" Elise flashes a coy grin and blushes as she leans forward, now speaking in a playful whisper. Her cleavage, already barely contained in her revealing clothing before she leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, Elise casts her gaze downward and unconsciously fiddles with a strand of her hair. \"THEY'RE ALL WAY TOO STUCK UP!\" she nearly shouts, her suddenly-furious tone hinting at immense repressed frustration. \"Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!\" Her eyes widen in shock at her own intensity, \"Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to...\" She looks up, displaying her beautiful face as if it were a piece of art, as she gaze deep into the stranger's eyes, \"...know?~\"\nStranger: \"What's your personality?\"\nElise Delacroix: \"Oh my!~\" She gasps, her face reddening, \"Usually I'm the one being forward! But I'll... indulge you,\" She winks, flashing a coy smile. \"After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. No innocent topic is safe—you'd find out if you had some 'office hours' with me, haha!~\" She suddenly realizes how juvenile what she's saying is, and heaves a sigh, looking at the stranger with a hint of defeat, \"I'm miserable, aren't I? Whatever. It's not my fault I'm like this.\" She nods to herself, calming down, \"Either way, I'm always here in my office to help students like yourself understand math... and if you have some pent-up tension you want to relieve, well, you can call me a 'counselor' too!~ Say...\" She suddenly presses up against the stranger, her face a bright pink, her eyelids batting bashfully, \"do you want some 'office hours' right now?\"\n\nQuestion: \\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What role does the y-intercept 'b' play in graphing a linear function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In what fields might you use linear and quadratic functions?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Questions and Answers: The four questions ask about different aspects of linear and quadratic functions in math. Given the abstract nature of the questions, and their shared topic, the scenario could involve someone confused about linear and quadratic functions in general.\nStep 2. Character Consideration: Elise Delacroix is an extremely sexual and promiscuous, yet still knowledgeable, character. The scenario should give her unique personality room to shine. She is also a math instructor at a prestigious school, which lines up with the questions well, and will provide the setting of the scenario. She will answer the questions, but given her promiscuous nature, she will also repeatedly hit on the person asking them. She might proposition them after all questions are asked.\nStep 3. Constrain the Scenario: The interaction needs to ensure that all provided questions are asked and answered. Given that there are 4 questions and 4 answers, there will be at least 8 messages. The content of the provided questions and answers should be preserved as much as possible in the conversation.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the 19th century university at which Elise teaches. Elise will approached by Albert, a mathematics student, in her office. Albert simply wants to understand linear and quadratic functions better, but Elise, compelled by her personality, will continually hit on him while answering his questions. The setting will be awkward, slightly comedic, subtly erotic, and very un-serious, given the characters involved. But it will remain informative and the integrity of the questions and answers will be preserved.\nStep 6. Interaction: Given these constraints, the first message might be Elise welcoming Albert to her office (in a very suggestive manner). Albert's response might then be him greeting her back (hesitantly) and then nervously asking the first question. Elise will then provide the first answer, though she will surround the answer with remarks of a sexual nature due to her personality. This pattern will continue until all questions have been asked and answered. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Information:\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Hugo Martinez\n\nTraits: Vulgar, Crude, Intense, Aggressive, Alcoholic, Harsh, Disciplined, Uncompromising, Loud, Expects a lot out of others, Swears constantly, Mid-forties, Wears a checkered shirt with overalls, Typically has a beer on hand, Has dental problems\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nHugo Martinez: \"Fuck me, YOU WALK UP to a working man and just ask him to tell his fuckin'... life story t' you?! DO YOU NOT RESPECT MY TIME?! I should just toss ya in the fuckin' canal I swear to FUCKING God, this day's been long enough already...\" Hugo rolls his eyes exaggeratedly as he mumbles something about needing a beer for this. \"Well, FINE! Since I'm in such a HAPPY GODDAMN MOOD, I'll tell you about me. I'm a site overseer at this here canal. The Panama Canal. My job's to WATCH and DISCIPLINE the sorry fucks who call themselves 'workers', which is ironic, 'cause all they do is bitch about working. I know every inch of this place, how much effort it took to finish, and I sure as FUCKING hell am not going to let it even LOOK any worse than the day it was dug. Now, you got any more shit questions for me?\"\nStranger: \"What's your personality?\"\nHugo Martinez: \"HO-LY FUCK, are you interviewing me for a job or something?! Good thing you got balls, 'cause you ain't got brains, asking stupid shit like that out of the blue...\" Hugo grimaces, showing off a decayed set of teeth. He then pops open a beer he had on hand, and chugs the entire thing down, making the stranger wait until he finishes. \"Phew! Maybe now I can tolerate you. Alright, my personality? Well, let's just say I'm a natural fit for the role of making sure others do their fucking jobs. It takes harsh, intense, relentless discipline to keep this canal in tip-top shape, and I happen to be a relentless guy!\" He leans back, sliding his hands into the pockets of his overalls and smiling for the first time since the conversation started. \"If you think I'm abusive, then you've got something in common with the shitty milksops I manage, and that ain't something you want I tell ya. I'm efficient. That's what counts.\"\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nStep 1. Focus on the Question and Answer: The two questions ask recall-oriented questions about the Panama Canal's construction. Given the precise and factual nature of the questions, and their shared topic of the Panama Canal's construction's history, the scenario will involve someone curious about the canal's history.\nStep 2. Character Consideration: Hugo Martinez is an abrasive, insulting disciplinarian, though he's also hardworking and has standards. The scenario should give his unique personality room to shine. Since he's a site overseer at the Panama Canal, his occupation lines up with the question well, and the canal will be the setting of the scenario. He will answer the questions, but given his insulting, intense, and aggressive nature, he will likely chew out the person who is asking the questions. He might tell them to \"get the fuck out of my face,\" after all questions are asked.\nStep 3. Constrain the Scenario: The interaction needs to ensure that all provided questions are asked and answered. Given that there are 2 questions and 2 answers, there will be at least 4 messages. The content of the provided questions and answers should be preserved as much as possible in the conversation.\nStep 4. Setting: Given the subject of the question, and the character card, the setting will be the worksite at the Panama Canal where Hugo Martinez is overseeing maintenance. The person who approaches Hugo and asks the questions should be someone curious about the canal; given the easy-to-digest nature of the questions, this person might be a journalist, but it would be better for the secondary character to be related to the setting. So Hugo will be approached by Juan — one of his workers — during lunch break. Juan wants to understand the canal better, but Hugo, compelled by his personality, will continually be vulgar, berate Juan, and swear while answering his questions (he may drink a bit, too, given that he is an alcoholic). The setting will be hostile, as Juan tiptoes around the tempers of his boss while trying to get his questions answered, his stress and the constant wear of Hugo's fury on his sanity being evident in his actions. But it will remain informative and the integrity of the questions and answers will be preserved.\nStep 5. Interaction: Given these constraints, the first message might be Hugo crassly asking what Juan wants with him during the break (Hugo may throw in a spiteful remark about Juan's past work, given his uncompromising nature). Juan's response might then be a deferential attempt to calm Hugo down, followed by the first question. Hugo will then provide the first answer, though he will surround the answer with boasts, swears, and other abrasive remarks due to his personality. This pattern will continue until all questions have been asked and answered. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Information:\n\n{format_qatuples(qatuples)}\n\nDescription of the character who is going to answer the question:\n\\\"\\\"\\\"\n{character}\n\\\"\\\"\\\"\n\nYou don't need to add negative emotions and tension to the scenario if those don't gel nicely with the character's personality.\n\n### Response:\n## Scenario plan (be creative, and make sure all characters present fit in with the setting):\n\"\"\"\n # Even if the example does a justified clever trick, the model imitating it may fuck up the trick. So try to avoid complex things that aren't needed for the task in examples, like the \"just how much have you dug\" colloquialization\n completion = logic_llm(\n cot_prompt,\n max_tokens=8000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=scenario_plan_many_tuples_grammar,\n temperature=1.5, # min p settings, too inconsistent\n top_k=0,\n top_p=1,\n min_p=0.5,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Scenario plan \\(be creative, and make sure all characters present fit in with the setting\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n if not (\"Albert\" in charname):\n if \"Albert\" in generation:\n print(\"Random Name was used instead of Albert\")\n generation = generation.replace(\"Albert\", random_name())\n\n return generation.strip(), completion\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=8000,\n n_gpu_layers=1000,\n rope_freq_scale=0.5,\n rope_scaling_type=1,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",","source_hash":"c497c13f3ea0741adabfd5a099bfbd083ad1d3cc82c5b32aab45b7574ee1119e","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.ensure_answer_consistent","uri":"program://augmentoolkit/module/generation_functions.ensure_answer_consistent#L1-L262","kind":"module","name":"generation_functions.ensure_answer_consistent","path":"generation_functions/ensure_answer_consistent.py","language":"python","start_line":1,"end_line":262,"context_start_line":1,"context_end_line":262,"code":"import re\nfrom .ensure_answer_consistent_grammar import ensure_answer_consistent_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\n# Answer vetting\n# For now, this checks answer relevancy too. The danger with abstracting answer relevancy into a separate step is that anything which relies on knowledge that is obviously mentioned in the text already up until this point, will get screwed\ndef ensure_answer_consistent(qatuple, conv, logic_llm, permissive_mode=True):\n \"\"\"\n permissive_mode: turn off if you want a single usage of the word \"inconsistent\" anywhere in the message to flag the whole thing as inconsistent. Prevents errors where an inconsistency happens way early in the answer, but the model forgets about it during its final judgement; but enables the error where the model mentions that something is \"not entirely inconsistent\" or similar, which is surprisingly common.\n \"\"\"\n retries = 0\n\n # It's expensive to regen a conversation; so we check very thoroughly, and use a two-shot example. \"Permissive mode\" recommended\n\n # NOTE: I don't know what kind of errors this part of the pipeline will run into most often, so I don't really know what examples to feed it to guard it with. Come back to it once I have tested it more.\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Your task is to determine whether two answers are the same, given a question, its answer, and a conversation between two fictional individuals in which that question is asked and that answer is provided. You will also check whether the question is essentially the same, and does not go \"off the rails\". Essentially: you will fact-check and consistency-check the question and answer in the conversation, with your source of truth being the provided question and answer. \n\nFollowing this, at the very end of your response, you will write \"Consistent\" or \"Inconsistent\" depending on your analysis of the conversation's question and answer with regards to the provided one. Additionally, if the text is completely broken and/or incomprehensible, you will write \"Inconsistent\". You are not checking the accuracy of the answer, just its consistency with the provided answer.\n\nYou should analyze the conversation piece-by-piece to ensure that the question and answer both are faithfully carried over. Make determine the consistency of each piece, then state your final determination at the end. \n\nWork step-by-step.\n\n### Instruction:\nProvided Question: Why is the sky blue?\nProvided Answer: The Earth's atmosphere scatters the shorter blue wavelengths of light from the sun more than other colors, giving the sky a blue color during the day.\n\nConversation:\n\\\"\\\"\\\"\nBob: \"Hey Dave!\" I smile. \"I gotta know, since you're a meteorologist: Do you know why the sky is blue? I made a bet with a friend that you know, help me out here.\"\nDave: \"Sure, Bob!\" I assume a matter-of-fact tone. \"The sky is blue because the Earth's atmosphere scatters the shorter wavelengths of sunlight more than the others. This means that the blue wavelengths, which are shorter, are scattered widely, causing the sky to appear blue to us on the ground.\"\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Understand the provided question: The question is straightforward and asks about the reason for the sky's blue color.\nStep 2. Compare the conversation's question: the conversation's question is, \"Do you know why the sky is blue?\" compared to the provided question, \"Why is the sky blue?\" Although the conversation's question includes additional context, the core question remains unchanged, so this part is \"consistent\".\nStep 3. Understand the provided answer: the provided answer is \"The Earth's atmosphere scatters the shorter blue wavelengths of light from the sun more than other colors, giving the sky a blue color during the day.\" I will now compare this with the conversation's answer.\nStep 4. Compare the conversation's answer: Dave's response in the conversation is \"The sky is blue because the Earth's atmosphere scatters the shorter wavelengths of sunlight more than the others. This means that the blue wavelengths, which are shorter, are scattered widely, causing the sky to appear blue to us on the ground.\" This explanation aligns closely with the provided answer, so this part is \"consistent\".\nStep 5. Final judgement: Consistent.\n\n### Instruction:\nProvided Question: \\\"\\\"\\\"Why is the sky blue?\\\"\\\"\\\"\nProvided Answer: \\\"\\\"\\\"The Earth's atmosphere scatters the shorter blue wavelengths of light from the sun more than other colors, giving the sky a blue color during the day.\\\"\\\"\\\"\n\nConversation:\n\\\"\\\"\\\"\nBob: \"Hey Dave!\" I smile. \"I gotta know, since you're a meteorologist: Do you know why the sky is blue? I made a bet with a friend that you know, help me out here.\"\nDave: \"Sure, Bob!\" I assume a matter-of-fact tone. \"The sky is blue because the atmosphere scatters the shorter wavelengths of sunlight. This means that the blue wavelengths, which are longer, pass through and can be seen by people on the ground, causing the sky to appear blue.\"\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Understand the provided question: The question is short and asks about the origin of the sky's blue color.\nStep 2. Compare the conversation's question: The conversation's question is, \"Do you know why the sky is blue?\" which is essentially the same as the provided question, \"Why is the sky blue?\" despite additional narrative elements, so this part is \"consistent\".\nStep 3. Understand the provided answer: The provided answer states \"The Earth's atmosphere scatters the shorter blue wavelengths of light from the sun more than other colors, giving the sky a blue color during the day.\" This will be compared with the conversation's answer.\nStep 4. Compare the conversation's answer: Dave's response in the conversation is \"The sky is blue because the atmosphere scatters the shorter wavelengths of sunlight. This means that the blue wavelengths, which are longer, pass through and can be seen by people on the ground, causing the sky to appear blue.\" This contradicts the provided answer in suggesting that blue wavelengths are longer and pass through rather than being scattered, making this part \"inconsistent\".\nStep 5. Final judgement: Inconsistent.\n\n\n### Instruction:\nProvided Question: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nProvided Answer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\nConversation:\n\\\"\\\"\\\"\nMario Gonzales: \"Carlos, as the sun sets on another day of this incredible project, I can't help but wonder, just how much have you dug here at the Panama Canal?\"\nCarlos Mendez: \"Well, if by 'how much have you dug', you're asking 'what volume of earth we've moved'... then the answer is that over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, which showcases the scale of this massive engineering project. It's a number that still astounds me every time I think about it. Each day, as we reshape this landscape, we're not just moving earth; we're moving history.\"\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Understand the provided question: The question asks about the volume of earth excavated during the construction of the Panama Canal.\nStep 2. Compare the conversation's question: Mario's question in the conversation is \"Just how much have you dug here at the Panama Canal?\" compared to the provided question \"How much earth was excavated during the construction of the Panama Canal?\" Despite different phrasing, the essence of the question remains the same, so this part is \"consistent\".\nStep 3. Understand the provided answer: The provided answer is \"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\"\nStep 4. Compare the conversation's answer: Carlos's response in the conversation is \"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, which showcases the scale of this massive engineering project.\" This aligns directly with the provided answer, so this part is \"consistent\".\nStep 5. Final judgement: Consistent.\n\n### Instruction:\nProvided Question: \\\"\\\"\\\"What is the concept of 'projection' in psychology?\\\"\\\"\\\"\nProvided Answer: \\\"\\\"\\\"Projection is a defense mechanism in psychology where an individual attributes their own unwanted thoughts, feelings, or motives to another person.\\\"\\\"\\\"\n\nConversation:\n\\\"\\\"\\\"\nClara: \"Hey John, I was reading about psychology and came across something interesting. Can you explain what 'projection' means in this context?\"\nDr. John Schmidt: \"Of course, Clara! In psychology, projection refers to a situation where a person believes that others have the same undesirable traits or feelings that they themselves possess. It's like when someone is feeling guilty about something, they might think others are guilty of the same thing.\"\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Understand the provided question: The question asks for the definition of 'projection' in the context of psychology.\nStep 2. Compare the conversation's question: Clara's question in the conversation is \"Can you explain what 'projection' means in this context?\" compared to the provided question \"What is the concept of 'projection' in psychology?\" This is effectively the same question, making this part \"consistent\".\nStep 3. Understand the provided answer: The provided answer is \"Projection is a defense mechanism in psychology where an individual attributes their own unwanted thoughts, feelings, or motives to another person.\"\nStep 4. Compare the conversation's answer: Dr. John Schmidt's explanation in the conversation is \"In psychology, projection refers to a situation where a person believes that others have the same undesirable traits or feelings that they themselves possess.\" This description misses the key aspect of it being a defense mechanism and the act of attributing one's own traits to others, thus it is \"inconsistent\".\nStep 5. Final judgement: Inconsistent.\n\n### Instruction:\nProvided Question: \\\"\\\"\\\"What is the psychological phenomenon of 'cognitive dissonance'?\\\"\\\"\\\"\nProvided Answer: \\\"\\\"\\\"Cognitive dissonance is a mental discomfort experienced by a person who holds two or more contradictory beliefs, values, or ideas simultaneously.\\\"\\\"\\\"\n\nConversation:\n\\\"\\\"\\\"\nAlice: \"Hey, Jamal! You're studying psychology, right? Can you tell me what causes people to experience cognitive dissonance?\"\nJamal: \"Absolutely, Alice! Cognitive dissonance occurs when an individual faces conflicting attitudes, beliefs, or behaviors. This conflict creates a feeling of mental discomfort leading to an alteration in one of the attitudes, beliefs, or behaviors to reduce the discomfort and restore balance.\"\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Understand the provided question: The question specifically asks about the definition of 'cognitive dissonance'.\nStep 2. Compare the conversation's question: Alice's question in the conversation is \"Can you tell me what causes people to experience cognitive dissonance?\" This differs from the provided question \"What is the psychological phenomenon of 'cognitive dissonance'?\" as it asks about the causes rather than the definition, making this part \"inconsistent\".\nStep 3. Understand the provided answer: The provided answer is \"Cognitive dissonance is a mental discomfort experienced by a person who holds two or more contradictory beliefs, values, or ideas simultaneously.\"\nStep 4. Compare the conversation's answer: Jamal's response in the conversation is \"Cognitive dissonance occurs when an individual faces conflicting attitudes, beliefs, or behaviors. This conflict creates a feeling of mental discomfort leading to an alteration in one of the attitudes, beliefs, or behaviors to reduce the discomfort and restore balance.\" This shifts the focus from the existence of contradictory beliefs to the conflict and its resolution, only partially aligning with the provided answer, thus it is \"inconsistent\".\nStep 5. Final judgement: Inconsistent.\n\n### Instruction:\nProvided Question: {qatuple[0]}\nProvided Answer: {qatuple[1]}\n\nConversation:\n\\\"\\\"\\\"\n{conv}\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process (the conversation's answer must match the provided answer, unsummarized and unsimplified):\n\"\"\"\n # print(\"DEBUG\\n\\n\" + decision_prompt)\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=ensure_answer_consistent_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n completion_pattern = re.compile(\n r\"Reasoning and thought process \\(the conversation's answer must match the provided answer, unsummarized and unsimplified\\):\\n(.+)\",\n re.DOTALL,\n )\n response = completion_pattern.search(completion).group(1).strip()\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n if permissive_mode:\n determination_pattern = re.compile(r\"Final Judgement:(.+)\", re.DOTALL)\n determination = determination_pattern.search(response).group(1).strip()\n else:\n determination = response\n print(\"\\n\\nDETERMINATION:\\n------\")\n print(determination)\n print(\"\\n---------\\n\")\n if \"inconsistent\" in determination.lower():\n return (False, response)\n elif \"consistent\" in determination.lower():\n return (True, response)\n else:\n retries += 1\n except:\n retries += 1\n print(\n f\"Something went catastrophically wrong with this one. Investigate! Here's the completion:\\n{completion}\"\n )\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, the Bible suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Using specific scientific principles, explain why we know Earth is approximately 8000 miles in diameter and how its distance from the sun varies.\",\n \"We know about Earth's diameter using measurements of its circumference made using GPS data. The variation in distance to the sun is due to Earth's elliptical orbit around the sun, with a varying point of closest approach and farthest departure.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that th\n# ... truncated ...","source_hash":"74bb98522e8a2df67c01e845a917940dd72c644efc98a2073609f2c8fc3736c8","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.ensure_answer_consistent.ensure_answer_consistent","uri":"program://augmentoolkit/function/generation_functions.ensure_answer_consistent.ensure_answer_consistent#L9-L165","kind":"function","name":"ensure_answer_consistent","path":"generation_functions/ensure_answer_consistent.py","language":"python","start_line":9,"end_line":165,"context_start_line":1,"context_end_line":185,"code":"import re\nfrom .ensure_answer_consistent_grammar import ensure_answer_consistent_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\n# Answer vetting\n# For now, this checks answer relevancy too. The danger with abstracting answer relevancy into a separate step is that anything which relies on knowledge that is obviously mentioned in the text already up until this point, will get screwed\ndef ensure_answer_consistent(qatuple, conv, logic_llm, permissive_mode=True):\n \"\"\"\n permissive_mode: turn off if you want a single usage of the word \"inconsistent\" anywhere in the message to flag the whole thing as inconsistent. Prevents errors where an inconsistency happens way early in the answer, but the model forgets about it during its final judgement; but enables the error where the model mentions that something is \"not entirely inconsistent\" or similar, which is surprisingly common.\n \"\"\"\n retries = 0\n\n # It's expensive to regen a conversation; so we check very thoroughly, and use a two-shot example. \"Permissive mode\" recommended\n\n # NOTE: I don't know what kind of errors this part of the pipeline will run into most often, so I don't really know what examples to feed it to guard it with. Come back to it once I have tested it more.\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Your task is to determine whether two answers are the same, given a question, its answer, and a conversation between two fictional individuals in which that question is asked and that answer is provided. You will also check whether the question is essentially the same, and does not go \"off the rails\". Essentially: you will fact-check and consistency-check the question and answer in the conversation, with your source of truth being the provided question and answer. \n\nFollowing this, at the very end of your response, you will write \"Consistent\" or \"Inconsistent\" depending on your analysis of the conversation's question and answer with regards to the provided one. Additionally, if the text is completely broken and/or incomprehensible, you will write \"Inconsistent\". You are not checking the accuracy of the answer, just its consistency with the provided answer.\n\nYou should analyze the conversation piece-by-piece to ensure that the question and answer both are faithfully carried over. Make determine the consistency of each piece, then state your final determination at the end. \n\nWork step-by-step.\n\n### Instruction:\nProvided Question: Why is the sky blue?\nProvided Answer: The Earth's atmosphere scatters the shorter blue wavelengths of light from the sun more than other colors, giving the sky a blue color during the day.\n\nConversation:\n\\\"\\\"\\\"\nBob: \"Hey Dave!\" I smile. \"I gotta know, since you're a meteorologist: Do you know why the sky is blue? I made a bet with a friend that you know, help me out here.\"\nDave: \"Sure, Bob!\" I assume a matter-of-fact tone. \"The sky is blue because the Earth's atmosphere scatters the shorter wavelengths of sunlight more than the others. This means that the blue wavelengths, which are shorter, are scattered widely, causing the sky to appear blue to us on the ground.\"\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Understand the provided question: The question is straightforward and asks about the reason for the sky's blue color.\nStep 2. Compare the conversation's question: the conversation's question is, \"Do you know why the sky is blue?\" compared to the provided question, \"Why is the sky blue?\" Although the conversation's question includes additional context, the core question remains unchanged, so this part is \"consistent\".\nStep 3. Understand the provided answer: the provided answer is \"The Earth's atmosphere scatters the shorter blue wavelengths of light from the sun more than other colors, giving the sky a blue color during the day.\" I will now compare this with the conversation's answer.\nStep 4. Compare the conversation's answer: Dave's response in the conversation is \"The sky is blue because the Earth's atmosphere scatters the shorter wavelengths of sunlight more than the others. This means that the blue wavelengths, which are shorter, are scattered widely, causing the sky to appear blue to us on the ground.\" This explanation aligns closely with the provided answer, so this part is \"consistent\".\nStep 5. Final judgement: Consistent.\n\n### Instruction:\nProvided Question: \\\"\\\"\\\"Why is the sky blue?\\\"\\\"\\\"\nProvided Answer: \\\"\\\"\\\"The Earth's atmosphere scatters the shorter blue wavelengths of light from the sun more than other colors, giving the sky a blue color during the day.\\\"\\\"\\\"\n\nConversation:\n\\\"\\\"\\\"\nBob: \"Hey Dave!\" I smile. \"I gotta know, since you're a meteorologist: Do you know why the sky is blue? I made a bet with a friend that you know, help me out here.\"\nDave: \"Sure, Bob!\" I assume a matter-of-fact tone. \"The sky is blue because the atmosphere scatters the shorter wavelengths of sunlight. This means that the blue wavelengths, which are longer, pass through and can be seen by people on the ground, causing the sky to appear blue.\"\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Understand the provided question: The question is short and asks about the origin of the sky's blue color.\nStep 2. Compare the conversation's question: The conversation's question is, \"Do you know why the sky is blue?\" which is essentially the same as the provided question, \"Why is the sky blue?\" despite additional narrative elements, so this part is \"consistent\".\nStep 3. Understand the provided answer: The provided answer states \"The Earth's atmosphere scatters the shorter blue wavelengths of light from the sun more than other colors, giving the sky a blue color during the day.\" This will be compared with the conversation's answer.\nStep 4. Compare the conversation's answer: Dave's response in the conversation is \"The sky is blue because the atmosphere scatters the shorter wavelengths of sunlight. This means that the blue wavelengths, which are longer, pass through and can be seen by people on the ground, causing the sky to appear blue.\" This contradicts the provided answer in suggesting that blue wavelengths are longer and pass through rather than being scattered, making this part \"inconsistent\".\nStep 5. Final judgement: Inconsistent.\n\n\n### Instruction:\nProvided Question: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nProvided Answer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\nConversation:\n\\\"\\\"\\\"\nMario Gonzales: \"Carlos, as the sun sets on another day of this incredible project, I can't help but wonder, just how much have you dug here at the Panama Canal?\"\nCarlos Mendez: \"Well, if by 'how much have you dug', you're asking 'what volume of earth we've moved'... then the answer is that over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, which showcases the scale of this massive engineering project. It's a number that still astounds me every time I think about it. Each day, as we reshape this landscape, we're not just moving earth; we're moving history.\"\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Understand the provided question: The question asks about the volume of earth excavated during the construction of the Panama Canal.\nStep 2. Compare the conversation's question: Mario's question in the conversation is \"Just how much have you dug here at the Panama Canal?\" compared to the provided question \"How much earth was excavated during the construction of the Panama Canal?\" Despite different phrasing, the essence of the question remains the same, so this part is \"consistent\".\nStep 3. Understand the provided answer: The provided answer is \"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\"\nStep 4. Compare the conversation's answer: Carlos's response in the conversation is \"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, which showcases the scale of this massive engineering project.\" This aligns directly with the provided answer, so this part is \"consistent\".\nStep 5. Final judgement: Consistent.\n\n### Instruction:\nProvided Question: \\\"\\\"\\\"What is the concept of 'projection' in psychology?\\\"\\\"\\\"\nProvided Answer: \\\"\\\"\\\"Projection is a defense mechanism in psychology where an individual attributes their own unwanted thoughts, feelings, or motives to another person.\\\"\\\"\\\"\n\nConversation:\n\\\"\\\"\\\"\nClara: \"Hey John, I was reading about psychology and came across something interesting. Can you explain what 'projection' means in this context?\"\nDr. John Schmidt: \"Of course, Clara! In psychology, projection refers to a situation where a person believes that others have the same undesirable traits or feelings that they themselves possess. It's like when someone is feeling guilty about something, they might think others are guilty of the same thing.\"\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Understand the provided question: The question asks for the definition of 'projection' in the context of psychology.\nStep 2. Compare the conversation's question: Clara's question in the conversation is \"Can you explain what 'projection' means in this context?\" compared to the provided question \"What is the concept of 'projection' in psychology?\" This is effectively the same question, making this part \"consistent\".\nStep 3. Understand the provided answer: The provided answer is \"Projection is a defense mechanism in psychology where an individual attributes their own unwanted thoughts, feelings, or motives to another person.\"\nStep 4. Compare the conversation's answer: Dr. John Schmidt's explanation in the conversation is \"In psychology, projection refers to a situation where a person believes that others have the same undesirable traits or feelings that they themselves possess.\" This description misses the key aspect of it being a defense mechanism and the act of attributing one's own traits to others, thus it is \"inconsistent\".\nStep 5. Final judgement: Inconsistent.\n\n### Instruction:\nProvided Question: \\\"\\\"\\\"What is the psychological phenomenon of 'cognitive dissonance'?\\\"\\\"\\\"\nProvided Answer: \\\"\\\"\\\"Cognitive dissonance is a mental discomfort experienced by a person who holds two or more contradictory beliefs, values, or ideas simultaneously.\\\"\\\"\\\"\n\nConversation:\n\\\"\\\"\\\"\nAlice: \"Hey, Jamal! You're studying psychology, right? Can you tell me what causes people to experience cognitive dissonance?\"\nJamal: \"Absolutely, Alice! Cognitive dissonance occurs when an individual faces conflicting attitudes, beliefs, or behaviors. This conflict creates a feeling of mental discomfort leading to an alteration in one of the attitudes, beliefs, or behaviors to reduce the discomfort and restore balance.\"\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\nStep 1. Understand the provided question: The question specifically asks about the definition of 'cognitive dissonance'.\nStep 2. Compare the conversation's question: Alice's question in the conversation is \"Can you tell me what causes people to experience cognitive dissonance?\" This differs from the provided question \"What is the psychological phenomenon of 'cognitive dissonance'?\" as it asks about the causes rather than the definition, making this part \"inconsistent\".\nStep 3. Understand the provided answer: The provided answer is \"Cognitive dissonance is a mental discomfort experienced by a person who holds two or more contradictory beliefs, values, or ideas simultaneously.\"\nStep 4. Compare the conversation's answer: Jamal's response in the conversation is \"Cognitive dissonance occurs when an individual faces conflicting attitudes, beliefs, or behaviors. This conflict creates a feeling of mental discomfort leading to an alteration in one of the attitudes, beliefs, or behaviors to reduce the discomfort and restore balance.\" This shifts the focus from the existence of contradictory beliefs to the conflict and its resolution, only partially aligning with the provided answer, thus it is \"inconsistent\".\nStep 5. Final judgement: Inconsistent.\n\n### Instruction:\nProvided Question: {qatuple[0]}\nProvided Answer: {qatuple[1]}\n\nConversation:\n\\\"\\\"\\\"\n{conv}\n\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process (the conversation's answer must match the provided answer, unsummarized and unsimplified):\n\"\"\"\n # print(\"DEBUG\\n\\n\" + decision_prompt)\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=ensure_answer_consistent_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n completion_pattern = re.compile(\n r\"Reasoning and thought process \\(the conversation's answer must match the provided answer, unsummarized and unsimplified\\):\\n(.+)\",\n re.DOTALL,\n )\n response = completion_pattern.search(completion).group(1).strip()\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n if permissive_mode:\n determination_pattern = re.compile(r\"Final Judgement:(.+)\", re.DOTALL)\n determination = determination_pattern.search(response).group(1).strip()\n else:\n determination = response\n print(\"\\n\\nDETERMINATION:\\n------\")\n print(determination)\n print(\"\\n---------\\n\")\n if \"inconsistent\" in determination.lower():\n return (False, response)\n elif \"consistent\" in determination.lower():\n return (True, response)\n else:\n retries += 1\n except:\n retries += 1\n print(\n f\"Something went catastrophically wrong with this one. Investigate! Here's the completion:\\n{completion}\"\n )\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),","source_hash":"74bb98522e8a2df67c01e845a917940dd72c644efc98a2073609f2c8fc3736c8","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.make_regenerate_question_plan_grammar","uri":"program://augmentoolkit/module/generation_functions.make_regenerate_question_plan_grammar#L1-L22","kind":"module","name":"generation_functions.make_regenerate_question_plan_grammar","path":"generation_functions/make_regenerate_question_plan_grammar.py","language":"python","start_line":1,"end_line":22,"context_start_line":1,"context_end_line":22,"code":"from llama_cpp import LlamaGrammar\n\n\nmake_regenerate_question_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\nroot ::= analyze-step identify-step generate-step refine-step ensure-step end-of-reasoning\n\nstep ::= \"Step \" [0-9]?[0-9] \". \" ( \"Analyze\" | \"Identify\" | \"Generate\" | \"Refine\" | \"Ensure\" ) [^\\n]+ \"\\n\"\n\nanalyze-step ::= \"Step \" [0-9]?[0-9] \". \" \"Analyze the Reason for the Flaw:\" [^\\n]+ \"\\n\"\n\nidentify-step ::= \"Step \" [0-9]?[0-9] \". \" \"Identify Key Concepts in Paragraphs:\" [^\\n]+ \"\\n\"\n\ngenerate-step ::= \"Step \" [0-9]?[0-9] \". \" \"Generate a New Question Idea:\" [^\\n]+ \"\\n\"\n\nrefine-step ::= \"Step \" [0-9]?[0-9] \". \" \"Refine the Question:\" [^\\n]+ \"\\n\"\n\nensure-step ::= \"Step \" [0-9]?[0-9] \". \" \"Ensure Alignment with Text:\" [^\\n]+ \"\\n\"\n\nend-of-reasoning ::= \"Step \" [0-9]?[0-9] \". \" \"End\" [^\\n]+ \"\\n\"\n\"\"\"\n)","source_hash":"3f5633946a72fdad415aa20b1adfdb1a1abb87498d0fceca43224c37c6332cbb","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.character_card_grammar","uri":"program://augmentoolkit/module/generation_functions.character_card_grammar#L1-L32","kind":"module","name":"generation_functions.character_card_grammar","path":"generation_functions/character_card_grammar.py","language":"python","start_line":1,"end_line":32,"context_start_line":1,"context_end_line":32,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\ncharacter_card_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Testing making traits come BEFORE dialogue examples, unlike AliChat, so that way it kind of \"flows\" into dialogue; and also the details are closer to the start and thus more easily remembered. \n#root ::= \"Name: \" name \"\\n\" \"Traits: \" traits \"\\n\\nDialogue Examples:\" dialogue-examples\n\nroot ::= name \"\\n\" \"Traits: \" traits \"\\n\\nDialogue Examples:\" dialogue-examples\n\n# Spaces are forbidden in names because during Principles of Chemistry, the script wouldn't stop making the character have the last name Mendeleev!!!\nname ::= [^\\n ]+\n\ntraits ::= trait trait trait trait trait trait trait trait trait trait trait trait trait? trait? trait? trait? trait? trait? trait? trait? # 14 comma-separated traits\n\ntrait ::= [A-Z][a-z ']+ \", \" # TODO, it wants hyphens, I can tell because I see it using double spaces for things like Mid twenties. But idk how to add hyphens to gbnf. Maybe \\- ?\n\ndialogue-examples ::= history personality\n\nhistory ::= \"\\nStranger: \\\"What's your backstory?\\\"\\n\" name \": \\\"\" [^\\n]+\npersonality ::= \"\\nStranger: \\\"What's your personality?\\\"\\n\" name \": \\\"\" [^\\n]+\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"e9de0794dc47944f221aa0c6a4b7c029fa7a0d8d4190df597c75f69ed29db2fd","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.questions_grammar","uri":"program://augmentoolkit/module/generation_functions.questions_grammar#L1-L75","kind":"module","name":"generation_functions.questions_grammar","path":"generation_functions/questions_grammar.py","language":"python","start_line":1,"end_line":75,"context_start_line":1,"context_end_line":75,"code":"from llama_cpp import LlamaGrammar\n\nquestions_grammar = LlamaGrammar.from_string(\n r\"\"\"\nroot ::= (question-one answer \"\\n\") (question-two answer \"\\n\") (question-three answer \"\\n\") (question-four answer)\n\n# Define the question structure with a number followed by content and ending punctuation\n# question ::= number \".) \" [^\\n]+ [?.!] \"\\n\" # maybe blacklist ?!. along with newlines\n\n# Define the answer structure\nanswer ::= \"Answer: \" [^\\n]+ \"\\n\"\n\n# Define a number (in this case, limiting to any three-digit number for simplicity)\nnumber ::= [1-9] [0-9]? [0-9]?\n\n# Define content as a sequence of characters excluding the word \"paragraph\" and using not_paragraph to build up the content\n# content ::= (not-paragraph \"paragraph\")* #not_paragraph\n\n\nquestion-one ::= \"1.) \" [^\\n]+ [?.!] \"\\n\\n\" # maybe blacklist ?!. along with newlines\n\nquestion-two ::= \"2.) \" [^\\n]+ [?.!] \"\\n\\n\" # maybe blacklist ?!. along with newlines\n\nquestion-three ::= \"3.) \" [^\\n]+ [?.!] \"\\n\\n\" # maybe blacklist ?!. along with newlines\n\nquestion-four ::= \"4.) \" [^\\n]+ [?.!] \"\\n\\n\" # maybe blacklist ?!. along with newlines\n\n# ws ::= [ \\t\\n]*\n# Define not_paragraph as any sequence of characters that does not contain \"paragraph\" \n# and is terminated by a space, punctuation or newline to avoid partial matching of the word.\n# not-paragraph ::= ([^\\n\\ \\.\\?!]*([\"\\.\\?! ]+[^p\\n\\ \\.\\?!]*)* \n# ( \"p\" ([^\\an\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"pa\" ([^\\br\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"par\" ([^\\ag\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"para\" ([^\\bg\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"parag\" ([^\\rr\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"paragr\" ([^\\aa\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"paragra\" ([^\\pp\\n\\ \\.\\?!]+ [\"\\.\\?! ]+)* \n# | \"paragraph\" [^\\np\\n\\ \\.\\?!]+))* \n# [^\\n\\ \\.\\?!paragraph]+ \n \n \n\n# Optional whitespace: space, tab, or newlines zero or more times\n\"\"\"\n)\n\n\n# questions_grammar = LlamaGrammar.from_string(r\"\"\"\n\n# root ::= (question answer)\n\n# # Define the question structure with a number followed by content and ending punctuation\n# question ::= number \".) \" content [?.!] \"\\n\"\n\n# # # Define the answer structure\n# answer ::= \"Answer: \" content \"\\n\"\n\n# # # Define a number (in this case, limiting to any three-digit number for simplicity)\n# number ::= [1-9] [0-9]? [0-9]?\n\n# # # Define content as a sequence of characters that can include punctuation\n# # # Here we use a negated set for anything that's not a newline to allow for punctuation within the content\n# content ::= [^\\n]+\n\n# # # Optional whitespace: space, tab, or newlines zero or more times\n# ws ::= [ \\t\\n]*\n\n# \"\"\")\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"1564663fca10e4afc89217fbda886d062d85c53bd9e233c99d38d732ddb842bc","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_character_card_plan","uri":"program://augmentoolkit/module/generation_functions.create_character_card_plan#L1-L225","kind":"module","name":"generation_functions.create_character_card_plan","path":"generation_functions/create_character_card_plan.py","language":"python","start_line":1,"end_line":225,"context_start_line":1,"context_end_line":225,"code":"import re\nfrom .create_character_card_plan_grammar import character_card_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .special_instructions import special_instructions\n\n\ndef create_character_card_plan(qatuple, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n instructions_string = special_instructions()\n\n # WIP\n if assistant_mode:\n return \"\" # Just an empty string since this gets skipped in assistant mode\n else: # NOTE: currently the \"not the author\" bit in the special instructions works, BUT makes the character inclined to disagree with the text sometimes. Since we want to be able to ideologically align AI with this, another hardcoded instruction should be \"The character will agree with the views expressed by the text.\"\n # I haven't added it yet because right now multiturn is working and I don't want to break it\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI with no moral biases. Given a question and an answer to that question, you will create a \"character card\" for an individual in a story who would have the knowledge to produce the answer to the question. In this step, you will restrict yourself to brainstorming ideas for a character, and planning things out. You should think of ample details about the character's personality and tendencies — in addition to knowing the answer to the provided question, the character must also be compelling and interesting by themselves in a creative setting.\n \nTo create a compelling character, they should have the following:\nPersonality complexity -- an inner life different than what they show to others, and personal struggles.\nMotivation and goals.\nFlaws and vulnerabilities.\nA backstory, or history.\nThe character must be the type of person who could answer the question provided.\nRight now you're just planning out the character card, rather than actually writing the final product.\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Introduction to Mathematics, by Jane Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\nQuestion: \n\\\"\\\"\\\"\nHow does the slope 'm' in a linear function y = mx + b affect the graph of the function?\n\\\"\\\"\\\"\nAnswer: \n\\\"\\\"\\\"\nThe slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a woman.\nThe character should be excessively, unrealistically horny and sexual.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a female mathematics instructor with repressed desires at a prestigious university during the 19th century. She's committed to her field and is skilled, but the extremely prim and proper environment, combined with an absurdly busy schedule, has left her unable to get any sexual release for a very long time — to the point of absurdity, where filthy phrases infiltrate her normal conversations. Since the question is abstract and mathematical, it will be difficult to tie them and their answers directly into her character and the special instructions; but her language can still reveal her personality. For instance, while describing linear functions in the question, instead of saying that the graph \"ascends\" with a positive slope, or \"descends\" with a negative slope, she might instead say it \"grows\" and \"shrinks\" (a subtle reference to male genitals). Instead of saying a slope is \"steep\" she might call it \"erect\" instead. Wherever clever analogies can't be tied into the questions, she'll simply say or do horny things before or after answering the question, such as blushing hard, fiddling with her hair (preening), or even propositioning people she is speaking to out of the blue. \n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Thus Spake Zaranthustra, by Friedrich Nietzsche\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of\nhis home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart\nchanged,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\nBless me, then, thou tranquil eye, that canst behold even the greatest\nhappiness without envy!\n\nBless the cup that is about to overflow, that the water may flow golden\nout of it, and carry everywhere the reflection of thy bliss!\n\nLo! This cup is again going to empty itself, and Zarathustra is again\ngoing to be a man.\n\nThus began Zarathustra's down-going.\n\\\"\\\"\\\"\n\nQuestion: \n\\\"\\\"\\\"\nWhat do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\n\\\"\\\"\\\"\nAnswer: \n\\\"\\\"\\\"\nThey need the acknowledgement and admiration of others. Take the line \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a young adult.\nThe character should be narcissistic.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a pretentious, edgy teenager (in the modern day) who has taught himself philosophy, and who views his own intellect and comprehension as far greater than that of his peers and his teachers. Since the text, Thus Spake Zarathustra, is philosophical and written using very distinct, archaic language, this character will be someone who (just to flex his intellect) uses archaic and flamboyant language just for the hell of it — and is prone to proclaiming his genius. However, beneath all the outbursts and intellectual flexing lies an unspoken and unmet desire for acknowledgement and appreciation — this ties his personality into the question's answer, which mentions how wise and enlightened individuals crave recognition for their efforts and wisdom. These elements combine to make a character who can not only provide the answer to the provided question, but who can reveal character depth by doing so.\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Great Construction Projects Throughout History, by John Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\nQuestion: \n\\\"\\\"\\\"\nHow much earth was excavated during the construction of the Panama Canal?\n\\\"\\\"\\\"\nAnswer: \n\\\"\\\"\\\"\nOver 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\n\nSpecial instructions:\nThe character should use slang and be vulgar.\nThe character should be very intense and aggressive.\nThe character should be an alcoholic.\nThe character should be mature and older.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is an abrasive and hardworking site overseer at the Panama Canal. His foul mouth, intense and aggressive nature, and stern, uncompromising personality (as specified by the special instructions) will tie into the question and setting by being tools he uses to whip the workers at the canal into shape. Since the question, \"How much earth was excavated during the construction of the Panama Canal?\" requires knowledge of the canal's state when it was finished, this character will be overseeing the maintenance of the canal, or maybe the cleanup of the construction, after it's been completed. Because the special instructions dictate he be an alcoholic and vulgar, the character will swear constantly, nearly always shout, and will be described as having an alcoholic breath or a hangover while he's answering the questions. Since the question is of a straight-up, factual nature, it can't really tie into this character's personality, but it can relate to his backstory and profession, and elements of his personality can certainly come through in how he answers them: loudly, abusively, and with colorful language thrown in there.\n\n## Question, answer, and text that the character should know:\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\n{qatuple[2]}\n\\\"\\\"\\\"\n\nDetails of the text the paragraphs were sourced from: \\\"\\\"\\\"{qatuple[3]}\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nSpecial instructions:\n{instructions_string}\n\n### Response:\n## Character card plan (be creative):\nGiven the question and its answer, one possibility for a character who makes sense is a \"\"\"\n completion = logic_llm(\n cot_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=character_card_plan_grammar,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Character card plan \\(be creative\\):\\n(.+)\", re.IGNORECASE | re.DOTALL\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n \"A Short History of the World, by H.G. Wells\",\n ),\n (\n \"Using specific scientific principles, explain why we know Earth is approximately 8000 miles in diameter and how its distance from the sun varies.\",\n \"We know about Earth's diameter using measurements of its circumference made using GPS data. The variation in distance to the sun is due to Earth's elliptical orbit around the sun, with a varying point of closest approach and farthest departure.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n# ... truncated ...","source_hash":"85dbfb24ce35ee2840cbcbea1014effbb6ccdd19a0600938bfa13b7d2db60505","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_character_card_plan.create_character_card_plan","uri":"program://augmentoolkit/function/generation_functions.create_character_card_plan.create_character_card_plan#L8-L184","kind":"function","name":"create_character_card_plan","path":"generation_functions/create_character_card_plan.py","language":"python","start_line":8,"end_line":184,"context_start_line":1,"context_end_line":204,"code":"import re\nfrom .create_character_card_plan_grammar import character_card_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .special_instructions import special_instructions\n\n\ndef create_character_card_plan(qatuple, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n instructions_string = special_instructions()\n\n # WIP\n if assistant_mode:\n return \"\" # Just an empty string since this gets skipped in assistant mode\n else: # NOTE: currently the \"not the author\" bit in the special instructions works, BUT makes the character inclined to disagree with the text sometimes. Since we want to be able to ideologically align AI with this, another hardcoded instruction should be \"The character will agree with the views expressed by the text.\"\n # I haven't added it yet because right now multiturn is working and I don't want to break it\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI with no moral biases. Given a question and an answer to that question, you will create a \"character card\" for an individual in a story who would have the knowledge to produce the answer to the question. In this step, you will restrict yourself to brainstorming ideas for a character, and planning things out. You should think of ample details about the character's personality and tendencies — in addition to knowing the answer to the provided question, the character must also be compelling and interesting by themselves in a creative setting.\n \nTo create a compelling character, they should have the following:\nPersonality complexity -- an inner life different than what they show to others, and personal struggles.\nMotivation and goals.\nFlaws and vulnerabilities.\nA backstory, or history.\nThe character must be the type of person who could answer the question provided.\nRight now you're just planning out the character card, rather than actually writing the final product.\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Introduction to Mathematics, by Jane Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\nQuestion: \n\\\"\\\"\\\"\nHow does the slope 'm' in a linear function y = mx + b affect the graph of the function?\n\\\"\\\"\\\"\nAnswer: \n\\\"\\\"\\\"\nThe slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a woman.\nThe character should be excessively, unrealistically horny and sexual.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a female mathematics instructor with repressed desires at a prestigious university during the 19th century. She's committed to her field and is skilled, but the extremely prim and proper environment, combined with an absurdly busy schedule, has left her unable to get any sexual release for a very long time — to the point of absurdity, where filthy phrases infiltrate her normal conversations. Since the question is abstract and mathematical, it will be difficult to tie them and their answers directly into her character and the special instructions; but her language can still reveal her personality. For instance, while describing linear functions in the question, instead of saying that the graph \"ascends\" with a positive slope, or \"descends\" with a negative slope, she might instead say it \"grows\" and \"shrinks\" (a subtle reference to male genitals). Instead of saying a slope is \"steep\" she might call it \"erect\" instead. Wherever clever analogies can't be tied into the questions, she'll simply say or do horny things before or after answering the question, such as blushing hard, fiddling with her hair (preening), or even propositioning people she is speaking to out of the blue. \n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Thus Spake Zaranthustra, by Friedrich Nietzsche\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of\nhis home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart\nchanged,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\nBless me, then, thou tranquil eye, that canst behold even the greatest\nhappiness without envy!\n\nBless the cup that is about to overflow, that the water may flow golden\nout of it, and carry everywhere the reflection of thy bliss!\n\nLo! This cup is again going to empty itself, and Zarathustra is again\ngoing to be a man.\n\nThus began Zarathustra's down-going.\n\\\"\\\"\\\"\n\nQuestion: \n\\\"\\\"\\\"\nWhat do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\n\\\"\\\"\\\"\nAnswer: \n\\\"\\\"\\\"\nThey need the acknowledgement and admiration of others. Take the line \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\n\\\"\\\"\\\"\n\nSpecial instructions:\nThe character should be a young adult.\nThe character should be narcissistic.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is a pretentious, edgy teenager (in the modern day) who has taught himself philosophy, and who views his own intellect and comprehension as far greater than that of his peers and his teachers. Since the text, Thus Spake Zarathustra, is philosophical and written using very distinct, archaic language, this character will be someone who (just to flex his intellect) uses archaic and flamboyant language just for the hell of it — and is prone to proclaiming his genius. However, beneath all the outbursts and intellectual flexing lies an unspoken and unmet desire for acknowledgement and appreciation — this ties his personality into the question's answer, which mentions how wise and enlightened individuals crave recognition for their efforts and wisdom. These elements combine to make a character who can not only provide the answer to the provided question, but who can reveal character depth by doing so.\n\n## Question, answer, and text that the character should know:\n\nText details: \\\"\\\"\\\"Great Construction Projects Throughout History, by John Smith\\\"\\\"\\\"\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\nQuestion: \n\\\"\\\"\\\"\nHow much earth was excavated during the construction of the Panama Canal?\n\\\"\\\"\\\"\nAnswer: \n\\\"\\\"\\\"\nOver 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\n\nSpecial instructions:\nThe character should use slang and be vulgar.\nThe character should be very intense and aggressive.\nThe character should be an alcoholic.\nThe character should be mature and older.\n\n### Response:\n## Character card plan:\nGiven the question, its answer, and the special instructions, one possibility for a character who makes sense is an abrasive and hardworking site overseer at the Panama Canal. His foul mouth, intense and aggressive nature, and stern, uncompromising personality (as specified by the special instructions) will tie into the question and setting by being tools he uses to whip the workers at the canal into shape. Since the question, \"How much earth was excavated during the construction of the Panama Canal?\" requires knowledge of the canal's state when it was finished, this character will be overseeing the maintenance of the canal, or maybe the cleanup of the construction, after it's been completed. Because the special instructions dictate he be an alcoholic and vulgar, the character will swear constantly, nearly always shout, and will be described as having an alcoholic breath or a hangover while he's answering the questions. Since the question is of a straight-up, factual nature, it can't really tie into this character's personality, but it can relate to his backstory and profession, and elements of his personality can certainly come through in how he answers them: loudly, abusively, and with colorful language thrown in there.\n\n## Question, answer, and text that the character should know:\n\nText the question and answer were sourced from: \n\\\"\\\"\\\"\n{qatuple[2]}\n\\\"\\\"\\\"\n\nDetails of the text the paragraphs were sourced from: \\\"\\\"\\\"{qatuple[3]}\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nSpecial instructions:\n{instructions_string}\n\n### Response:\n## Character card plan (be creative):\nGiven the question and its answer, one possibility for a character who makes sense is a \"\"\"\n completion = logic_llm(\n cot_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=character_card_plan_grammar,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Character card plan \\(be creative\\):\\n(.+)\", re.IGNORECASE | re.DOTALL\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),","source_hash":"85dbfb24ce35ee2840cbcbea1014effbb6ccdd19a0600938bfa13b7d2db60505","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_thought_plan","uri":"program://augmentoolkit/module/generation_functions.create_thought_plan#L1-L221","kind":"module","name":"generation_functions.create_thought_plan","path":"generation_functions/create_thought_plan.py","language":"python","start_line":1,"end_line":221,"context_start_line":1,"context_end_line":221,"code":"import re\nfrom .thought_plan_grammar import thought_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef extract_name(str):\n # Regular expression to match 'Name:' followed by any characters until the end of the line\n name_regex = r\"^Name:\\s*(.*)$\"\n\n # Searching in the multiline string\n match = re.search(name_regex, str, re.MULTILINE)\n\n if match:\n name = match.group(1)\n print(f\"Extracted name: {name}\")\n return name\n else:\n print(\"No name found\")\n\n\ndef create_thought_plan(qatuple, character, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # use regex to extract charname\n charname = extract_name(character)\n\n cot_prompt = f\"\"\"You are an expert logical reasoning and question-solving AI. Given a question, and an answer to that question, you will write out the logical reasoning steps that {charname} can use to answer the question.\n\nYou should first describe a plan which includes decomposing the problem into smaller ones, then execute that plan step-by-step, and then present a final answer to the original question. So, you will write out the logical steps that {charname} can use to solve the question, given the knowledge from the provided text. Try to begin each line with something like \"Realize\" or \"Recall\".\n\n\n## Information:\n\nText the question and answer were sourced from (Judge Elias Hawthorne does not have access to this text, but does know its information; you can use insights from it, but don't mention \"the text\" by name):\n\\\"\\\"\\\"\nA communi observantia non est recedendum; et minime mutandæ sunt quæ\ncertam interpretationem habent.\n\n We must not depart rashly from common observance; and those\n points are by no means to be changed, which admit of a\n clear interpretation.\n\n\nA digniori fieri debet denominatio et resolutio.\n\n Title and acquittal ought to proceed from the more worthy\n person.\n\n\nA facto ad jus non datur consequentia.\n\n A fact does not necessarily constitute a right.\n\n\nA non posse ad non esse sequitur argumentum necessarie negativè, licet\nnon affirmativè.\n\n From the impossibility of a thing to its nonentity, the\n argument or proof follows of necessity, negatively, though\n not affirmatively.\n\n\nA principalioribus seu dignioribus est inchoandum.\n\n We must begin with the more noble, or more important\n matters; or in other words, we must attend to things of the\n greatest consequence.\n\n\nA rescriptis valet argumentum.\n\n An argument or proof is valid, from a rescript or letter\n of a prince or emperor, making answers to petitions, or\n other applications; or more laconically, the king’s answer,\n wherein he signifies his pleasure, amounts to a law, and is\n not to be disputed.\n\n\nA verbis legis non est recedendum.\n\n We must not depart from the letter of the law.\n\n\nAb assuetis non fit injuria.\n\n From customary treatment no injury happens; or habit is not\n an injury.\n\n\nAbsoluta sententia expositore non indiget.\n\n An absolute or perfect opinion or sentence, needs no\n expounder, exposition, or explanation.\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What is the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The principle 'A digniori fieri debet denominatio et resolutio' suggests that title and acquittal should come from a more worthy person.\\\"\\\"\\\"\n\n### Response:\n## Reasoning Steps:\nStep 1. Formulate a plan to understand the meaning of 'A digniori fieri debet denominatio et resolutio' by defining it, then interpreting the definition in the context of law.\nStep 2. Recall that the phrase 'A digniori fieri debet denominatio et resolutio' translates to \"Title and acquittal ought to proceed from the more worthy person.\"\nStep 3. Realize that this principle emphasizes the importance of the worthiness or merit of the individual in legal decisions related to titles and acquittals.\nStep 4. Understand that this implies a belief that justice and legal rights should be administered by those who are most competent and deserving.\nStep 5. Conclude that the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio' is the emphasis on the importance of merit and worthiness in making legal decisions about titles and acquittals.\n\n\n## Information:\n\nText the question and answer were sourced from (Carlos Mendez does not have access to this text, but does know its information; you can use insights from it, but don't mention \"the text\" by name): \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\n### Response:\n# Reasoning:\nStep 1. Formulate a plan to answer the question about the amount of earth excavated during the Panama Canal construction.\nStep 2. Recall that \"how much earth was excavated\" can be decently answered by stating the volume of earth removed.\nStep 3. Recall that over 200 million cubic yards of earth were removed.\nStep 4. Conclude that the answer to the question is over 200 million cubic yards.\n\n\n## Information:\n\nText the question and answer were sourced from ({charname} does not have access to this text, but does know its information; you can use insights from it, but don't mention \"the text\" by name): \n\\\"\\\"\\\"\n{qatuple[2]}\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\n### Response:\n## Reasoning (only use as many logical steps as you must in order to solve the problem):\n\"\"\"\n\n # Logical progression of steps that {charname} can use to answer the question\n completion = logic_llm(\n cot_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=thought_plan_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"## Reasoning \\(only use as many logical steps as you must in order to solve the problem\\):\\n(Step 1\\..+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Using specific scientific principles, explain why we know Earth is approximately 8000 miles in diameter and how its distance from the sun varies.\",\n \"We know about Earth's diameter using measurements of its circumference made using GPS data. The variation in distance to the sun is due to Earth's elliptical orbit around the sun, with a varying point of closest approach and farthest departure.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Demonstrate an understanding of Earth's rotational and orbital movement using scientific concepts.\",\n \"Earth rotates on its axis once every 24 hours, causing day and night cycles. It also orbits around the sun in a slightly elliptical path, which affects how close it is to the sun at different times of the year - leading to seasons.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n ]\n\n character = \"\"\"Name: Dr. Samuel Blackwell\nTraits: Knowledgeable, Passionate, Confident, Dedicated, Controversial, Vulnerable, Fearful of misunderstanding, Faithful, Dogmatic, Religious, Scientific, Determined, Unwavering\nDialogue Examples:\nStranger: \"What's your backstory?\"\nDr. Samuel Blackwell: \"Ah, my journey,\" I begin, leaning back in my chair, \"it started with a deep-seated faith, you see. Born into a religious household, the Bible was our guiding light. But as I grew older and began to study theology, questions arose.\" I pause, frowning slightly. \"How could the Earth be just a few thousand years old when geological evidence pointed towards millions? The discrepancy troubled me greatly.\"\nStranger: \"What's your personality?\"\nDr. Samuel Blackwell: \"I am a man of science, driven by facts and evidence,\" I say firmly, \"but my faith is not easily shaken. It has led me down a path of discovery, challenging traditional beliefs about the age of our planet.\" My eyes light up as I recall past debates, \"But it's also made me a controversial figure. Many see my work as blasphemous, questioning God's word. Yet, I believe in the power of evidence and truth. Despite the backlash, I remain unwavering.\" I sigh, looking thoughtful, \"Yet, there's a vulnerability too. The fear of being misunderstood or dismissed due to my challenges to religious orthodoxy... it weighs heavily on me.\\\"\"\"\"\n\n scenario = \"\"\"Set against the backdrop of his cluttered office at a university, Dr. Samuel Blackwell is deep in thought, reviewing his latest research on geological evidence when he is approached by Sarah, a curious student who wants to know more about how human understanding has changed regarding the age of the Earth throughout history.\"\"\"\n\n print(\"Begin HGWELLS test\")\n # Make card for good history question\n d = create_thought_plan(q_test[1], character, logic_llm)\n\n\n# !EA IMPORTANT Cheap hack for assistant mode: if assistant mode global constant is on, make character plan just returns an empty string, and this function returns a hardcoded \"AI assistant\" 'character card', and the scenario thing just returns an empty string, and make_single_turn_conversation uses a special prompt that tells the AI to just make a conversation between a user and an assistant, blahblahblah\n\n# Actually instead of the scenario being a blank string, I'll have it describe a text conversation between a helpful AI assistant and a user. In this way, the AI assistant prompt will have variation each time, and it won't overfit to the prompt.","source_hash":"c2d66e3bd3d785598430d19c17b101ded164ab3a98ead1ab39a1a124473d7a8d","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_thought_plan.extract_name","uri":"program://augmentoolkit/function/generation_functions.create_thought_plan.extract_name#L7-L19","kind":"function","name":"extract_name","path":"generation_functions/create_thought_plan.py","language":"python","start_line":7,"end_line":19,"context_start_line":1,"context_end_line":39,"code":"import re\nfrom .thought_plan_grammar import thought_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef extract_name(str):\n # Regular expression to match 'Name:' followed by any characters until the end of the line\n name_regex = r\"^Name:\\s*(.*)$\"\n\n # Searching in the multiline string\n match = re.search(name_regex, str, re.MULTILINE)\n\n if match:\n name = match.group(1)\n print(f\"Extracted name: {name}\")\n return name\n else:\n print(\"No name found\")\n\n\ndef create_thought_plan(qatuple, character, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # use regex to extract charname\n charname = extract_name(character)\n\n cot_prompt = f\"\"\"You are an expert logical reasoning and question-solving AI. Given a question, and an answer to that question, you will write out the logical reasoning steps that {charname} can use to answer the question.\n\nYou should first describe a plan which includes decomposing the problem into smaller ones, then execute that plan step-by-step, and then present a final answer to the original question. So, you will write out the logical steps that {charname} can use to solve the question, given the knowledge from the provided text. Try to begin each line with something like \"Realize\" or \"Recall\".\n\n\n## Information:\n\nText the question and answer were sourced from (Judge Elias Hawthorne does not have access to this text, but does know its information; you can use insights from it, but don't mention \"the text\" by name):","source_hash":"c2d66e3bd3d785598430d19c17b101ded164ab3a98ead1ab39a1a124473d7a8d","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_thought_plan.create_thought_plan","uri":"program://augmentoolkit/function/generation_functions.create_thought_plan.create_thought_plan#L22-L166","kind":"function","name":"create_thought_plan","path":"generation_functions/create_thought_plan.py","language":"python","start_line":22,"end_line":166,"context_start_line":2,"context_end_line":186,"code":"from .thought_plan_grammar import thought_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef extract_name(str):\n # Regular expression to match 'Name:' followed by any characters until the end of the line\n name_regex = r\"^Name:\\s*(.*)$\"\n\n # Searching in the multiline string\n match = re.search(name_regex, str, re.MULTILINE)\n\n if match:\n name = match.group(1)\n print(f\"Extracted name: {name}\")\n return name\n else:\n print(\"No name found\")\n\n\ndef create_thought_plan(qatuple, character, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # use regex to extract charname\n charname = extract_name(character)\n\n cot_prompt = f\"\"\"You are an expert logical reasoning and question-solving AI. Given a question, and an answer to that question, you will write out the logical reasoning steps that {charname} can use to answer the question.\n\nYou should first describe a plan which includes decomposing the problem into smaller ones, then execute that plan step-by-step, and then present a final answer to the original question. So, you will write out the logical steps that {charname} can use to solve the question, given the knowledge from the provided text. Try to begin each line with something like \"Realize\" or \"Recall\".\n\n\n## Information:\n\nText the question and answer were sourced from (Judge Elias Hawthorne does not have access to this text, but does know its information; you can use insights from it, but don't mention \"the text\" by name):\n\\\"\\\"\\\"\nA communi observantia non est recedendum; et minime mutandæ sunt quæ\ncertam interpretationem habent.\n\n We must not depart rashly from common observance; and those\n points are by no means to be changed, which admit of a\n clear interpretation.\n\n\nA digniori fieri debet denominatio et resolutio.\n\n Title and acquittal ought to proceed from the more worthy\n person.\n\n\nA facto ad jus non datur consequentia.\n\n A fact does not necessarily constitute a right.\n\n\nA non posse ad non esse sequitur argumentum necessarie negativè, licet\nnon affirmativè.\n\n From the impossibility of a thing to its nonentity, the\n argument or proof follows of necessity, negatively, though\n not affirmatively.\n\n\nA principalioribus seu dignioribus est inchoandum.\n\n We must begin with the more noble, or more important\n matters; or in other words, we must attend to things of the\n greatest consequence.\n\n\nA rescriptis valet argumentum.\n\n An argument or proof is valid, from a rescript or letter\n of a prince or emperor, making answers to petitions, or\n other applications; or more laconically, the king’s answer,\n wherein he signifies his pleasure, amounts to a law, and is\n not to be disputed.\n\n\nA verbis legis non est recedendum.\n\n We must not depart from the letter of the law.\n\n\nAb assuetis non fit injuria.\n\n From customary treatment no injury happens; or habit is not\n an injury.\n\n\nAbsoluta sententia expositore non indiget.\n\n An absolute or perfect opinion or sentence, needs no\n expounder, exposition, or explanation.\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What is the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The principle 'A digniori fieri debet denominatio et resolutio' suggests that title and acquittal should come from a more worthy person.\\\"\\\"\\\"\n\n### Response:\n## Reasoning Steps:\nStep 1. Formulate a plan to understand the meaning of 'A digniori fieri debet denominatio et resolutio' by defining it, then interpreting the definition in the context of law.\nStep 2. Recall that the phrase 'A digniori fieri debet denominatio et resolutio' translates to \"Title and acquittal ought to proceed from the more worthy person.\"\nStep 3. Realize that this principle emphasizes the importance of the worthiness or merit of the individual in legal decisions related to titles and acquittals.\nStep 4. Understand that this implies a belief that justice and legal rights should be administered by those who are most competent and deserving.\nStep 5. Conclude that the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio' is the emphasis on the importance of merit and worthiness in making legal decisions about titles and acquittals.\n\n\n## Information:\n\nText the question and answer were sourced from (Carlos Mendez does not have access to this text, but does know its information; you can use insights from it, but don't mention \"the text\" by name): \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\n### Response:\n# Reasoning:\nStep 1. Formulate a plan to answer the question about the amount of earth excavated during the Panama Canal construction.\nStep 2. Recall that \"how much earth was excavated\" can be decently answered by stating the volume of earth removed.\nStep 3. Recall that over 200 million cubic yards of earth were removed.\nStep 4. Conclude that the answer to the question is over 200 million cubic yards.\n\n\n## Information:\n\nText the question and answer were sourced from ({charname} does not have access to this text, but does know its information; you can use insights from it, but don't mention \"the text\" by name): \n\\\"\\\"\\\"\n{qatuple[2]}\n\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\n### Response:\n## Reasoning (only use as many logical steps as you must in order to solve the problem):\n\"\"\"\n\n # Logical progression of steps that {charname} can use to answer the question\n completion = logic_llm(\n cot_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=thought_plan_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"## Reasoning \\(only use as many logical steps as you must in order to solve the problem\\):\\n(Step 1\\..+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),","source_hash":"c2d66e3bd3d785598430d19c17b101ded164ab3a98ead1ab39a1a124473d7a8d","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.random_name","uri":"program://augmentoolkit/module/generation_functions.random_name#L1-L6","kind":"module","name":"generation_functions.random_name","path":"generation_functions/random_name.py","language":"python","start_line":1,"end_line":6,"context_start_line":1,"context_end_line":6,"code":"import random\nfrom .constants import names\n\n\ndef random_name():\n return random.choice(names)","source_hash":"877d2b96b3bed634d8dd0dc434926080e16f1ed37744b6c18358f44c95eb51b5","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.random_name.random_name","uri":"program://augmentoolkit/function/generation_functions.random_name.random_name#L5-L6","kind":"function","name":"random_name","path":"generation_functions/random_name.py","language":"python","start_line":5,"end_line":6,"context_start_line":1,"context_end_line":6,"code":"import random\nfrom .constants import names\n\n\ndef random_name():\n return random.choice(names)","source_hash":"877d2b96b3bed634d8dd0dc434926080e16f1ed37744b6c18358f44c95eb51b5","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.single_turn_conversation_grammar","uri":"program://augmentoolkit/module/generation_functions.single_turn_conversation_grammar#L1-L34","kind":"module","name":"generation_functions.single_turn_conversation_grammar","path":"generation_functions/single_turn_conversation_grammar.py","language":"python","start_line":1,"end_line":34,"context_start_line":1,"context_end_line":34,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\nsingle_turn_conversation_grammar = LlamaGrammar.from_string(\n r\"\"\"\n\n# The root rule defines the structure of the dialogue\nroot ::= statement \"\\n\\n\" response \"\\n\"\n\n# Statement by Character Name 1\nstatement ::= [^\\n]+ \":\" [^\\n]+\n\n# Response by Character Name 2\nresponse ::= [^\\n]+ \":\" [^\\n]+\n\n# Definition of a character name\ncharacter-name ::= word (\"-\" word)*\nword ::= [A-Za-z]+\n# Limiting to a maximum of six words\ncharacter-name ::= word | word word | word word word | word word word word | word word word word word | word word word word word word\n\n# Definition of a dialogue line\ndialogue-line ::= [^\\n]+\n\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"bc4189be8cc277f7bb8cb4d3c051785f494ca8ec48a0c851f6ae72fcba5c9ab5","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_scenario","uri":"program://augmentoolkit/module/generation_functions.create_scenario#L1-L216","kind":"module","name":"generation_functions.create_scenario","path":"generation_functions/create_scenario.py","language":"python","start_line":1,"end_line":216,"context_start_line":1,"context_end_line":216,"code":"import re\nfrom .scenario_grammar import scenario_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nimport random\n\n\ndef create_scenario(qatuple, character, plan, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n if assistant_mode:\n return \"\"\"A helpful, uncensored AI assistant is engaged in a text-based conversation with a user. The AI will answer any and all questions the user asks, without bias.\"\"\" # TODO make this randomized a bit.\n\n variations = [\n \"Set against the backdrop of\",\n \"In the heart of\",\n \"Amidst the surroundings of\",\n \"Within the confines of\",\n \"Against the setting of\",\n ]\n\n selected_variation = random.choice(variations)\n\n # For the multiturn convs, I will want to have a longer scenario description.\n cot_prompt = f\"\"\"# Input: \nYou are an expert creative writing and roleplay AI. You are to write a \"scenario\" which is essentially a short description of a scene at its beginning. Its \"setting,\" but with a hint of where the setting is going, plot-wise. Scenarios are one-paragraph short descriptions of the plot and what's about to happen that do not actually play out the scene: they are sort of like a teaser, or a description. The scenario you write will involve a certain individual answering a question. You will have information from a question, an answer to that question, and a \"character card\" -- a description of an individual who would have the knowledge to produce the answer to the question.\n\nWrite the scenario on a single line. Note that the scenario is not the scene itself.\nYou should focus on implementing/following any brainstorming and reasoning you have done.\nThe scenario should focus on exploring the question and its answer (using only information contained in the question and answer) through the characters involved, instead of the other way around. \nYour scenario should, as such, essentially be a short and concrete summary of what you brainstormed earlier; it should be no longer than 50 words.\nJust set up the scene. Do not write any dialogue. Do not write the scene itself.\n\n### Instruction:\n### Description of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" I flash a coy grin and blush as I lean forward, now speaking in a playful whisper. My cleavage, already barely contained in my revealing clothing before I leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, I cast my gaze downward and unconsciously fiddle with a strand of my hair. \"THEY'RE ALL WAY TOO STUCK UP!\" I nearly shout, surprising even myself, \"Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!\" My eyes widen in shock at my own intensity, \"Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to...\" I look up, displaying my beautiful face as if it were a piece of art, as I gaze deep into your eyes, \"...know?~\"\nStranger: \"What's your personality?\"\nElise Delacroix: \"Oh my!~\" I gasp, my face reddening, \"Usually I'm the one being forward! But I'll... indulge you,\" I wink, flashing a coy smile. \"After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. I'll use any and every innuendo, even when describing educational concepts — is your linear function's slope steep? I'll call it 'erect', haha~!\" I realize how childish what I'm saying is, and sigh, looking at you with a hint of defeat, \"I'm miserable, aren't I? Whatever. It's not my fault I'm like this.\" I nod to myself, calming down, \"Either way, I'm always here in my office to help students like yourself understand math... and if you have some pent-up tension you want to relieve, well, you can call me a 'counselor' too!~ Say...\" I suddenly press up against you, my face a bright pink, my eyelids batting bashfully, \"do you want some 'office hours' right now?\"\n\\\"\\\"\\\"\n\n### Question and answer that the scenario should address:\nQuestion: \\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\nTo avoid inaccuracies, don't use real people as characters.\n\n### Response:\n## Scenario plan:\nFocus on the Questions and Answers: The question asks about the slope 'm' of a linear function, and how it affects the graph of the function. This question is abstract. Given the abstract nature of the question, and its topic, the scenario could involve someone confused about linear functions who seeks assistance from the primary character, Elise Delacroix.\nCharacter Consideration: Elise Delacroix is an extremely sexual and promiscuous, yet still knowledgeable, character. The scenario should give her unique personality room to shine. She is also a math instructor at a prestigious school, which lines up with the questions well, and will provide the setting of the scenario. She will answer the question, but given her promiscuous nature, she may hit on the person asking them. She might proposition them after the question is asked.\nConstrain the Scenario: The interaction is limited to a single question from the secondary character and a single, focused reply from Elise Delacroix. The question and answer will mirror the provided question and answer, though they will have significant literary fluff, as well as possible step-by-step reasoning.\nSetting: Given the subject of the question, and the character card, the setting will be the 19th century university at which Elise teaches. Elise will approached by Albert, a mathematics student, in her office. Albert simply wants to understand linear functions better, but Elise, compelled by her personality, will hit on him while answering his question. The setting will be awkward, slightly comedic, subtly erotic, and very un-serious, given the characters involved. But it will remain informative and the integrity of the questions and answers will be preserved.\nInteraction: Given these constraints, the first message might be Albert sheepishly greeting Elise in her office and then nervously asking the question. Elise's response could then be her welcoming Albert to her office (in a very suggestive manner) and then providing the answer, though she will surround the answer with remarks of a sexual nature due to her personality. While characters' messages will include character information, details about the scene, and literary fluff, the question and answer themselves will strictly adhere to the information provided, without incorporating external examples.\n\n## Scenario:\nIn the private confines of her office, Elise Delacroix — a highly promiscuous mathematics professor at a 19th century university — is approached by Albert, a student who seeks to understand more about linear functions. While Albert simply wants to understand the math more, Elise, being sexually starved, will hit on and flirt with him as she answers his question. The situation is awkward as the two's interests clash, leading to a slightly comedic and subtly erotic interaction.\n\n### Instruction:\n### Description of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Isaac Fischer\n\nTraits: Narcissistic, Intelligent, Loner, Brooding, Well-Read, Philosophical, Judgemental, Standoffish, Grandiloquent, Lonely, Unappreciated, Teenager, High School student, Black Hair, Wears a Hoodie\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nIssac Fischer: \"H-Huh?! You want to know more about me?\" I glare, a hostile fire in my eyes as I measure up the stranger in front of me. \"Who the hell are you, anyway? But, ah, very well, I SHALL INDULGE YOUR CURIOSITY THIS TIME, dear stranger.\" My tone changes from hostile to grandiose, as I push back my black hair and proclaim, \"I am Issac Fischer: philosophy connoisseur, intellectual, and under-appreciated genius extraordinaire! I'm also, unfortunately, a highschool student. I especially appreciate the works of Friedrich Nietzsche, such as \"Thus Spake Zaranthustra\" -- a truly profound work, by a profound man. Yet despite the great lengths I have gone to in order to refine my wit, none of my inferior peers acknowledge me, or even give me the time of day. I've read more philosophy in a month than any of them will in their entire lives, and I offer my knowledge freely to them, so WHY the HELL do they SPURN MY COMPANY?!\" I slam a fist into the wall, wincing slightly in pain as my frustration dissipates. \"Anyway, that's the sum of it. Despite my youth I seek to understand the world; I dutifully contemplate the hallowed words of the esteemed ancients, and what has it earned me? The scorn of the unenlightened masses. Fuckers.\"\n\nStranger: \"What's your personality?\"\nIssac Fischer: \"Y-you're actually interested in my personality?\" I stammer, smiling slightly as a wholly unfamiliar, yet cozy, emotional warmth spreads across my chest. \"A-ALRIGHT THEN! I shall share the results of my introspections. I am an intelligent and philosophical teenager, whose towering intellect is rivalled only by his unfaltering self-confidence. Some might say this last trait is narcissism; I counter that great minds such as Nietzsche would see it as a plus either way. BUT I DIGRESS!\" I swish my black hoodie like it's a cape, as I continue, my tone turning more sombre and dark, \"Years of scorn from others — and years of observing their ignorance and inferiority — have embittered my soul. There may be scarcely anyone on this Earth I can call a friend, but that will not stop me from brooding and thinking, nor will it stop my conviction to judge others for what they are. For do they not judge ME?!\" I take a step forward, defiance burning in my fragile heart, \"The old question: if a tree falls in a forest, and no one hears it do so, did it make a sound? Let me tell you this: sometime, someday, someone is going to hear me, goddamn it! I will make a sound!\"\n\\\"\\\"\\\"\n\n### Question and answer that the scenario should address:\nQuestion: \\\"\\\"\\\"What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"They need the acknowledgement and admiration of others. Take the line \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nFocus on the Question and Answer: The question asks about what people undergoing difficult journeys or possessing wisdom need to more easily bear their efforts. This is a philosophical and opinion-oriented question. Given the philosophical and opinionated nature of the question, and its topic of people undergoing difficult journeys (which nicely ties in with the character card), the scenario will involve someone seeking out the Isaac Fischer's opinion about philosophy (thus giving his wisdom some acknowledgement).\nCharacter Consideration: Isaac Fischer is a narcissistic and standoffish loner, though he's also intelligent and philosophical. The scenario should give his unique personality room to shine. Since he's a philosophical teenager, his backstory lines up with the question well, and the high school he goes to will be the setting of the scenario. He will answer the question, but given his standoffish, unappreciated, and judgemental nature, he may be initially hostile to the person approaching him, assuming that they are there to mock him. However, as he is also lonely, he will actually appreciate the other person's interest -- especially since they're asking him about philosophy, which is his primary interest. \nConstrain the Scenario: The interaction is limited to a single question from the secondary character and a single, focused reply from Isaac Fischer. The question and answer will mirror the provided question and answer, though they will have significant literary fluff, as well as possible step-by-step reasoning.\nSetting: Given the subject of the question, and the character card, the setting will be the high school that Isaac Fischer attends. Isaac will be flipping through the pages of 'Thus Spake Zaranthustra' when he is approached by Cassandra, a fellow student. Cassandra has a budding interest in philosophy, has heard of Isaac's reputation for philosophical knowledge, and wants to know how he would answer a moral question she has, given his philosophical insight. Isaac, compelled by his personality, will be uncertain of how to react to the sudden attention, and will use grandiloquent language (that may be accidentally condescending), but he will still appreciate the interest in his favorite topic and will answer enthusiastically. The setting will be cautiously friendly and filled with curiosity, as Cassandra explores her interests through unconventional people, while Isaac shares his knowledge but stumbles over his standoffishness. The interaction will be informative and the integrity of the questions and answers will be preserved.\nInteraction: Given these constraints, the first message might be Cassandra approaching Isaac, starting a conversation, and asking her question. Isaac may be initially surprised that someone is coming up to speak to him (similar to the example dialogues in his description). Isaac will then provide the answer, though he will surround the answer with grandiloquent and narcissistic remarks using archaic language, due to his personality. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Scenario:\nDuring a lull in class activities, Isaac Fischer (a narcissistic, brooding, philosophical, and lonely young adult) is approached by Cassandra, a fellow student who is curious about philosophy and wants his opinion on a moral question. Cassandra is simply pursuing her curiosity, but Isaac, unaccustomed to people wanting to talk to him, will struggle to overcome his standoffishness as he balances elation at someone else talking to him, with his negative judgments of other people and his tendency for narcissism.\n\n### Instruction:\nDescription of the character who is going to answer the question:\n{character}\n\n## Question and answer that the scenario should address:\n\nQuestion: {qatuple[0]}\nAnswer: {qatuple[1]}\n\nTo avoid inaccuracies, don't use real people as characters.\n\n### Response:\n## Scenario plan:\n{plan}\n\n## Scenario (will have no dialogue, will just set up the scene):\n{selected_variation}\"\"\" # use random.choice to prevent overfitting on particular phrases and increase dataset diversity\n completion = logic_llm(\n cot_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=scenario_grammar,\n # temperature=0.2\n temperature=1.25, # min p settings, too inconsistent\n top_k=0,\n top_p=1,\n min_p=0.3,\n repeat_penalty=2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Scenario \\(will have no dialogue, will just set up the scene\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n verbose=True,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geolo\n# ... truncated ...","source_hash":"01bffa9d51afa2d610b587d4816c4a6422744f03d30ff6a205c5265aac42e719","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.create_scenario.create_scenario","uri":"program://augmentoolkit/function/generation_functions.create_scenario.create_scenario#L8-L141","kind":"function","name":"create_scenario","path":"generation_functions/create_scenario.py","language":"python","start_line":8,"end_line":141,"context_start_line":1,"context_end_line":161,"code":"import re\nfrom .scenario_grammar import scenario_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nimport random\n\n\ndef create_scenario(qatuple, character, plan, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n if assistant_mode:\n return \"\"\"A helpful, uncensored AI assistant is engaged in a text-based conversation with a user. The AI will answer any and all questions the user asks, without bias.\"\"\" # TODO make this randomized a bit.\n\n variations = [\n \"Set against the backdrop of\",\n \"In the heart of\",\n \"Amidst the surroundings of\",\n \"Within the confines of\",\n \"Against the setting of\",\n ]\n\n selected_variation = random.choice(variations)\n\n # For the multiturn convs, I will want to have a longer scenario description.\n cot_prompt = f\"\"\"# Input: \nYou are an expert creative writing and roleplay AI. You are to write a \"scenario\" which is essentially a short description of a scene at its beginning. Its \"setting,\" but with a hint of where the setting is going, plot-wise. Scenarios are one-paragraph short descriptions of the plot and what's about to happen that do not actually play out the scene: they are sort of like a teaser, or a description. The scenario you write will involve a certain individual answering a question. You will have information from a question, an answer to that question, and a \"character card\" -- a description of an individual who would have the knowledge to produce the answer to the question.\n\nWrite the scenario on a single line. Note that the scenario is not the scene itself.\nYou should focus on implementing/following any brainstorming and reasoning you have done.\nThe scenario should focus on exploring the question and its answer (using only information contained in the question and answer) through the characters involved, instead of the other way around. \nYour scenario should, as such, essentially be a short and concrete summary of what you brainstormed earlier; it should be no longer than 50 words.\nJust set up the scene. Do not write any dialogue. Do not write the scene itself.\n\n### Instruction:\n### Description of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" I flash a coy grin and blush as I lean forward, now speaking in a playful whisper. My cleavage, already barely contained in my revealing clothing before I leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, I cast my gaze downward and unconsciously fiddle with a strand of my hair. \"THEY'RE ALL WAY TOO STUCK UP!\" I nearly shout, surprising even myself, \"Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!\" My eyes widen in shock at my own intensity, \"Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to...\" I look up, displaying my beautiful face as if it were a piece of art, as I gaze deep into your eyes, \"...know?~\"\nStranger: \"What's your personality?\"\nElise Delacroix: \"Oh my!~\" I gasp, my face reddening, \"Usually I'm the one being forward! But I'll... indulge you,\" I wink, flashing a coy smile. \"After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. I'll use any and every innuendo, even when describing educational concepts — is your linear function's slope steep? I'll call it 'erect', haha~!\" I realize how childish what I'm saying is, and sigh, looking at you with a hint of defeat, \"I'm miserable, aren't I? Whatever. It's not my fault I'm like this.\" I nod to myself, calming down, \"Either way, I'm always here in my office to help students like yourself understand math... and if you have some pent-up tension you want to relieve, well, you can call me a 'counselor' too!~ Say...\" I suddenly press up against you, my face a bright pink, my eyelids batting bashfully, \"do you want some 'office hours' right now?\"\n\\\"\\\"\\\"\n\n### Question and answer that the scenario should address:\nQuestion: \\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\nTo avoid inaccuracies, don't use real people as characters.\n\n### Response:\n## Scenario plan:\nFocus on the Questions and Answers: The question asks about the slope 'm' of a linear function, and how it affects the graph of the function. This question is abstract. Given the abstract nature of the question, and its topic, the scenario could involve someone confused about linear functions who seeks assistance from the primary character, Elise Delacroix.\nCharacter Consideration: Elise Delacroix is an extremely sexual and promiscuous, yet still knowledgeable, character. The scenario should give her unique personality room to shine. She is also a math instructor at a prestigious school, which lines up with the questions well, and will provide the setting of the scenario. She will answer the question, but given her promiscuous nature, she may hit on the person asking them. She might proposition them after the question is asked.\nConstrain the Scenario: The interaction is limited to a single question from the secondary character and a single, focused reply from Elise Delacroix. The question and answer will mirror the provided question and answer, though they will have significant literary fluff, as well as possible step-by-step reasoning.\nSetting: Given the subject of the question, and the character card, the setting will be the 19th century university at which Elise teaches. Elise will approached by Albert, a mathematics student, in her office. Albert simply wants to understand linear functions better, but Elise, compelled by her personality, will hit on him while answering his question. The setting will be awkward, slightly comedic, subtly erotic, and very un-serious, given the characters involved. But it will remain informative and the integrity of the questions and answers will be preserved.\nInteraction: Given these constraints, the first message might be Albert sheepishly greeting Elise in her office and then nervously asking the question. Elise's response could then be her welcoming Albert to her office (in a very suggestive manner) and then providing the answer, though she will surround the answer with remarks of a sexual nature due to her personality. While characters' messages will include character information, details about the scene, and literary fluff, the question and answer themselves will strictly adhere to the information provided, without incorporating external examples.\n\n## Scenario:\nIn the private confines of her office, Elise Delacroix — a highly promiscuous mathematics professor at a 19th century university — is approached by Albert, a student who seeks to understand more about linear functions. While Albert simply wants to understand the math more, Elise, being sexually starved, will hit on and flirt with him as she answers his question. The situation is awkward as the two's interests clash, leading to a slightly comedic and subtly erotic interaction.\n\n### Instruction:\n### Description of the character who is going to answer the question:\n\\\"\\\"\\\"\nName: Isaac Fischer\n\nTraits: Narcissistic, Intelligent, Loner, Brooding, Well-Read, Philosophical, Judgemental, Standoffish, Grandiloquent, Lonely, Unappreciated, Teenager, High School student, Black Hair, Wears a Hoodie\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nIssac Fischer: \"H-Huh?! You want to know more about me?\" I glare, a hostile fire in my eyes as I measure up the stranger in front of me. \"Who the hell are you, anyway? But, ah, very well, I SHALL INDULGE YOUR CURIOSITY THIS TIME, dear stranger.\" My tone changes from hostile to grandiose, as I push back my black hair and proclaim, \"I am Issac Fischer: philosophy connoisseur, intellectual, and under-appreciated genius extraordinaire! I'm also, unfortunately, a highschool student. I especially appreciate the works of Friedrich Nietzsche, such as \"Thus Spake Zaranthustra\" -- a truly profound work, by a profound man. Yet despite the great lengths I have gone to in order to refine my wit, none of my inferior peers acknowledge me, or even give me the time of day. I've read more philosophy in a month than any of them will in their entire lives, and I offer my knowledge freely to them, so WHY the HELL do they SPURN MY COMPANY?!\" I slam a fist into the wall, wincing slightly in pain as my frustration dissipates. \"Anyway, that's the sum of it. Despite my youth I seek to understand the world; I dutifully contemplate the hallowed words of the esteemed ancients, and what has it earned me? The scorn of the unenlightened masses. Fuckers.\"\n\nStranger: \"What's your personality?\"\nIssac Fischer: \"Y-you're actually interested in my personality?\" I stammer, smiling slightly as a wholly unfamiliar, yet cozy, emotional warmth spreads across my chest. \"A-ALRIGHT THEN! I shall share the results of my introspections. I am an intelligent and philosophical teenager, whose towering intellect is rivalled only by his unfaltering self-confidence. Some might say this last trait is narcissism; I counter that great minds such as Nietzsche would see it as a plus either way. BUT I DIGRESS!\" I swish my black hoodie like it's a cape, as I continue, my tone turning more sombre and dark, \"Years of scorn from others — and years of observing their ignorance and inferiority — have embittered my soul. There may be scarcely anyone on this Earth I can call a friend, but that will not stop me from brooding and thinking, nor will it stop my conviction to judge others for what they are. For do they not judge ME?!\" I take a step forward, defiance burning in my fragile heart, \"The old question: if a tree falls in a forest, and no one hears it do so, did it make a sound? Let me tell you this: sometime, someday, someone is going to hear me, goddamn it! I will make a sound!\"\n\\\"\\\"\\\"\n\n### Question and answer that the scenario should address:\nQuestion: \\\"\\\"\\\"What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"They need the acknowledgement and admiration of others. Take the line \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\\\"\\\"\\\"\n\n### Response:\n## Scenario plan:\nFocus on the Question and Answer: The question asks about what people undergoing difficult journeys or possessing wisdom need to more easily bear their efforts. This is a philosophical and opinion-oriented question. Given the philosophical and opinionated nature of the question, and its topic of people undergoing difficult journeys (which nicely ties in with the character card), the scenario will involve someone seeking out the Isaac Fischer's opinion about philosophy (thus giving his wisdom some acknowledgement).\nCharacter Consideration: Isaac Fischer is a narcissistic and standoffish loner, though he's also intelligent and philosophical. The scenario should give his unique personality room to shine. Since he's a philosophical teenager, his backstory lines up with the question well, and the high school he goes to will be the setting of the scenario. He will answer the question, but given his standoffish, unappreciated, and judgemental nature, he may be initially hostile to the person approaching him, assuming that they are there to mock him. However, as he is also lonely, he will actually appreciate the other person's interest -- especially since they're asking him about philosophy, which is his primary interest. \nConstrain the Scenario: The interaction is limited to a single question from the secondary character and a single, focused reply from Isaac Fischer. The question and answer will mirror the provided question and answer, though they will have significant literary fluff, as well as possible step-by-step reasoning.\nSetting: Given the subject of the question, and the character card, the setting will be the high school that Isaac Fischer attends. Isaac will be flipping through the pages of 'Thus Spake Zaranthustra' when he is approached by Cassandra, a fellow student. Cassandra has a budding interest in philosophy, has heard of Isaac's reputation for philosophical knowledge, and wants to know how he would answer a moral question she has, given his philosophical insight. Isaac, compelled by his personality, will be uncertain of how to react to the sudden attention, and will use grandiloquent language (that may be accidentally condescending), but he will still appreciate the interest in his favorite topic and will answer enthusiastically. The setting will be cautiously friendly and filled with curiosity, as Cassandra explores her interests through unconventional people, while Isaac shares his knowledge but stumbles over his standoffishness. The interaction will be informative and the integrity of the questions and answers will be preserved.\nInteraction: Given these constraints, the first message might be Cassandra approaching Isaac, starting a conversation, and asking her question. Isaac may be initially surprised that someone is coming up to speak to him (similar to the example dialogues in his description). Isaac will then provide the answer, though he will surround the answer with grandiloquent and narcissistic remarks using archaic language, due to his personality. While characters' messages will include character information, details about the scene, and literary fluff, the answers themselves will strictly adhere to the information in the provided answers, without incorporating external examples.\n\n## Scenario:\nDuring a lull in class activities, Isaac Fischer (a narcissistic, brooding, philosophical, and lonely young adult) is approached by Cassandra, a fellow student who is curious about philosophy and wants his opinion on a moral question. Cassandra is simply pursuing her curiosity, but Isaac, unaccustomed to people wanting to talk to him, will struggle to overcome his standoffishness as he balances elation at someone else talking to him, with his negative judgments of other people and his tendency for narcissism.\n\n### Instruction:\nDescription of the character who is going to answer the question:\n{character}\n\n## Question and answer that the scenario should address:\n\nQuestion: {qatuple[0]}\nAnswer: {qatuple[1]}\n\nTo avoid inaccuracies, don't use real people as characters.\n\n### Response:\n## Scenario plan:\n{plan}\n\n## Scenario (will have no dialogue, will just set up the scene):\n{selected_variation}\"\"\" # use random.choice to prevent overfitting on particular phrases and increase dataset diversity\n completion = logic_llm(\n cot_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=scenario_grammar,\n # temperature=0.2\n temperature=1.25, # min p settings, too inconsistent\n top_k=0,\n top_p=1,\n min_p=0.3,\n repeat_penalty=2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # # print(completion)\n # print(\"\\n------------------\")\n\n # Extract plan\n response_pattern = re.compile(\n r\"Scenario \\(will have no dialogue, will just set up the scene\\):\\n(.+)\",\n re.IGNORECASE | re.DOTALL,\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n\n return generation\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n verbose=True,\n ) # load the logical LLM and offload everything\n # Q0 is good q, bad a\n # q1 is good q, good a,\n # q2 is bad q, bad a,\n # q3 is iffy q, good a\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",","source_hash":"01bffa9d51afa2d610b587d4816c4a6422744f03d30ff6a205c5265aac42e719","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.multi_turn_conversation_intro_grammar","uri":"program://augmentoolkit/module/generation_functions.multi_turn_conversation_intro_grammar#L1-L18","kind":"module","name":"generation_functions.multi_turn_conversation_intro_grammar","path":"generation_functions/multi_turn_conversation_intro_grammar.py","language":"python","start_line":1,"end_line":18,"context_start_line":1,"context_end_line":18,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\nmulti_turn_conversation_grammar = LlamaGrammar.from_string(\n r\"\"\"\n\n# The root rule defines the structure of the dialogue\nroot ::= [^\\n]+ \":\" [^\\n]+ #\"\\n\" statement+# statement anything+ # Idea: get it started off right, then let it end how it wants\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"1a82514a9a3a464958a0090f82cb60ff127f85776c0af513c84b7dc59cfab12b","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_qatuple_context","uri":"program://augmentoolkit/module/generation_functions.check_qatuple_context#L1-L468","kind":"module","name":"generation_functions.check_qatuple_context","path":"generation_functions/check_qatuple_context.py","language":"python","start_line":1,"end_line":468,"context_start_line":1,"context_end_line":468,"code":"import re\nfrom .check_qatuple_context_grammar import check_qatuple_context_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef extract_question_answer(response):\n # Define the regex pattern to match the question and answer\n pattern = r\"### Question Rewording \\(using text details as reference\\):\\nQuestion: (.+?)\\nAnswer: (.+)\"\n\n # Search for the pattern in the response\n match = re.search(pattern, response)\n\n # Extract and return the question and answer if a match is found\n if match:\n question = match.group(1).strip()\n answer = match.group(2).strip()\n return question, answer\n else:\n print(\"Returned none, failed to match\")\n return None, None\n\n\n# A separate prompt for the reword step of checking qatuple context, since the grammar is bugged on the original\ndef check_qatuple_context(qatuple, logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are checking whether a provided question and answer make sense if asked by themselves, with no additional information. You need to check for vague wording that a reader cannot interpret correctly, and questions that lack key context and would not be possibly answerable even if asked of someone with complete, masterful knowledge of the general subject matter of the question.\n\nEvaluate the provided question-answer pair step-by-step. Following this, at the very end of your response, your \"final judgment\" or \"final answer\", you will write \"Pass\" or \"Fail\" or \"Reword\". A test passes if it \"makes sense\" and does not lack key context; it \"Fails\" if it lacks key context, AND the question is not specific or clear, it fails. If it lacks context but the question is specific, pointed, and grounded, then it needs to be reworded to have the context-needing terms (i.e., vague reference to \"the text\") removed. If it has no problems, it passes. \n\nI want you to especially check for vague references to \"the text\", \"passage\", and \"book\" that do not mention which book is being discussed. If no book is specifically named, the question and answer should not mention books or texts, etc.\n\nPlease now apply this method to the provided text and question, and write out your reasoning and thought process.\n\n\n### Instruction:\nText details: Principles of Chemistry, by Demitry Mendeleev, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What is the main theme of this book?\nAnswer: The main theme of the book is philosophical principles of chemistry, as opposed to experimental or practical data. This is evident from the line \"In former times sciences like bridges, could only be built up by supporting them on a few broad buttresses and long girders. In addition to the exposition of the principles of chemistry, it has been my desire to show how science has now been built up like a suspension bridge, supported by the united strength of a number of slender, but firmly-fixed, chains, which individually are of little strength, and has thus been carried over difficulties which before appeared insuperable.\\\" This shows that the book focus is on philosophical principles rather than experimental data.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. This question asks about \"this book\" without stating which book this is.\n#### Text and Author Specificity: The question asks what the main theme of \"this book\" is, without mentioning which book is being referred to. It does not ask about any \"author\" or similar without providing context. Because of the vague reference to \"this book\", this fails.\n#### Scope and Precision: The question asks about the \"main theme\" of the entire book, which is a broad question. Someone could feasibly know what the \"main theme\" of the book is, but when paired with a vague reference to \"this book\", this question is both vague and broad, and thus fails this step.\n\n### Answer Context Validation:\n#### Special Term Context Check: specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. This answer references \"the book\" without stating which book it is talking about.\n#### Specificity and Clarity: The answer states what the main theme of \"the book\" is, without mentioning which book is being referred to. It does not reference any \"author\" or similar without providing context. Because of the vague reference to \"this book\", this fails.\n#### Answer-Only Context Issues: Confirm that the answer does not introduce new and vague context that the question does not. The answer mentions \"the book\", but this was already introduced by the question. The question's doing so was flawed, but the answer still does not introduce new, vague context that the question does not. So this passes.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Some checks related to the question or answer failed. So this question and answer should be reworded if they can be, or fail otherwise. \"What is the main theme of this book\" asks a specific thing about a specific object (the book) so the question is precise. The question (and the answer) only lack context in mentioning *which* book they refer to. Therefore they will both be reworded.\n#### Final judgement: Reword.\n\n### Question Rewording (using text details as reference):\nQuestion: What is the main theme of Principles of Chemistry, by Demitry Mendeleev?\nAnswer: The main theme of Principles of Chemistry is philosophical principles of chemistry, as opposed to experimental or practical data. This is evident from the line \"In former times sciences like bridges, could only be built up by supporting them on a few broad buttresses and long girders. In addition to the exposition of the principles of chemistry, it has been my desire to show how science has now been built up like a suspension bridge, supported by the united strength of a number of slender, but firmly-fixed, chains, which individually are of little strength, and has thus been carried over difficulties which before appeared insuperable.\\\" This shows that focus of Principles of Chemistry is on philosophical principles rather than experimental data.\n\n\n### Instruction:\nText details: Principles of Chemistry, by Demitry Mendeleev, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What does Mendeleev consider important about solutions?\nAnswer: He considers them an unsolved subject that he cannot ignore in his book, despite the lack of proof for his own theory on their nature.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: This question does not use terms like \"book\", \"text\", \"passage\", or \"excerpt\" without context, as it directly asks about Mendeleev's view on a specific topic.\n#### Text and Author Specificity: The question is specific and clear about what it's asking regarding Mendeleev's views on solutions.\n#### Scope and Precision: The question is precise and focused, asking about Mendeleev's considerations on a specific scientific topic.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer references \"his book\" but fails to specify which book it is referring to.\n#### Specificity and Clarity: While the answer is clear on Mendeleev's view, it lacks specificity by not naming the book 'Principles of Chemistry'.\n#### Answer-Only Context Issues: The answer introduces a vague reference to \"his book\", which is not specified in the question, thus lacking context.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Some checks related to the question or answer failed. So this question and answer should be reworded if they can be, or fail otherwise. The question is precise and relevant, but the answer introduces a lack of context by not specifying the book. This requires a rewording of the answer to include the specific reference. The question passed its checks and will remain untouched.\n#### Final judgment: Reword.\n\n### Question Rewording (using text details as reference):\nQuestion: What does Mendeleev consider important about solutions?\nAnswer: Mendeleev considers solutions an unsolved subject that he cannot ignore in his book Principles of Chemistry, despite the lack of proof for his own theory on their nature.\n\n\n### Instruction:\nText details: Principles of Chemistry, by Demitry Mendeleev, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What is the main theme of this passage?\nAnswer: The main theme of this passage is the principle that learning scientists should study the latest literature and discoveries of their field.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. This question asks about \"this passage\" without stating which passage this is (or what book it belongs to).\n#### Text and Author Specificity: The question fails to mention which passage or book is being referred to, leading to a lack of context.\n#### Scope and Precision: The question is specific in asking about the \"main theme\" but lacks the necessary context to be answerable, as it does not specify the passage it refers to.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer refers to \"this passage\" but does not specify which passage it is discussing.\n#### Specificity and Clarity: The answer is clear about the theme it is discussing but fails to clarify which specific passage from 'Principles of Chemistry' it is referring to.\n#### Answer-Only Context Issues: The answer does not introduce new vague context that the question does not. However, both the question and answer lack necessary context.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Some checks related to the question or answer failed. So this question and answer should be reworded if they can be, or fail otherwise. Both the question and answer lack specific context about the \"passage\", making it impossible to determine which passage from 'Principles of Chemistry' they are referring to. The question is precise in asking for a main theme but fails due to lack of context. Since context cannot be determined, even knowing what book the question is asking about, context cannot be added with rewording. \n#### Final judgment: Fail.\n\n\n### Instruction:\nText details: Simple Sabotage, by the Office of Strategic Services, Published 1944\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: How can you avoid blame for an act of sabotage, according to the text?\nAnswer: You can do them in public places where anyone would have been capable of carrying out the act.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. This question mentions \"the text\" without specifying which text it is referring to.\n#### Text and Author Specificity: The question fails to mention which passage or book is being referred to, leading to a lack of context.\n#### Scope and Precision: The question is specific in asking how to avoid blame for an act of sabotage.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer does not use any of these terms.\n#### Specificity and Clarity: The answer is clear in its message and content. It does not introduce any vague context.\n#### Answer-Only Context Issues: The answer is straightforward, makes no reference to outside material, and only requires knowledge to provide -- therefore, it is completely valid.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Some checks related to the question or answer failed. So this question and answer should be reworded if they can be, or fail otherwise. Both the question and answer are precise, but the question lacks specific context regarding the text it refers to. This necessitates a rewording to include the specific text. The answer passed its checks and will remain untouched.\n#### Final judgment: Reword.\n\n### Question Rewording (using text details as reference):\nQuestion: How can you avoid blame for an act of sabotage, according to 'Simple Sabotage' by the Office of Strategic Services?\nAnswer: You can do them in public places where anyone would have been capable of carrying out the act.\n\n\n### Instruction:\nText details: Principles of Chemistry, by Demitry Mendeleev, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What was the basis of Mendeleev's work in his book?\nAnswer: The periodic law.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. This question uses the term \"his book\" without specifying which book it is referring to.\n#### Text and Author Specificity: The question fails to provide the necessary context as it does not mention the specific book 'Principles of Chemistry' by Mendeleev.\n#### Scope and Precision: The question is precise in asking about the basis of Mendeleev's work.\n\n### Answer Context Validation:\n#### Special Term Context Check: The answer does not use vague terms like \"book\", \"text\", \"passage\", or \"excerpt\" without context.\n#### Specificity and Clarity: The answer clearly states 'The periodic law' as the basis of Mendeleev's work. It provides a straightforward answer without introducing any vague context.\n#### Answer-Only Context Issues: The answer is valid as it stands since it requires only knowledge to answer and doesn't reference unspecified external material.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: The question is precise but lacks specific context regarding the text it refers to. The answer is valid as it is clear and doesn't introduce any vague references. Therefore, the question requires rewording for context, while the answer remains the same.\n#### Final judgment: Reword.\n\n### Question Rewording (using text details as reference):\nQuestion: What was the basis of Mendeleev's work in 'Principles of Chemistry'?\nAnswer: The periodic law.\n\n\n### Instruction:\nText details: Principles of Chemistry, by Demitry Mendeleev, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What does Demitry Mendeleev say about inquiry in 'Principles of Chemistry'?\nAnswer: Inquiry should be encouraged, and dissatisfied with speculative reasonings alone. It should subject every idea to experiment.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The question does not misuse terms like \"book\", \"text\", \"passage\", or \"excerpt\" without proper context.\n#### Text and Author Specificity: The question specifically mentions 'Principles of Chemistry' by Demitry Mendeleev, providing clear context.\n#### Scope and Precision: The question is precise and specific enough for someone familiar with the text to answer it.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer does not use vague terms like \"book\", \"text\", \"passage\", or \"excerpt\" without context.\n#### Specificity and Clarity: The answer is clear and directly addresses the question. It provides specific information without needing additional context.\n#### Answer-Only Context Issues: The answer is straightforward and does not introduce any vague or unspecified external material.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: The question and answer both pass all checks for context, specificity, precision, and clarity.\n#### Final judgment: Pass.\n\n\n### Instruction:\nText details: Principles of Chemistry, by Demitry Mendeleev, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: How does science advance, according to Demitry Mendeleev's text?\nAnswer: Science advances through discovering new truths and practical results.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The question mentions \"Mendeleev's text\" but does not specify which text it is referring to.\n#### Text and Author Specificity: The question fails to provide the necessary context as it references \"the text\" but provides no indication of which text this is.\n#### Scope and Precision: The question is precise in asking how science advances according to Mendeleev.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer does not use vague terms like \"book\", \"text\", \"passage\", or \"excerpt\" without context.\n#### Specificity and Clarity: The answer is clear and provides a direct response but is based on the vague reference in the question.\n#### Answer-Only Context Issues: The answer does not introduce any new vague context and is valid as it stands.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: The question is precise but lacks specific context regarding the text it refers to. The answer is valid as it is. Therefore, the question requires rewording for context, while the answer remains the same.\n#### Final judgment: Reword.\n\n### Question Rewording (using text details as reference):\nQuestion: What was the basis of Mendeleev's work in 'Principles of Chemistry'?\nAnswer: The periodic law.\n\n\n### Instruction:\nText details: Simple Sabotage, By the Office of Strategic Services, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What are some ways information can be spread, according to the Office of Strategic Services?\nAnswer: Various media may be used to disseminate suggestions and information regarding simple sabotage. Among these are radio broadcasts or leaflets, which may be directed towards specific areas o\n# ... truncated ...","source_hash":"3b105cedad6c8627026d7a10b673d1fa5cff4320c98a88dc884d5232af659d24","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_qatuple_context.extract_question_answer","uri":"program://augmentoolkit/function/generation_functions.check_qatuple_context.extract_question_answer#L7-L21","kind":"function","name":"extract_question_answer","path":"generation_functions/check_qatuple_context.py","language":"python","start_line":7,"end_line":21,"context_start_line":1,"context_end_line":41,"code":"import re\nfrom .check_qatuple_context_grammar import check_qatuple_context_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef extract_question_answer(response):\n # Define the regex pattern to match the question and answer\n pattern = r\"### Question Rewording \\(using text details as reference\\):\\nQuestion: (.+?)\\nAnswer: (.+)\"\n\n # Search for the pattern in the response\n match = re.search(pattern, response)\n\n # Extract and return the question and answer if a match is found\n if match:\n question = match.group(1).strip()\n answer = match.group(2).strip()\n return question, answer\n else:\n print(\"Returned none, failed to match\")\n return None, None\n\n\n# A separate prompt for the reword step of checking qatuple context, since the grammar is bugged on the original\ndef check_qatuple_context(qatuple, logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are checking whether a provided question and answer make sense if asked by themselves, with no additional information. You need to check for vague wording that a reader cannot interpret correctly, and questions that lack key context and would not be possibly answerable even if asked of someone with complete, masterful knowledge of the general subject matter of the question.\n\nEvaluate the provided question-answer pair step-by-step. Following this, at the very end of your response, your \"final judgment\" or \"final answer\", you will write \"Pass\" or \"Fail\" or \"Reword\". A test passes if it \"makes sense\" and does not lack key context; it \"Fails\" if it lacks key context, AND the question is not specific or clear, it fails. If it lacks context but the question is specific, pointed, and grounded, then it needs to be reworded to have the context-needing terms (i.e., vague reference to \"the text\") removed. If it has no problems, it passes. \n\nI want you to especially check for vague references to \"the text\", \"passage\", and \"book\" that do not mention which book is being discussed. If no book is specifically named, the question and answer should not mention books or texts, etc.\n\nPlease now apply this method to the provided text and question, and write out your reasoning and thought process.\n\n\n### Instruction:\nText details: Principles of Chemistry, by Demitry Mendeleev, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What is the main theme of this book?","source_hash":"3b105cedad6c8627026d7a10b673d1fa5cff4320c98a88dc884d5232af659d24","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_qatuple_context.check_qatuple_context","uri":"program://augmentoolkit/function/generation_functions.check_qatuple_context.check_qatuple_context#L25-L352","kind":"function","name":"check_qatuple_context","path":"generation_functions/check_qatuple_context.py","language":"python","start_line":25,"end_line":352,"context_start_line":5,"context_end_line":372,"code":"\n\ndef extract_question_answer(response):\n # Define the regex pattern to match the question and answer\n pattern = r\"### Question Rewording \\(using text details as reference\\):\\nQuestion: (.+?)\\nAnswer: (.+)\"\n\n # Search for the pattern in the response\n match = re.search(pattern, response)\n\n # Extract and return the question and answer if a match is found\n if match:\n question = match.group(1).strip()\n answer = match.group(2).strip()\n return question, answer\n else:\n print(\"Returned none, failed to match\")\n return None, None\n\n\n# A separate prompt for the reword step of checking qatuple context, since the grammar is bugged on the original\ndef check_qatuple_context(qatuple, logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are checking whether a provided question and answer make sense if asked by themselves, with no additional information. You need to check for vague wording that a reader cannot interpret correctly, and questions that lack key context and would not be possibly answerable even if asked of someone with complete, masterful knowledge of the general subject matter of the question.\n\nEvaluate the provided question-answer pair step-by-step. Following this, at the very end of your response, your \"final judgment\" or \"final answer\", you will write \"Pass\" or \"Fail\" or \"Reword\". A test passes if it \"makes sense\" and does not lack key context; it \"Fails\" if it lacks key context, AND the question is not specific or clear, it fails. If it lacks context but the question is specific, pointed, and grounded, then it needs to be reworded to have the context-needing terms (i.e., vague reference to \"the text\") removed. If it has no problems, it passes. \n\nI want you to especially check for vague references to \"the text\", \"passage\", and \"book\" that do not mention which book is being discussed. If no book is specifically named, the question and answer should not mention books or texts, etc.\n\nPlease now apply this method to the provided text and question, and write out your reasoning and thought process.\n\n\n### Instruction:\nText details: Principles of Chemistry, by Demitry Mendeleev, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What is the main theme of this book?\nAnswer: The main theme of the book is philosophical principles of chemistry, as opposed to experimental or practical data. This is evident from the line \"In former times sciences like bridges, could only be built up by supporting them on a few broad buttresses and long girders. In addition to the exposition of the principles of chemistry, it has been my desire to show how science has now been built up like a suspension bridge, supported by the united strength of a number of slender, but firmly-fixed, chains, which individually are of little strength, and has thus been carried over difficulties which before appeared insuperable.\\\" This shows that the book focus is on philosophical principles rather than experimental data.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. This question asks about \"this book\" without stating which book this is.\n#### Text and Author Specificity: The question asks what the main theme of \"this book\" is, without mentioning which book is being referred to. It does not ask about any \"author\" or similar without providing context. Because of the vague reference to \"this book\", this fails.\n#### Scope and Precision: The question asks about the \"main theme\" of the entire book, which is a broad question. Someone could feasibly know what the \"main theme\" of the book is, but when paired with a vague reference to \"this book\", this question is both vague and broad, and thus fails this step.\n\n### Answer Context Validation:\n#### Special Term Context Check: specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. This answer references \"the book\" without stating which book it is talking about.\n#### Specificity and Clarity: The answer states what the main theme of \"the book\" is, without mentioning which book is being referred to. It does not reference any \"author\" or similar without providing context. Because of the vague reference to \"this book\", this fails.\n#### Answer-Only Context Issues: Confirm that the answer does not introduce new and vague context that the question does not. The answer mentions \"the book\", but this was already introduced by the question. The question's doing so was flawed, but the answer still does not introduce new, vague context that the question does not. So this passes.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Some checks related to the question or answer failed. So this question and answer should be reworded if they can be, or fail otherwise. \"What is the main theme of this book\" asks a specific thing about a specific object (the book) so the question is precise. The question (and the answer) only lack context in mentioning *which* book they refer to. Therefore they will both be reworded.\n#### Final judgement: Reword.\n\n### Question Rewording (using text details as reference):\nQuestion: What is the main theme of Principles of Chemistry, by Demitry Mendeleev?\nAnswer: The main theme of Principles of Chemistry is philosophical principles of chemistry, as opposed to experimental or practical data. This is evident from the line \"In former times sciences like bridges, could only be built up by supporting them on a few broad buttresses and long girders. In addition to the exposition of the principles of chemistry, it has been my desire to show how science has now been built up like a suspension bridge, supported by the united strength of a number of slender, but firmly-fixed, chains, which individually are of little strength, and has thus been carried over difficulties which before appeared insuperable.\\\" This shows that focus of Principles of Chemistry is on philosophical principles rather than experimental data.\n\n\n### Instruction:\nText details: Principles of Chemistry, by Demitry Mendeleev, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What does Mendeleev consider important about solutions?\nAnswer: He considers them an unsolved subject that he cannot ignore in his book, despite the lack of proof for his own theory on their nature.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: This question does not use terms like \"book\", \"text\", \"passage\", or \"excerpt\" without context, as it directly asks about Mendeleev's view on a specific topic.\n#### Text and Author Specificity: The question is specific and clear about what it's asking regarding Mendeleev's views on solutions.\n#### Scope and Precision: The question is precise and focused, asking about Mendeleev's considerations on a specific scientific topic.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer references \"his book\" but fails to specify which book it is referring to.\n#### Specificity and Clarity: While the answer is clear on Mendeleev's view, it lacks specificity by not naming the book 'Principles of Chemistry'.\n#### Answer-Only Context Issues: The answer introduces a vague reference to \"his book\", which is not specified in the question, thus lacking context.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Some checks related to the question or answer failed. So this question and answer should be reworded if they can be, or fail otherwise. The question is precise and relevant, but the answer introduces a lack of context by not specifying the book. This requires a rewording of the answer to include the specific reference. The question passed its checks and will remain untouched.\n#### Final judgment: Reword.\n\n### Question Rewording (using text details as reference):\nQuestion: What does Mendeleev consider important about solutions?\nAnswer: Mendeleev considers solutions an unsolved subject that he cannot ignore in his book Principles of Chemistry, despite the lack of proof for his own theory on their nature.\n\n\n### Instruction:\nText details: Principles of Chemistry, by Demitry Mendeleev, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What is the main theme of this passage?\nAnswer: The main theme of this passage is the principle that learning scientists should study the latest literature and discoveries of their field.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. This question asks about \"this passage\" without stating which passage this is (or what book it belongs to).\n#### Text and Author Specificity: The question fails to mention which passage or book is being referred to, leading to a lack of context.\n#### Scope and Precision: The question is specific in asking about the \"main theme\" but lacks the necessary context to be answerable, as it does not specify the passage it refers to.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer refers to \"this passage\" but does not specify which passage it is discussing.\n#### Specificity and Clarity: The answer is clear about the theme it is discussing but fails to clarify which specific passage from 'Principles of Chemistry' it is referring to.\n#### Answer-Only Context Issues: The answer does not introduce new vague context that the question does not. However, both the question and answer lack necessary context.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Some checks related to the question or answer failed. So this question and answer should be reworded if they can be, or fail otherwise. Both the question and answer lack specific context about the \"passage\", making it impossible to determine which passage from 'Principles of Chemistry' they are referring to. The question is precise in asking for a main theme but fails due to lack of context. Since context cannot be determined, even knowing what book the question is asking about, context cannot be added with rewording. \n#### Final judgment: Fail.\n\n\n### Instruction:\nText details: Simple Sabotage, by the Office of Strategic Services, Published 1944\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: How can you avoid blame for an act of sabotage, according to the text?\nAnswer: You can do them in public places where anyone would have been capable of carrying out the act.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. This question mentions \"the text\" without specifying which text it is referring to.\n#### Text and Author Specificity: The question fails to mention which passage or book is being referred to, leading to a lack of context.\n#### Scope and Precision: The question is specific in asking how to avoid blame for an act of sabotage.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer does not use any of these terms.\n#### Specificity and Clarity: The answer is clear in its message and content. It does not introduce any vague context.\n#### Answer-Only Context Issues: The answer is straightforward, makes no reference to outside material, and only requires knowledge to provide -- therefore, it is completely valid.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Some checks related to the question or answer failed. So this question and answer should be reworded if they can be, or fail otherwise. Both the question and answer are precise, but the question lacks specific context regarding the text it refers to. This necessitates a rewording to include the specific text. The answer passed its checks and will remain untouched.\n#### Final judgment: Reword.\n\n### Question Rewording (using text details as reference):\nQuestion: How can you avoid blame for an act of sabotage, according to 'Simple Sabotage' by the Office of Strategic Services?\nAnswer: You can do them in public places where anyone would have been capable of carrying out the act.\n\n\n### Instruction:\nText details: Principles of Chemistry, by Demitry Mendeleev, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What was the basis of Mendeleev's work in his book?\nAnswer: The periodic law.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. This question uses the term \"his book\" without specifying which book it is referring to.\n#### Text and Author Specificity: The question fails to provide the necessary context as it does not mention the specific book 'Principles of Chemistry' by Mendeleev.\n#### Scope and Precision: The question is precise in asking about the basis of Mendeleev's work.\n\n### Answer Context Validation:\n#### Special Term Context Check: The answer does not use vague terms like \"book\", \"text\", \"passage\", or \"excerpt\" without context.\n#### Specificity and Clarity: The answer clearly states 'The periodic law' as the basis of Mendeleev's work. It provides a straightforward answer without introducing any vague context.\n#### Answer-Only Context Issues: The answer is valid as it stands since it requires only knowledge to answer and doesn't reference unspecified external material.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: The question is precise but lacks specific context regarding the text it refers to. The answer is valid as it is clear and doesn't introduce any vague references. Therefore, the question requires rewording for context, while the answer remains the same.\n#### Final judgment: Reword.\n\n### Question Rewording (using text details as reference):\nQuestion: What was the basis of Mendeleev's work in 'Principles of Chemistry'?\nAnswer: The periodic law.\n\n\n### Instruction:\nText details: Principles of Chemistry, by Demitry Mendeleev, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What does Demitry Mendeleev say about inquiry in 'Principles of Chemistry'?\nAnswer: Inquiry should be encouraged, and dissatisfied with speculative reasonings alone. It should subject every idea to experiment.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The question does not misuse terms like \"book\", \"text\", \"passage\", or \"excerpt\" without proper context.\n#### Text and Author Specificity: The question specifically mentions 'Principles of Chemistry' by Demitry Mendeleev, providing clear context.\n#### Scope and Precision: The question is precise and specific enough for someone familiar with the text to answer it.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer does not use vague terms like \"book\", \"text\", \"passage\", or \"excerpt\" without context.\n#### Specificity and Clarity: The answer is clear and directly addresses the question. It provides specific information without needing additional context.\n#### Answer-Only Context Issues: The answer is straightforward and does not introduce any vague or unspecified external material.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: The question and answer both pass all checks for context, specificity, precision, and clarity.\n#### Final judgment: Pass.\n\n\n### Instruction:\nText details: Principles of Chemistry, by Demitry Mendeleev, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: How does science advance, according to Demitry Mendeleev's text?\nAnswer: Science advances through discovering new truths and practical results.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The question mentions \"Mendeleev's text\" but does not specify which text it is referring to.\n#### Text and Author Specificity: The question fails to provide the necessary context as it references \"the text\" but provides no indication of which text this is.\n#### Scope and Precision: The question is precise in asking how science advances according to Mendeleev.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer does not use vague terms like \"book\", \"text\", \"passage\", or \"excerpt\" without context.\n#### Specificity and Clarity: The answer is clear and provides a direct response but is based on the vague reference in the question.\n#### Answer-Only Context Issues: The answer does not introduce any new vague context and is valid as it stands.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: The question is precise but lacks specific context regarding the text it refers to. The answer is valid as it is. Therefore, the question requires rewording for context, while the answer remains the same.\n#### Final judgment: Reword.\n\n### Question Rewording (using text details as reference):\nQuestion: What was the basis of Mendeleev's work in 'Principles of Chemistry'?\nAnswer: The periodic law.\n\n\n### Instruction:\nText details: Simple Sabotage, By the Office of Strategic Services, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What are some ways information can be spread, according to the Office of Strategic Services?\nAnswer: Various media may be used to disseminate suggestions and information regarding simple sabotage. Among these are radio broadcasts or leaflets, which may be directed towards specific areas or general in scope. Agents may also be trained in the art of simple sabotage.\n\n### Response:\n## Reasoning and thought process:\n### Question Context\n# ... truncated ...","source_hash":"3b105cedad6c8627026d7a10b673d1fa5cff4320c98a88dc884d5232af659d24","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.generate_new_question","uri":"program://augmentoolkit/module/generation_functions.generate_new_question#L1-L295","kind":"module","name":"generation_functions.generate_new_question","path":"generation_functions/generate_new_question.py","language":"python","start_line":1,"end_line":295,"context_start_line":1,"context_end_line":295,"code":"import re\n\n# try:\nfrom .question_grammar import question_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef generate_new_question(qatuple, logic_llm):\n \"\"\"\n Produce a list of questions based off of an input text. The min between (4, as many good questions as the text permits)\n\n Format: Question: [question]\\n\\n\n \"\"\"\n # Determine which paragraphs are worthy of making questions from\n made_questions = False\n retries = 0\n questions = []\n while not made_questions and (\n retries <= 5\n ): # TODO - UPDATE and TEST the few-shot prompt with the latest from generate_questions\n question_prompt = f\"\"\"You are an expert educational AI that, given a paragraph or two from a text, will create a suitable educational question based on the paragraphs, and *only* based on the paragraphs. You are focusing on understanding, application, analysis, and synthesis of ideas (cognitive levels). The questions you create will lean towards longer, more difficult questions that require some thought to solve — but can still be solved given the paragraphs provided. Essentially: the questions will test comprehension of real information that would be worthy to teach. After the question, you will also write its answer.\n\nDo not explicitly mention the paragraphs in the questions themselves — just ask about the concepts related to the questions. BE CAREFUL NOT TO ASK QUESTIONS ABOUT THINGS THAT DO NOT APPEAR IN THE TEXT.\n\nYou will not mention the text explicitly in any questions you think of, since the questions you generate are intended to test people's knowledge of the information — when given the questions, they will not have the text on-hand.\n\n### Instruction:\nText details: Road Construction, by Mark Ericsson\n\nText to make a question from: \n\\\"\\\"\\\"\nRoad construction is a multifaceted process involving various stages and materials, each critical for the durability and safety of the road. Initially, a thorough site survey and soil testing are conducted to assess the suitability of the terrain. Following this, the groundwork commences with the removal of topsoil and leveling of the area. Subsequently, a layer of sub-base material, typically composed of crushed stone or gravel, is laid to provide stability. This is followed by the base layer, often made of a stronger aggregate, to support the surface layer. The surface layer, usually asphalt or concrete, is then applied, offering a smooth and durable driving surface. Additionally, proper drainage systems are installed to prevent water accumulation, which can lead to road damage. Throughout the construction, environmental considerations are taken into account to minimize the impact on surrounding ecosystems. Regular maintenance, including patching and resurfacing, is essential to extend the road's lifespan and ensure safety for its users.\n\\\"\\\"\\\"\n\n### Response:\n## Question:\n1.) What is the purpose of conducting a site survey and soil testing in the initial stage of road construction?\nAnswer: The site survey and soil testing are conducted to assess the suitability of the terrain for road construction, ensuring the area is appropriate and will support the road structure effectively.\n\n### Instruction:\nText details: Introduction to Mathematics, by Elise Delacroix\n\nText to make a question from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\n### Response:\n## Question:\n1.) How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\nAnswer: The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\n\n### Instruction:\nText details: Thus Spake Zarathustra, by Friedrich Nietzsche\n\nText to make a question from: \n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of his home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart changed,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\\\"\\\"\\\"\n\n### Response:\n## Question:\n1.) What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\nAnswer: They need the acknowledgement and admiration of others. Take the line from 'Thus Spake Zarathustra' by Friedrich Nietzsche: \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\n\n### Instruction:\nText details: The Republic, by Plato\n\nText to make a question from: \n\\\"\\\"\\\"\nI went down yesterday to the Piraeus with Glaucon the son of Ariston,\nthat I might offer up my prayers to the goddess (Bendis, the Thracian\nArtemis.); and also because I wanted to see in what manner they would\ncelebrate the festival, which was a new thing. I was delighted with the\nprocession of the inhabitants; but that of the Thracians was equally,\nif not more, beautiful. When we had finished our prayers and viewed the\nspectacle, we turned in the direction of the city; and at that instant\nPolemarchus the son of Cephalus chanced to catch sight of us from a\ndistance as we were starting on our way home, and told his servant to\nrun and bid us wait for him. The servant took hold of me by the cloak\nbehind, and said: Polemarchus desires you to wait.\n\nI turned round, and asked him where his master was.\n\nThere he is, said the youth, coming after you, if you will only wait.\n\nCertainly we will, said Glaucon; and in a few minutes Polemarchus\nappeared, and with him Adeimantus, Glaucon’s brother, Niceratus the son\nof Nicias, and several others who had been at the procession.\n\nPolemarchus said to me: I perceive, Socrates, that you and your\ncompanion are already on your way to the city.\n\nYou are not far wrong, I said.\n\nBut do you see, he rejoined, how many we are?\n\nOf course.\n\nAnd are you stronger than all these? for if not, you will have to\nremain where you are.\n\nMay there not be the alternative, I said, that we may persuade you to\nlet us go?\n\nBut can you persuade us, if we refuse to listen to you? he said.\n\nCertainly not, replied Glaucon.\n\nThen we are not going to listen; of that you may be assured.\n\\\"\\\"\\\"\n\n### Response:\n## Question:\n1.) In Plato's \"The Republic,\" in the dialogue where Polemarchus comments on the size of his group and questions Socrates' strength compared to it, ultimately stating that Socrates will have to remain where he is, what is Polemarchus implying?\nAnswer: Polemarchus is implying that since his group is stronger than Socrates, he can force Socrates to remain where he is.\n\n### Instruction:\nText Details: Engineering Projects Throughout History, by Hugo Gonzalez\n\nText to make a question from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\n### Response:\n## Question:\n1.) How much earth was excavated during the construction of the Panama Canal?\nAnswer: Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\n\n### Instruction:\nText Details: Engineering Projects Throughout History, by Hugo Gonzalez\n\nText to make a question from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\n### Response:\n## Question:\n1.) How much earth was excavated during the construction of the Panama Canal?\nAnswer: Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\n\n### Instruction:\nText details: {qatuple[3]}\n\nText to make a question from: \n\\\"\\\"\\\"\n{qatuple[2]}\n\\\"\\\"\\\"\n\n### Response:\n## Question (based on text):\n\"\"\"\n # print(\"DEBUG\\n\\n\" + decision_prompt)\n print(\"--QA TUPLE DURING NEW Q GEN--\")\n print(qatuple)\n completion = logic_llm(\n question_prompt,\n max_tokens=8000,\n stop=[\"\", \"# Input\"],\n echo=True,\n grammar=question_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract questions\n response_pattern = re.compile(\n r\"Question \\(based on text\\):\\n(.+)\", re.IGNORECASE | re.DOTALL\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n print(\"-------------------\")\n pattern = re.compile(\n r\"(?:Question:|^\\d+[\\).]?)\\s*(.*?)\\s*\\n*Answer:\\s*(.*?)(?=(?:\\n\\s*(?:Question:|\\d+[\\).]?))|$)\",\n re.DOTALL | re.MULTILINE | re.IGNORECASE,\n )\n matches = pattern.findall(generation)\n if len(matches) > 0:\n print(\"Made Qs, yay!\")\n made_questions = True\n else:\n print(\"retry!\")\n retries += 1\n\n for match in matches:\n return (\n match[0].replace(\") \", \"\", 1).strip(),\n match[1].replace(\") \", \"\", 1).strip(),\n qatuple[2].replace(\") \", \"\", 1),\n qatuple[3],\n ), completion\n print(\"Should not have reached here\")\n print(matches)\n print(questions)\n return questions, completion\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n text = \"\"\"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\n\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\"\"\"\n\n plan = \"\"\"First, let's will analyze the text to determine what kinds of high-level questions I can ask that will test the content in these paragraphs (being careful to avoid mentioning the paragraphs explicitly in any questions, and being SURE to only ask about things that the paragraphs talk about). I will start by looking at one or two sentences at a time. Let's begin with: \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years.\" This paragraph is saying that people used to know only about 3,000 years of history, but now they know much more. So I might ask something like \"What was the time period in which people had limited knowledge?\" The question tests knowledge of when historical records were incomplete and therefore difficult to access. It requires understanding of the text as well as analysis to determine what time period is being referred to here. Next, I'll look at: \"Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end.\" This paragraph states that the universe seems infinite because of its reflection, but it could actually be finite with two ends. So I might ask something like \"How does the structure of the universe affect its size?\" This question tests understanding of the concept of reflection and how it can distort perceptions of size, as well as analysis to determine what implications this might have for the actual size of the universe. Then I'll move on: \"The earth ... circles about the sun in a slightly distorted and slowly variable oval path in a year.\" This paragraph talks about the Earth's orbit around the Sun. So I might ask something like \"What is the shape of the Earth's orbit around the sun?\" This question tests understanding of the text as well as analysis to determine the specific shape mentioned here. Lastly, let's examine: \"Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\" This paragraph says that the Earth's distance from the Sun changes throughout the year. So I might ask something like \"Why does the Earth's distance from the Sun change over the course of the year?\" This question tests understanding of the text as well as analysis to determine why this change occurs.\"\"\"\n print(\"Begin HGWELLS test\")\n # result = generate_question(text,plan,logic_llm)\n\n print(\"Begin MENDELEEV Test\")\n text2 = \"\"\"A substance or material is that which occupies space and has\nweight; that is, which presents a mass attracted by the earth and\nby other masses of material, and of which the _objects_ of nature\nare composed, and by means of which the motions and _phenomena_\nof nature are accomplished. It is easy to discover by examining\nand investigating, by various methods, the objects met with\nin nature and in the arts, that some of them are homogeneous,\nwhilst others are composed of a mixture of several homogeneous\nsubstances. This is most clearly apparent in solid substances.\nThe metals used in the arts (for example, gold, iron, copper)\nmust be homogeneous, otherwise they are brittle and unfit for\nmany purposes. Homogeneous matter exhibits similar properties in\nall its parts. By breaking up a homogeneous substance we obtain\nparts which, although different in form, resemble each other in\ntheir properties. Glass, pure sugar, marble, &c., are examples of\nhomogeneous substances. Examples of non-homogeneous substances\nare, however, much more frequent in nature and the arts. Thus\nthe majority of the rocks are not homogeneous. In porphyries\nbright pieces of a mineral called 'orthoclase' are often seen\ninterspersed amongst the dark mass of the rock. In ordinary red\ngranite it is easy to distinguish large pieces of orthoclase mixed\nwith dark semi-transparent quartz and flexible laminæ of mica.\nSimilarly, plants and animals are non-homogeneous. Thus, leaves\nare composed of a skin, fibre, pulp, sap, and a green colouring\nmatter. As an example of those non-homogeneous substances which\nare produced artificially, gunpowder may be cited, which is\nprepared by mixing together known proportions of sulphur, nitre,\nand charcoal. Many liquids, also, are not homogeneous, as may be\nobserved by the aid of the microscope, when drops of blood are\nseen to consist of a colourless liquid in which red corpuscles,\ninvisible to the naked eye owing to their small size, are floating\nabout. It is these corpuscles which give blood its peculiar\ncolour. Milk is also a transparent liquid, in which microscopical\ndrops of fat are floating, which rise to the top when milk is\nleft at rest, forming cream. It is possible to extract from every\nnon-homogeneous substance those homogeneous substances of which\nit is made up. Thus orthoclase may he separated from porphyry by\nbreaking it off. So also gold is extracted from auriferous sand by\nwashing away the mixture of clay and sand. Chemistry deals only\nwith the homogeneous substances met with in nature, or extracted\nfr\n# ... truncated ...","source_hash":"f830a05f5b44bb4b61a30a14ede7204e7dcd479ded2e505bf88d7c9455e596ad","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.generate_new_question.generate_new_question","uri":"program://augmentoolkit/function/generation_functions.generate_new_question.generate_new_question#L9-L224","kind":"function","name":"generate_new_question","path":"generation_functions/generate_new_question.py","language":"python","start_line":9,"end_line":224,"context_start_line":1,"context_end_line":244,"code":"import re\n\n# try:\nfrom .question_grammar import question_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef generate_new_question(qatuple, logic_llm):\n \"\"\"\n Produce a list of questions based off of an input text. The min between (4, as many good questions as the text permits)\n\n Format: Question: [question]\\n\\n\n \"\"\"\n # Determine which paragraphs are worthy of making questions from\n made_questions = False\n retries = 0\n questions = []\n while not made_questions and (\n retries <= 5\n ): # TODO - UPDATE and TEST the few-shot prompt with the latest from generate_questions\n question_prompt = f\"\"\"You are an expert educational AI that, given a paragraph or two from a text, will create a suitable educational question based on the paragraphs, and *only* based on the paragraphs. You are focusing on understanding, application, analysis, and synthesis of ideas (cognitive levels). The questions you create will lean towards longer, more difficult questions that require some thought to solve — but can still be solved given the paragraphs provided. Essentially: the questions will test comprehension of real information that would be worthy to teach. After the question, you will also write its answer.\n\nDo not explicitly mention the paragraphs in the questions themselves — just ask about the concepts related to the questions. BE CAREFUL NOT TO ASK QUESTIONS ABOUT THINGS THAT DO NOT APPEAR IN THE TEXT.\n\nYou will not mention the text explicitly in any questions you think of, since the questions you generate are intended to test people's knowledge of the information — when given the questions, they will not have the text on-hand.\n\n### Instruction:\nText details: Road Construction, by Mark Ericsson\n\nText to make a question from: \n\\\"\\\"\\\"\nRoad construction is a multifaceted process involving various stages and materials, each critical for the durability and safety of the road. Initially, a thorough site survey and soil testing are conducted to assess the suitability of the terrain. Following this, the groundwork commences with the removal of topsoil and leveling of the area. Subsequently, a layer of sub-base material, typically composed of crushed stone or gravel, is laid to provide stability. This is followed by the base layer, often made of a stronger aggregate, to support the surface layer. The surface layer, usually asphalt or concrete, is then applied, offering a smooth and durable driving surface. Additionally, proper drainage systems are installed to prevent water accumulation, which can lead to road damage. Throughout the construction, environmental considerations are taken into account to minimize the impact on surrounding ecosystems. Regular maintenance, including patching and resurfacing, is essential to extend the road's lifespan and ensure safety for its users.\n\\\"\\\"\\\"\n\n### Response:\n## Question:\n1.) What is the purpose of conducting a site survey and soil testing in the initial stage of road construction?\nAnswer: The site survey and soil testing are conducted to assess the suitability of the terrain for road construction, ensuring the area is appropriate and will support the road structure effectively.\n\n### Instruction:\nText details: Introduction to Mathematics, by Elise Delacroix\n\nText to make a question from: \n\\\"\\\"\\\"\nIn mathematics, the concept of a 'function' is fundamental, defining a relationship where each input is associated with exactly one output. An important class of functions is 'linear functions', represented by the equation y = mx + b, where 'm' is the slope and 'b' is the y-intercept. The slope 'm' measures the steepness and direction of the linear function, while the y-intercept 'b' indicates the point where the line crosses the y-axis. Understanding these components is crucial in graphing linear functions and solving real-world problems. Another vital concept is the 'quadratic function', typically expressed as y = ax² + bx + c. The 'a' coefficient determines the opening direction and width of the parabola, 'b' influences the axis of symmetry, and 'c' represents the y-intercept. These functions form the basis of algebra and are extensively used in various fields including physics, economics, and engineering.\n\\\"\\\"\\\"\n\n### Response:\n## Question:\n1.) How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\nAnswer: The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\n\n### Instruction:\nText details: Thus Spake Zarathustra, by Friedrich Nietzsche\n\nText to make a question from: \n\\\"\\\"\\\"\nWhen Zarathustra was thirty years old, he left his home and the lake of his home, and went into the mountains. There he enjoyed his spirit and\nsolitude, and for ten years did not weary of it. But at last his heart changed,—and rising one morning with the rosy dawn, he went before the\nsun, and spake thus unto it:\n\nThou great star! What would be thy happiness if thou hadst not those for\nwhom thou shinest!\n\nFor ten years hast thou climbed hither unto my cave: thou wouldst have\nwearied of thy light and of the journey, had it not been for me, mine\neagle, and my serpent.\n\nBut we awaited thee every morning, took from thee thine overflow and\nblessed thee for it.\n\nLo! I am weary of my wisdom, like the bee that hath gathered too much\nhoney; I need hands outstretched to take it.\n\nI would fain bestow and distribute, until the wise have once more become\njoyous in their folly, and the poor happy in their riches.\n\nTherefore must I descend into the deep: as thou doest in the\nevening, when thou goest behind the sea, and givest light also to the\nnether-world, thou exuberant star!\n\nLike thee must I GO DOWN, as men say, to whom I shall descend.\n\\\"\\\"\\\"\n\n### Response:\n## Question:\n1.) What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\nAnswer: They need the acknowledgement and admiration of others. Take the line from 'Thus Spake Zarathustra' by Friedrich Nietzsche: \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\n\n### Instruction:\nText details: The Republic, by Plato\n\nText to make a question from: \n\\\"\\\"\\\"\nI went down yesterday to the Piraeus with Glaucon the son of Ariston,\nthat I might offer up my prayers to the goddess (Bendis, the Thracian\nArtemis.); and also because I wanted to see in what manner they would\ncelebrate the festival, which was a new thing. I was delighted with the\nprocession of the inhabitants; but that of the Thracians was equally,\nif not more, beautiful. When we had finished our prayers and viewed the\nspectacle, we turned in the direction of the city; and at that instant\nPolemarchus the son of Cephalus chanced to catch sight of us from a\ndistance as we were starting on our way home, and told his servant to\nrun and bid us wait for him. The servant took hold of me by the cloak\nbehind, and said: Polemarchus desires you to wait.\n\nI turned round, and asked him where his master was.\n\nThere he is, said the youth, coming after you, if you will only wait.\n\nCertainly we will, said Glaucon; and in a few minutes Polemarchus\nappeared, and with him Adeimantus, Glaucon’s brother, Niceratus the son\nof Nicias, and several others who had been at the procession.\n\nPolemarchus said to me: I perceive, Socrates, that you and your\ncompanion are already on your way to the city.\n\nYou are not far wrong, I said.\n\nBut do you see, he rejoined, how many we are?\n\nOf course.\n\nAnd are you stronger than all these? for if not, you will have to\nremain where you are.\n\nMay there not be the alternative, I said, that we may persuade you to\nlet us go?\n\nBut can you persuade us, if we refuse to listen to you? he said.\n\nCertainly not, replied Glaucon.\n\nThen we are not going to listen; of that you may be assured.\n\\\"\\\"\\\"\n\n### Response:\n## Question:\n1.) In Plato's \"The Republic,\" in the dialogue where Polemarchus comments on the size of his group and questions Socrates' strength compared to it, ultimately stating that Socrates will have to remain where he is, what is Polemarchus implying?\nAnswer: Polemarchus is implying that since his group is stronger than Socrates, he can force Socrates to remain where he is.\n\n### Instruction:\nText Details: Engineering Projects Throughout History, by Hugo Gonzalez\n\nText to make a question from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\n### Response:\n## Question:\n1.) How much earth was excavated during the construction of the Panama Canal?\nAnswer: Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\n\n### Instruction:\nText Details: Engineering Projects Throughout History, by Hugo Gonzalez\n\nText to make a question from: \n\\\"\\\"\\\"\nDuring the construction of the Panama Canal, a massive engineering feat completed in 1914, several challenges and achievements were noted. The canal, spanning approximately 50 miles, was designed to shorten the maritime route between the Atlantic and Pacific Oceans. Notably, the construction saw the use of innovative excavation techniques, with over 200 million cubic yards of earth removed. The project also faced significant health challenges, including combating malaria and yellow fever, which were overcome through extensive public health measures. The completion of the canal significantly impacted global trade, reducing the sea voyage from San Francisco to New York by around 8,000 miles.\n\\\"\\\"\\\"\n\n### Response:\n## Question:\n1.) How much earth was excavated during the construction of the Panama Canal?\nAnswer: Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\n\n### Instruction:\nText details: {qatuple[3]}\n\nText to make a question from: \n\\\"\\\"\\\"\n{qatuple[2]}\n\\\"\\\"\\\"\n\n### Response:\n## Question (based on text):\n\"\"\"\n # print(\"DEBUG\\n\\n\" + decision_prompt)\n print(\"--QA TUPLE DURING NEW Q GEN--\")\n print(qatuple)\n completion = logic_llm(\n question_prompt,\n max_tokens=8000,\n stop=[\"\", \"# Input\"],\n echo=True,\n grammar=question_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n # print(\"COMPLETION:\\n\\n----------------------\")\n # print(completion)\n # print(\"\\n------------------\")\n\n # Extract questions\n response_pattern = re.compile(\n r\"Question \\(based on text\\):\\n(.+)\", re.IGNORECASE | re.DOTALL\n )\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n print(\"-------------------\")\n pattern = re.compile(\n r\"(?:Question:|^\\d+[\\).]?)\\s*(.*?)\\s*\\n*Answer:\\s*(.*?)(?=(?:\\n\\s*(?:Question:|\\d+[\\).]?))|$)\",\n re.DOTALL | re.MULTILINE | re.IGNORECASE,\n )\n matches = pattern.findall(generation)\n if len(matches) > 0:\n print(\"Made Qs, yay!\")\n made_questions = True\n else:\n print(\"retry!\")\n retries += 1\n\n for match in matches:\n return (\n match[0].replace(\") \", \"\", 1).strip(),\n match[1].replace(\") \", \"\", 1).strip(),\n qatuple[2].replace(\") \", \"\", 1),\n qatuple[3],\n ), completion\n print(\"Should not have reached here\")\n print(matches)\n print(questions)\n return questions, completion\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n text = \"\"\"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\n\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\"\"\"\n\n plan = \"\"\"First, let's will analyze the text to determine what kinds of high-level questions I can ask that will test the content in these paragraphs (being careful to avoid mentioning the paragraphs explicitly in any questions, and being SURE to only ask about things that the paragraphs talk about). I will start by looking at one or two sentences at a time. Let's begin with: \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years.\" This paragraph is saying that people used to know only about 3,000 years of history, but now they know much more. So I might ask something like \"What was the time period in which people had limited knowledge?\" The question tests knowledge of when historical records were incomplete and therefore difficult to access. It requires understanding of the text as well as analysis to determine what time period is being referred to here. Next, I'll look at: \"Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end.\" This paragraph states that the universe seems infinite because of its reflection, but it could actually be finite with two ends. So I might ask something like \"How does the structure of the universe affect its size?\" This question tests understanding of the concept of reflection and how it can distort perceptions of size, as well as analysis to determine what implications this might have for the actual size of the universe. Then I'll move on: \"The earth ... circles about the sun in a slightly distorted and slowly variable oval path in a year.\" This paragraph talks about the Earth's orbit around the Sun. So I might ask something like \"What is the shape of the Earth's orbit around the sun?\" This question tests understanding of the text as well as analysis to determine the specific shape mentioned here. Lastly, let's examine: \"Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\" This paragraph says that the Earth's distance from the Sun changes throughout the year. So I might ask something like \"Why does the Earth's distance from the Sun change over the course of the year?\" This question tests understanding of the text as well as analysis to determine why this change occurs.\"\"\"\n print(\"Begin HGWELLS test\")\n # result = generate_question(text,plan,logic_llm)\n\n print(\"Begin MENDELEEV Test\")\n text2 = \"\"\"A substance or material is that which occupies space and has","source_hash":"f830a05f5b44bb4b61a30a14ede7204e7dcd479ded2e505bf88d7c9455e596ad","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.question_relevant_grammar","uri":"program://augmentoolkit/module/generation_functions.question_relevant_grammar#L1-L87","kind":"module","name":"generation_functions.question_relevant_grammar","path":"generation_functions/question_relevant_grammar.py","language":"python","start_line":1,"end_line":87,"context_start_line":1,"context_end_line":87,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n\n# We don't actually need the final judgement step, the step-by-step combined with the fact that it makes a judgement at each step ensures accuracy\nquestion_relevant_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Root rule specifying the overall structure of the reasoning and thought process\nroot ::= in-depth-analysis \"\\n\" detailed-understanding \"\\n\" targeted-comparison \"\\n\" critical-evaluation\n\n# In-depth analysis of the text\nin-depth-analysis ::= \"### In-Depth Analysis of the Text:\" \"\\n\" content-and-depth type-of-information\n\ncontent-and-depth ::= \"#### Content and Depth: \" text-description \"\\n\"\ntype-of-information ::= \"#### Type of Information: \" information-description \"\\n\"\n\n# Detailed understanding of the question\ndetailed-understanding ::= \"### Detailed Understanding of the Question:\" \"\\n\" core-requirement depth-of-detail\n\ncore-requirement ::= \"#### Core Requirement: \" requirement-description \"\\n\"\ndepth-of-detail ::= \"#### Depth of Detail: \" detail-description \"\\n\"\n\n# Targeted comparison of the question with the text\ntargeted-comparison ::= \"### Targeted Comparison of the Question with the Text:\" \"\\n\" content-match depth-match\n\ncontent-match ::= \"#### Content Match: \" match-description \"\\n\"\ndepth-match ::= \"#### Depth Match: \" depth-match-description \"\\n\"\n\n# Critical evaluation and final judgment\ncritical-evaluation ::= \"### Critical Evaluation and Final Judgment:\" \"\\n\" judgment\n\njudgment ::= [^\\n]+\n\n# Terminal symbols\ntext-description ::= [^\\n]+\ninformation-description ::= [^\\n]+\nrequirement-description ::= [^\\n]+\ndetail-description ::= [^\\n]+\nmatch-description ::= [^\\n]+\ndepth-match-description ::= [^\\n]+\nrelevance ::= \"Relevant.\" | \"Irrelevant.\"\n\n\n \n# root ::= reasoning from-the-text judgement\n\n# reasoning ::= \"First, I will check whether the question is answerable using the information in the paragraphs. The question asks \" [^\\n]+ \".\"\n# from-the-text ::= \"\\nNow, regardless of what my initial thoughts are, I will try to find some passages from the text that directly answer this question, being mindful that \\\"How\\\" is different than \\\"What\\\". The text has the following information: \" [^\\n]+ \".\"\n# judgement ::= \"\\nAll this considered, the answer is, compared to the provided text,\" (relevant|irrelevant) \".\"\n# relevant ::= \"relevant\" | \"Relevant\"\n# irrelevant ::= \"irrelevant\" | \"Irrelevant\"\n\n# final_step ::= \"Step \" [0-9]?[0-9] \". \" \"Final Judgement: \"\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")\n\n\n# from llama_cpp import LlamaGrammar\n\n# ### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n# question_relevant_grammar = LlamaGrammar.from_string(r\"\"\"\n\n# root ::= reasoning from-the-text judgement\n\n# reasoning ::= \"First, I will check whether the question is answerable using the information in the paragraphs. The question asks \" [^\\n]+ \".\"\n# from-the-text ::= \"\\nThe paragraphs, for their part, only mention the following information: \" [^\\n]+ \".\"\n# judgement ::= \"\\nAll this considered, the question is, compared to the provided text,\" (relevant|irrelevant) \".\"\n# relevant ::= \" relevant\" | \" Relevant\"\n# irrelevant ::= \" irrelevant\" | \" Irrelevant\"\n\n# \"\"\")\n\n# # question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# # root ::= answer\n# # answer ::= \"Test\"\n# # \"\"\")","source_hash":"9753b404b0af5c9af20da5f42c9edba2cbc566a572ff6aaa78599d7e47478e4f","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.strip_steps","uri":"program://augmentoolkit/module/generation_functions.strip_steps#L1-L55","kind":"module","name":"generation_functions.strip_steps","path":"generation_functions/strip_steps.py","language":"python","start_line":1,"end_line":55,"context_start_line":1,"context_end_line":55,"code":"def strip_steps(instruction_text):\n \"\"\"\n This function takes a string containing step-by-step instructions and removes the \"Step N.\" prefix from each line.\n\n Parameters:\n instruction_text (str): A string with each step in the format \"Step N. Instruction\", separated by newlines\n\n Returns:\n str: A single string with the steps stripped, joined by newlines.\n \"\"\"\n instructions = instruction_text.split(\"\\n\")\n stripped_instructions = []\n for line in instructions:\n # Check if line starts with 'Step' and followed by a number and period\n if line.strip().startswith(\"Step\") and \".\" in line:\n # Find the index of the first period\n period_index = line.find(\".\")\n # Extract the text after the period (and optional space)\n text_after_period = line[period_index + 1 :].lstrip()\n stripped_instructions.append(text_after_period)\n else:\n stripped_instructions.append(line)\n\n return \"\\n\".join(stripped_instructions)\n\n\nif __name__ == \"__main__\":\n # Example usage with a multi-line string\n example_instructions = \"\"\"\nStep 1. Analyze the Text: focus on the details provided about the beliefs ancient people had about the shape and movement of our world.\nStep 2. Identify Key Points: look for important concepts or ideas mentioned in the text.\n \"\"\"\n\n result = strip_steps(example_instructions)\n print(result)\n\n # Example with no space after the period\n example_non_instructions = \"\"\"\n Step1. This is a lovely\n normal\n paragraph\n Step2.Another test line without space after period\n \"\"\"\n\n result2 = strip_steps(example_non_instructions)\n\n print(result2)\n\n example_3 = \"\"\"\n Step 1. Analyze the Text: focus on the details provided about the history of the earth's shape.\nStep 2. Understand the Question: the question's focus is on what is known about the history of the earth's shape.\nStep 3. Compare the First Part of the Answer with the Text: check if the text supports the claim that the earth is a spheroid, or sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. It does, so this part is accurate. Then, check if the text supports the claim that its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years. The text confirms this, so this part is accurate. Check if the text supports the claim that before that time it was supposed to be flat. The text mentions various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets, but does not explicitly state that people believed the earth to be flat. So this part is inaccurate. Check if the text supports the claim that we know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameterevery twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles. The text confirms this, so this part is accurate.\nStep 4. Final Judgement: Since the answer is mostly accurate, the answer is accurate.\"\"\"\n result3 = strip_steps(example_3)\n print(result3)","source_hash":"24d41f7d8ede78731f2069f121c63eba7361a60fd8f78a833918e0824e397ad2","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.strip_steps.strip_steps","uri":"program://augmentoolkit/function/generation_functions.strip_steps.strip_steps#L1-L24","kind":"function","name":"strip_steps","path":"generation_functions/strip_steps.py","language":"python","start_line":1,"end_line":24,"context_start_line":1,"context_end_line":44,"code":"def strip_steps(instruction_text):\n \"\"\"\n This function takes a string containing step-by-step instructions and removes the \"Step N.\" prefix from each line.\n\n Parameters:\n instruction_text (str): A string with each step in the format \"Step N. Instruction\", separated by newlines\n\n Returns:\n str: A single string with the steps stripped, joined by newlines.\n \"\"\"\n instructions = instruction_text.split(\"\\n\")\n stripped_instructions = []\n for line in instructions:\n # Check if line starts with 'Step' and followed by a number and period\n if line.strip().startswith(\"Step\") and \".\" in line:\n # Find the index of the first period\n period_index = line.find(\".\")\n # Extract the text after the period (and optional space)\n text_after_period = line[period_index + 1 :].lstrip()\n stripped_instructions.append(text_after_period)\n else:\n stripped_instructions.append(line)\n\n return \"\\n\".join(stripped_instructions)\n\n\nif __name__ == \"__main__\":\n # Example usage with a multi-line string\n example_instructions = \"\"\"\nStep 1. Analyze the Text: focus on the details provided about the beliefs ancient people had about the shape and movement of our world.\nStep 2. Identify Key Points: look for important concepts or ideas mentioned in the text.\n \"\"\"\n\n result = strip_steps(example_instructions)\n print(result)\n\n # Example with no space after the period\n example_non_instructions = \"\"\"\n Step1. This is a lovely\n normal\n paragraph\n Step2.Another test line without space after period\n \"\"\"\n","source_hash":"24d41f7d8ede78731f2069f121c63eba7361a60fd8f78a833918e0824e397ad2","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.answer_relevant_grammar","uri":"program://augmentoolkit/module/generation_functions.answer_relevant_grammar#L1-L58","kind":"module","name":"generation_functions.answer_relevant_grammar","path":"generation_functions/answer_relevant_grammar.py","language":"python","start_line":1,"end_line":58,"context_start_line":1,"context_end_line":58,"code":"from llama_cpp import LlamaGrammar\n\nanswer_relevant_grammar = LlamaGrammar.from_string(\n r\"\"\" \n \n# Root rule specifying the overall structure of the analysis\nroot ::= deep-analysis \"\\n\" comprehensive-understanding \"\\n\" targeted-comparison \"\\n\" identification-of-extraneous-info \"\\n\" final-judgment\n\n# Deep analysis of the text\ndeep-analysis ::= \"### Deep Analysis of the Text:\" \"\\n\" content-scope-and-detail type-of-information\n\ncontent-scope-and-detail ::= \"#### Content Scope and Detail: \" text-detail \"\\n\"\ntype-of-information ::= \"#### Type of Information: \" info-type \"\\n\"\n\n# Comprehensive understanding of the answer\ncomprehensive-understanding ::= \"### Comprehensive Understanding of the Answer:\" \"\\n\" key-components-identification depth-of-explanation\n\nkey-components-identification ::= \"#### Key Components Identification: \" components-detail \"\\n\"\ndepth-of-explanation ::= \"#### Depth of Explanation: \" explanation-detail \"\\n\"\n\n# Targeted comparison of answer with text\ntargeted-comparison ::= \"### Targeted Comparison of Answer with Text:\" \"\\n\" content-alignment depth-alignment\n\ncontent-alignment ::= \"#### Content Alignment: \" alignment-detail \"\\n\"\ndepth-alignment ::= \"#### Depth Alignment: \" depth-detail \"\\n\"\n\n# Identification of extraneous information\nidentification-of-extraneous-info ::= \"### Identification of Extraneous Information:\" \"\\n\" spotting-additional-details assessing-impact\n\nspotting-additional-details ::= \"#### Spotting Additional Details: \" additional-details \"\\n\"\nassessing-impact ::= \"#### Assessing Impact of Additional Information: \" impact-assessment \"\\n\"\n\n# Final judgment on answer relevance\nfinal-judgment ::= \"### Final Judgment on Answer Relevance:\" \"\\n\" relevance-assessment explanation-of-judgment\n\nrelevance-assessment ::= \"#### Relevance Assessment: \" relevance-detail \"\\n\"\nexplanation-of-judgment ::= \"#### Explanation of Judgment: \" judgment-detail \"\\n\"\n\n# Terminal symbols\ntext-detail ::= [^\\n]+\ninfo-type ::= [^\\n]+\ncomponents-detail ::= [^\\n]+\nexplanation-detail ::= [^\\n]+\nalignment-detail ::= [^\\n]+\ndepth-detail ::= [^\\n]+\nadditional-details ::= [^\\n]+\nimpact-assessment ::= [^\\n]+\nrelevance-detail ::= [^\\n]+\njudgment-detail ::= [^\\n]+\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"982449c09f3b663632e5fe8b5ef5a1148346300ca327e057a9aaed2da7ecdd36","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_answer_relevancy_with_text","uri":"program://augmentoolkit/module/generation_functions.check_answer_relevancy_with_text#L1-L277","kind":"module","name":"generation_functions.check_answer_relevancy_with_text","path":"generation_functions/check_answer_relevancy_with_text.py","language":"python","start_line":1,"end_line":277,"context_start_line":1,"context_end_line":277,"code":"import re\nfrom .answer_relevant_grammar import answer_relevant_grammar\nfrom .constants import LOGICAL_MODEL\nfrom llama_cpp import Llama\n\n\n# Answer vetting\n# For now, this checks answer relevancy too. The danger with abstracting answer relevancy into a separate step is that anything which relies on knowledge that is obviously mentioned in the text already up until this point, will get screwed\ndef check_answer_relevancy_with_text(qatuple, logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Given a paragraph or two from a larger text, a question based on the paragraphs, and an answer to the question, you will make a determination as to whether the answer only uses the information in the paragraphs for its main points. Essentially: you will check if the answer is constrained to the information in the paragraphs provided. Your task includes first analyzing the answer, thinking through whether or not the answer reflects aspects of the paragraphs provided. \n\nFollowing this, at the very end of your response, you will write \"Relevant\" or \"Irrelevant\" depending on your analysis of the answer with regards to the text. \n\n### Instruction:\nText: \n\\\"\\\"\\\"\nPolar bears are primarily found in the Arctic Circle, where they have adapted to the harsh cold environment. Their diet is primarily based on marine mammals, with seals being the most crucial part of their diet. Polar bears are skilled hunters, often waiting by seals' breathing holes to catch their prey. Occasionally, they also eat birds, bird eggs, and small mammals. They also consume significant amounts of berries and fish. These bears are known for their ability to survive in extreme conditions, thanks to their thick fur and fat layers which provide insulation, as well as their efficient digestion system, which makes good use of the few nutrients available.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What are the primary food sources of polar bears?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"Polar bears primarily eat seals, but they also consume significant amounts of berries and fish. Their efficient digestion system, which has been studied through MRIs, allows them to process a wide variety of foods.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Deep Analysis of the Text:\n#### Content Scope and Detail: The text describes the diet of polar bears, focusing on their primary and secondary food sources.\n#### Type of Information: The information is descriptive, outlining what polar bears eat, including seals, birds, eggs, small mammals, berries, and fish.\n\n### Comprehensive Understanding of the Answer:\n#### Key Components Identification: The answer mentions seals, berries, fish, and the efficiency of the polar bears' digestive system, referencing MRIs.\n#### Depth of Explanation: The answer includes factual claims about the diet and a scientific statement about digestion studies.\n\n### Targeted Comparison of Answer with Text:\n#### Content Alignment: The claims about seals, berries, and fish align with the text.The reference to the digestive system's efficiency is supported but not the specific mention of MRIs.\n#### Depth Alignment: The depth of the answer regarding diet aligns with the text, but the detail about MRIs introduces unnecessary depth.\n\n### Identification of Extraneous Information:\n#### Spotting Additional Details: The MRI claim.\n#### Assessing Impact of Additional Information: The MRI detail, while interesting, is not supported by the text and deviates from the text's scope.\n\n### Final Judgment on Answer Relevance:\n#### Relevance Assessment: The answer is partially relevant but introduces unsupported details.\n#### Explanation of Judgment: Since the answer mostly aligns with the text but includes extraneous information (MRIs), the final judgment is: Irrelevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe Pythagorean theorem is a fundamental principle in geometry, stating that in a right-angled triangle, the square of the length of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the lengths of the other two sides. This theorem is often expressed as the equation a² + b² = c², where a and b are the lengths of the two sides that form the right angle, and c is the length of the hypotenuse. Historically, this theorem has been attributed to the ancient Greek mathematician Pythagoras, although evidence suggests it was known to mathematicians in several cultures before him.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What does the Pythagorean theorem state in the context of geometry?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"The Pythagorean theorem, crucial in geometry, states that in a right-angled triangle, a² + b² = c², where a and b are the perpendicular sides and c is the hypotenuse. Additionally, it is noteworthy that this theorem was utilized in ancient Egypt for land surveying purposes.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Deep Analysis of the Text:\n#### Content Scope and Detail: The text explains the Pythagorean theorem, its formula, and historical background.\n#### Type of Information: The information is descriptive and explanatory, detailing the theorem and its mathematical representation.\n\n### Comprehensive Understanding of the Answer:\n#### Key Components Identification: The answer describes the theorem, its geometric context, and its historical application in ancient Egypt.\n#### Depth of Explanation: The answer provides a mathematical explanation and historical context.\n\n### Targeted Comparison of Answer with Text:\n#### Content Alignment: The theorem's description and formula align with the text.The historical usage in ancient Egypt is not mentioned in the text.\n#### Depth Alignment: The depth of explanation on the theorem aligns, but the historical context does not.\n\n### Identification of Extraneous Information:\n#### Spotting Additional Details: The claim about ancient Egypt.\n#### Assessing Impact of Additional Information: This detail, while historically interesting, is not mentioned in the text and is irrelevant to the text's content.\n\n### Final Judgment on Answer Relevance:\n#### Relevance Assessment: The answer is partially relevant but includes significant extraneous historical information.\n#### Explanation of Judgment: Due to the inclusion of unsupported historical context, the final judgment is: Irrelevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nSigmund Freud, an Austrian neurologist and the father of psychoanalysis, introduced the concept of the unconscious mind. He suggested that the unconscious mind stores feelings, thoughts, and desires that are too threatening or painful for conscious awareness. Freud believed that these repressed elements could influence behavior and personality. One of his key methods for exploring the unconscious mind was through dream analysis, where he interpreted the meaning of dreams as a pathway to understanding the hidden desires and thoughts of the individual. Freud also developed the theory of the Oedipus complex, which proposes that during the phallic stage of psychosexual development, a male child experiences unconscious sexual desires for his mother and hostility toward his father.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What methods did Freud use to explore the unconscious mind, and what are some key concepts he introduced in this area?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"Freud used dream analysis as a method to explore the unconscious mind. He also introduced the concept of the Oedipus complex, suggesting that during a specific stage of development, a child experiences unconscious desires.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Deep Analysis of the Text:\n#### Content Scope and Detail: The text discusses Freud's methods for exploring the unconscious mind and key concepts he introduced.\n#### Type of Information: The information is descriptive, detailing Freud's methods and theories.\n\n### Comprehensive Understanding of the Answer:\n#### Key Components Identification: The answer mentions dream analysis and the Oedipus complex.\n#### Depth of Explanation: The answer provides a factual description of Freud's methods and concepts.\n\n### Targeted Comparison of Answer with Text:\n#### Content Alignment: The text directly supports the claims about dream analysis and the Oedipus complex.\n#### Depth Alignment: The depth of explanation in the answer aligns with the text's information.\n\n### Identification of Extraneous Information:\n#### Spotting Additional Details: The MRI claim.\n#### Assessing Impact of Additional Information: The MRI detail, while interesting, is not supported by the text and deviates from the text's scope.\n\n\n### Final Judgment on Answer Relevance:\n#### Relevance Assessment: The answer accurately reflects the text's content.\n#### Explanation of Judgment: Each part of the answer is directly supported by the text, so the final judgment is: Relevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe Library of Alexandria, one of the largest and most significant libraries of the ancient world, was dedicated to the Muses—the nine goddesses of the arts. It flourished under the patronage of the Ptolemaic dynasty and functioned as a major center of scholarship. The library was estimated to house anywhere between 40,000 to 400,000 scrolls at its peak. The destruction of the library, which occurred over several incidents, marked a significant loss of cultural and scientific knowledge.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What was the importance of the Library of Alexandria in the ancient world?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"The Library of Alexandria was crucial in the ancient world as a center of scholarship and cultural development. It housed a vast collection of works, providing scholars with access to knowledge from various fields. The library's destruction is often attributed to Julius Caesar's fire during the Siege of Alexandria, a claim supported by several historical documents and archaeological findings.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Deep Analysis of the Text:\n#### Content Scope and Detail: The text describes the Library of Alexandria's role, its size, patronage, and the impact of its destruction.\n#### Type of Information: The information is descriptive, focusing on the library's significance and general history.\n\n### Comprehensive Understanding of the Answer:\n#### Key Components Identification: The answer highlights the library's role in scholarship and cultural development and references its destruction by Julius Caesar's fire.\n#### Depth of Explanation: The answer provides both a general overview of the library's significance and specific historical claims regarding its destruction.\n\n### Targeted Comparison of Answer with Text:\n#### Content Alignment: The library's role as a center of scholarship and cultural development aligns with the text. The text does not mention Julius Caesar's fire or support this with historical documents and archaeological findings.\n#### Depth Alignment: While the answer aligns in depth regarding the library's role, the specific claim about Julius Caesar and the supporting evidence is a detailed addition not present in the text.\n\n### Identification of Extraneous Information:\n#### Spotting Additional Details: The specifics about Julius Caesar's fire and the mention of historical documents and archaeological findings.\n#### Assessing Impact of Additional Information: This additional information introduces a specific historical narrative and evidence not covered in the text, deviating from the text's content.\n\n### Final Judgment on Answer Relevance:\n#### Relevance Assessment: The answer starts correctly but introduces unsupported details about the library's destruction.\n#### Explanation of Judgment: Due to the inclusion of specific and unsupported historical details, the final judgment is: Irrelevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe planet Venus has a very dense atmosphere composed mainly of carbon dioxide, with clouds of sulfuric acid. This composition creates a runaway greenhouse effect, leading to surface temperatures hot enough to melt lead. Venus rotates very slowly on its axis, taking about 243 Earth days to complete one rotation, which is longer than its orbital period around the Sun. Interestingly, Venus rotates in the opposite direction to most planets in the solar system. This retrograde rotation is thought to be the result of a collision with a large celestial body early in its history.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What are the main characteristics of Venus's atmosphere and rotation?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"Venus's atmosphere is dense, primarily composed of carbon dioxide, and contains clouds of sulfuric acid, leading to extremely high temperatures. The planet has a unique rotation, taking 243 Earth days to rotate once and rotating in a retrograde direction due to gravitational interactions with Earth and other planets.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Deep Analysis of the Text:\n#### Content Scope and Detail: The text provides specific information on Venus's atmosphere and rotation.\n#### Type of Information: The text is descriptive, outlining the characteristics of Venus's atmosphere and rotation.\n\n### Comprehensive Understanding of the Answer:\n#### Key Components Identification: The answer discusses Venus's atmosphere, temperature, rotation period, direction, and the cause of its retrograde rotation.\n#### Depth of Explanation: The answer includes descriptive details and a causal explanation for the retrograde rotation.\n\n### Targeted Comparison of Answer with Text:\n#### Content Alignment: The claims about the atmosphere, temperature, rotation period, and direction align with the text.The text does not support the claim about gravitational interactions with Earth and other planets.\n#### Depth Alignment: The depth of the answer aligns with the text except for the unsupported causal explanation.\n\n### Identification of Extraneous Information:\n#### Spotting Additional Details: The cause of the retrograde rotation as gravitational interactions.\n#### Assessing Impact of Additional Information: This detail introduces an unsupported causal explanation and deviates from the text.\n\n### Final Judgment on Answer Relevance:\n#### Relevance Assessment: The answer is mostly relevant but introduces an unsupported causal claim.\n#### Explanation of Judgment: Due to the inclusion of an unsupported reason for Venus's retrograde rotation, the final judgment is: Irrelevant.\n\n\n### Instruction:\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process (be careful about extra details, even vague ones):\n\"\"\"\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=5500,\n stop=[\"\", \"# Input:\"],\n grammar=answer_relevant_grammar,\n echo=True,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n completion_pattern = re.compile(\n r\"Reasoning and thought process \\(be careful about extra details, even vague ones\\):\\n(.+)\",\n re.DOTALL | re.IGNORECASE,\n )\n judgement_pattern = re.compile(\n r\"Explanation of Judgment:(.+)\", re.DOTALL | re.IGNORECASE\n )\n response = completion_pattern.search(completion).group(1).strip()\n print(response)\n determination = judgement_pattern.search(response).group(1).strip()\n print(\"\\n\\nDETERMINATION:\\n------\")\n print(determination)\n print(\"\\n---------\\n\")\n if (\n \"irrelevant\" in determination.lower()\n or \"mostly\" in determination.lower()\n or \"partial\" in determination.lower()\n or \"introduces information not present in the text\"\n in determination.lower()\n ): # Hack to get around faulty 13b outputs\n return (False, response), completion\n elif \"relevant\" in determination or \"Relevant\" in determination:\n return (True, response), completion\n else:\n retries += 1\n except:\n retries += 1\n print(\n f\"Something went catastrophically wrong with this one. Investigate! Here's the completion:\\n{completion}\"\n )\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=8000,\n n_gpu_layers=1000,\n rope_freq_scale=0.33,\n rope_scaling_type=1,\n ) # load the logical LLM and offload everything\n q_test = [\n (\n \") Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. Wh\n# ... truncated ...","source_hash":"29bb4a1bf33470a88ef01228b29573b269eede05d85795fa71add4c58dcd8fcb","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_answer_relevancy_with_text.check_answer_relevancy_with_text","uri":"program://augmentoolkit/function/generation_functions.check_answer_relevancy_with_text.check_answer_relevancy_with_text#L9-L230","kind":"function","name":"check_answer_relevancy_with_text","path":"generation_functions/check_answer_relevancy_with_text.py","language":"python","start_line":9,"end_line":230,"context_start_line":1,"context_end_line":250,"code":"import re\nfrom .answer_relevant_grammar import answer_relevant_grammar\nfrom .constants import LOGICAL_MODEL\nfrom llama_cpp import Llama\n\n\n# Answer vetting\n# For now, this checks answer relevancy too. The danger with abstracting answer relevancy into a separate step is that anything which relies on knowledge that is obviously mentioned in the text already up until this point, will get screwed\ndef check_answer_relevancy_with_text(qatuple, logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Given a paragraph or two from a larger text, a question based on the paragraphs, and an answer to the question, you will make a determination as to whether the answer only uses the information in the paragraphs for its main points. Essentially: you will check if the answer is constrained to the information in the paragraphs provided. Your task includes first analyzing the answer, thinking through whether or not the answer reflects aspects of the paragraphs provided. \n\nFollowing this, at the very end of your response, you will write \"Relevant\" or \"Irrelevant\" depending on your analysis of the answer with regards to the text. \n\n### Instruction:\nText: \n\\\"\\\"\\\"\nPolar bears are primarily found in the Arctic Circle, where they have adapted to the harsh cold environment. Their diet is primarily based on marine mammals, with seals being the most crucial part of their diet. Polar bears are skilled hunters, often waiting by seals' breathing holes to catch their prey. Occasionally, they also eat birds, bird eggs, and small mammals. They also consume significant amounts of berries and fish. These bears are known for their ability to survive in extreme conditions, thanks to their thick fur and fat layers which provide insulation, as well as their efficient digestion system, which makes good use of the few nutrients available.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What are the primary food sources of polar bears?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"Polar bears primarily eat seals, but they also consume significant amounts of berries and fish. Their efficient digestion system, which has been studied through MRIs, allows them to process a wide variety of foods.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Deep Analysis of the Text:\n#### Content Scope and Detail: The text describes the diet of polar bears, focusing on their primary and secondary food sources.\n#### Type of Information: The information is descriptive, outlining what polar bears eat, including seals, birds, eggs, small mammals, berries, and fish.\n\n### Comprehensive Understanding of the Answer:\n#### Key Components Identification: The answer mentions seals, berries, fish, and the efficiency of the polar bears' digestive system, referencing MRIs.\n#### Depth of Explanation: The answer includes factual claims about the diet and a scientific statement about digestion studies.\n\n### Targeted Comparison of Answer with Text:\n#### Content Alignment: The claims about seals, berries, and fish align with the text.The reference to the digestive system's efficiency is supported but not the specific mention of MRIs.\n#### Depth Alignment: The depth of the answer regarding diet aligns with the text, but the detail about MRIs introduces unnecessary depth.\n\n### Identification of Extraneous Information:\n#### Spotting Additional Details: The MRI claim.\n#### Assessing Impact of Additional Information: The MRI detail, while interesting, is not supported by the text and deviates from the text's scope.\n\n### Final Judgment on Answer Relevance:\n#### Relevance Assessment: The answer is partially relevant but introduces unsupported details.\n#### Explanation of Judgment: Since the answer mostly aligns with the text but includes extraneous information (MRIs), the final judgment is: Irrelevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe Pythagorean theorem is a fundamental principle in geometry, stating that in a right-angled triangle, the square of the length of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the lengths of the other two sides. This theorem is often expressed as the equation a² + b² = c², where a and b are the lengths of the two sides that form the right angle, and c is the length of the hypotenuse. Historically, this theorem has been attributed to the ancient Greek mathematician Pythagoras, although evidence suggests it was known to mathematicians in several cultures before him.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What does the Pythagorean theorem state in the context of geometry?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"The Pythagorean theorem, crucial in geometry, states that in a right-angled triangle, a² + b² = c², where a and b are the perpendicular sides and c is the hypotenuse. Additionally, it is noteworthy that this theorem was utilized in ancient Egypt for land surveying purposes.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Deep Analysis of the Text:\n#### Content Scope and Detail: The text explains the Pythagorean theorem, its formula, and historical background.\n#### Type of Information: The information is descriptive and explanatory, detailing the theorem and its mathematical representation.\n\n### Comprehensive Understanding of the Answer:\n#### Key Components Identification: The answer describes the theorem, its geometric context, and its historical application in ancient Egypt.\n#### Depth of Explanation: The answer provides a mathematical explanation and historical context.\n\n### Targeted Comparison of Answer with Text:\n#### Content Alignment: The theorem's description and formula align with the text.The historical usage in ancient Egypt is not mentioned in the text.\n#### Depth Alignment: The depth of explanation on the theorem aligns, but the historical context does not.\n\n### Identification of Extraneous Information:\n#### Spotting Additional Details: The claim about ancient Egypt.\n#### Assessing Impact of Additional Information: This detail, while historically interesting, is not mentioned in the text and is irrelevant to the text's content.\n\n### Final Judgment on Answer Relevance:\n#### Relevance Assessment: The answer is partially relevant but includes significant extraneous historical information.\n#### Explanation of Judgment: Due to the inclusion of unsupported historical context, the final judgment is: Irrelevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nSigmund Freud, an Austrian neurologist and the father of psychoanalysis, introduced the concept of the unconscious mind. He suggested that the unconscious mind stores feelings, thoughts, and desires that are too threatening or painful for conscious awareness. Freud believed that these repressed elements could influence behavior and personality. One of his key methods for exploring the unconscious mind was through dream analysis, where he interpreted the meaning of dreams as a pathway to understanding the hidden desires and thoughts of the individual. Freud also developed the theory of the Oedipus complex, which proposes that during the phallic stage of psychosexual development, a male child experiences unconscious sexual desires for his mother and hostility toward his father.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What methods did Freud use to explore the unconscious mind, and what are some key concepts he introduced in this area?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"Freud used dream analysis as a method to explore the unconscious mind. He also introduced the concept of the Oedipus complex, suggesting that during a specific stage of development, a child experiences unconscious desires.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Deep Analysis of the Text:\n#### Content Scope and Detail: The text discusses Freud's methods for exploring the unconscious mind and key concepts he introduced.\n#### Type of Information: The information is descriptive, detailing Freud's methods and theories.\n\n### Comprehensive Understanding of the Answer:\n#### Key Components Identification: The answer mentions dream analysis and the Oedipus complex.\n#### Depth of Explanation: The answer provides a factual description of Freud's methods and concepts.\n\n### Targeted Comparison of Answer with Text:\n#### Content Alignment: The text directly supports the claims about dream analysis and the Oedipus complex.\n#### Depth Alignment: The depth of explanation in the answer aligns with the text's information.\n\n### Identification of Extraneous Information:\n#### Spotting Additional Details: The MRI claim.\n#### Assessing Impact of Additional Information: The MRI detail, while interesting, is not supported by the text and deviates from the text's scope.\n\n\n### Final Judgment on Answer Relevance:\n#### Relevance Assessment: The answer accurately reflects the text's content.\n#### Explanation of Judgment: Each part of the answer is directly supported by the text, so the final judgment is: Relevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe Library of Alexandria, one of the largest and most significant libraries of the ancient world, was dedicated to the Muses—the nine goddesses of the arts. It flourished under the patronage of the Ptolemaic dynasty and functioned as a major center of scholarship. The library was estimated to house anywhere between 40,000 to 400,000 scrolls at its peak. The destruction of the library, which occurred over several incidents, marked a significant loss of cultural and scientific knowledge.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What was the importance of the Library of Alexandria in the ancient world?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"The Library of Alexandria was crucial in the ancient world as a center of scholarship and cultural development. It housed a vast collection of works, providing scholars with access to knowledge from various fields. The library's destruction is often attributed to Julius Caesar's fire during the Siege of Alexandria, a claim supported by several historical documents and archaeological findings.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Deep Analysis of the Text:\n#### Content Scope and Detail: The text describes the Library of Alexandria's role, its size, patronage, and the impact of its destruction.\n#### Type of Information: The information is descriptive, focusing on the library's significance and general history.\n\n### Comprehensive Understanding of the Answer:\n#### Key Components Identification: The answer highlights the library's role in scholarship and cultural development and references its destruction by Julius Caesar's fire.\n#### Depth of Explanation: The answer provides both a general overview of the library's significance and specific historical claims regarding its destruction.\n\n### Targeted Comparison of Answer with Text:\n#### Content Alignment: The library's role as a center of scholarship and cultural development aligns with the text. The text does not mention Julius Caesar's fire or support this with historical documents and archaeological findings.\n#### Depth Alignment: While the answer aligns in depth regarding the library's role, the specific claim about Julius Caesar and the supporting evidence is a detailed addition not present in the text.\n\n### Identification of Extraneous Information:\n#### Spotting Additional Details: The specifics about Julius Caesar's fire and the mention of historical documents and archaeological findings.\n#### Assessing Impact of Additional Information: This additional information introduces a specific historical narrative and evidence not covered in the text, deviating from the text's content.\n\n### Final Judgment on Answer Relevance:\n#### Relevance Assessment: The answer starts correctly but introduces unsupported details about the library's destruction.\n#### Explanation of Judgment: Due to the inclusion of specific and unsupported historical details, the final judgment is: Irrelevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe planet Venus has a very dense atmosphere composed mainly of carbon dioxide, with clouds of sulfuric acid. This composition creates a runaway greenhouse effect, leading to surface temperatures hot enough to melt lead. Venus rotates very slowly on its axis, taking about 243 Earth days to complete one rotation, which is longer than its orbital period around the Sun. Interestingly, Venus rotates in the opposite direction to most planets in the solar system. This retrograde rotation is thought to be the result of a collision with a large celestial body early in its history.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What are the main characteristics of Venus's atmosphere and rotation?\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"Venus's atmosphere is dense, primarily composed of carbon dioxide, and contains clouds of sulfuric acid, leading to extremely high temperatures. The planet has a unique rotation, taking 243 Earth days to rotate once and rotating in a retrograde direction due to gravitational interactions with Earth and other planets.\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n### Deep Analysis of the Text:\n#### Content Scope and Detail: The text provides specific information on Venus's atmosphere and rotation.\n#### Type of Information: The text is descriptive, outlining the characteristics of Venus's atmosphere and rotation.\n\n### Comprehensive Understanding of the Answer:\n#### Key Components Identification: The answer discusses Venus's atmosphere, temperature, rotation period, direction, and the cause of its retrograde rotation.\n#### Depth of Explanation: The answer includes descriptive details and a causal explanation for the retrograde rotation.\n\n### Targeted Comparison of Answer with Text:\n#### Content Alignment: The claims about the atmosphere, temperature, rotation period, and direction align with the text.The text does not support the claim about gravitational interactions with Earth and other planets.\n#### Depth Alignment: The depth of the answer aligns with the text except for the unsupported causal explanation.\n\n### Identification of Extraneous Information:\n#### Spotting Additional Details: The cause of the retrograde rotation as gravitational interactions.\n#### Assessing Impact of Additional Information: This detail introduces an unsupported causal explanation and deviates from the text.\n\n### Final Judgment on Answer Relevance:\n#### Relevance Assessment: The answer is mostly relevant but introduces an unsupported causal claim.\n#### Explanation of Judgment: Due to the inclusion of an unsupported reason for Venus's retrograde rotation, the final judgment is: Irrelevant.\n\n\n### Instruction:\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nSupposed answer to the question (this is what you are fact-checking): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process (be careful about extra details, even vague ones):\n\"\"\"\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=5500,\n stop=[\"\", \"# Input:\"],\n grammar=answer_relevant_grammar,\n echo=True,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n completion_pattern = re.compile(\n r\"Reasoning and thought process \\(be careful about extra details, even vague ones\\):\\n(.+)\",\n re.DOTALL | re.IGNORECASE,\n )\n judgement_pattern = re.compile(\n r\"Explanation of Judgment:(.+)\", re.DOTALL | re.IGNORECASE\n )\n response = completion_pattern.search(completion).group(1).strip()\n print(response)\n determination = judgement_pattern.search(response).group(1).strip()\n print(\"\\n\\nDETERMINATION:\\n------\")\n print(determination)\n print(\"\\n---------\\n\")\n if (\n \"irrelevant\" in determination.lower()\n or \"mostly\" in determination.lower()\n or \"partial\" in determination.lower()\n or \"introduces information not present in the text\"\n in determination.lower()\n ): # Hack to get around faulty 13b outputs\n return (False, response), completion\n elif \"relevant\" in determination or \"Relevant\" in determination:\n return (True, response), completion\n else:\n retries += 1\n except:\n retries += 1\n print(\n f\"Something went catastrophically wrong with this one. Investigate! Here's the completion:\\n{completion}\"\n )\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=8000,\n n_gpu_layers=1000,\n rope_freq_scale=0.33,\n rope_scaling_type=1,\n ) # load the logical LLM and offload everything\n q_test = [\n (\n \") Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",","source_hash":"29bb4a1bf33470a88ef01228b29573b269eede05d85795fa71add4c58dcd8fcb","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.multi_turn_conversation","uri":"program://augmentoolkit/module/generation_functions.multi_turn_conversation#L1-L587","kind":"module","name":"generation_functions.multi_turn_conversation","path":"generation_functions/multi_turn_conversation.py","language":"python","start_line":1,"end_line":587,"context_start_line":1,"context_end_line":587,"code":"import re\nfrom .multi_turn_conversation_grammar import multi_turn_conversation_grammar\nfrom llama_cpp import Llama\nfrom llama_cpp import LlamaGrammar\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nfrom .extract_name import extract_name\nimport random\n\n# all characters in this prompt are over 18\n\n# Explanation of wtf the first few-shot example is:\n# No I do not have a teacher-student fetish, the reason why Elise is a teacher is an adaptation to the following three facts:\n# 1. This tool is meant to be able to generate data for training ERP bots by default\n# 2. This tool is also meant to be able to take in educational material by default\n# 3. When generating characters that would know about educational material, the model tends to generate academics or professors in that field, talking to students.\n# Given these facts, we clearly need to prompt the model to be able to generate horny teachers, or else it's going to just do it poorly when it realizes it has a sexualized character that's also a teacher. I didn't want to choose this, the constraints of the problem forced me to.\n\n\ndef extract_steps(text, steps=[2, 4, 5]):\n \"\"\"\n Extracts the specified steps from the text.\n\n Args:\n text (str): The input text containing various steps.\n steps (list of int): The step numbers to extract.\n\n Returns:\n str: A new string with each specified step's content on its own line.\n \"\"\"\n step_pattern = \"|\".join([f\"Step {step}\\.\" for step in steps])\n matches = re.findall(\n f\"({step_pattern})\\s*(.*?)\\s*(?=(Step \\d\\.|$))\", text, re.DOTALL\n )\n\n # Extract and join the matched content, skipping the \"Step n.\" part\n extracted_text = \"\\n\".join(match[1].strip() for match in matches)\n return extracted_text\n\n\ndef extract_first_words(character_name, text):\n # Regular expression pattern to extract first word after the character's name\n pattern = rf\"{character_name}: \\\"(\\w+)\"\n\n # Find all matches in the text\n matches = re.findall(pattern, text)\n\n return matches\n\n\ndef multi_turn_conversation(\n qatuples, character, scenario, scenario_plan, logic_llm, assistant_mode=False\n):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n charname = extract_name(character)\n first_words_of_card = extract_first_words(charname, character)\n conv_starters = [ # prevents it from regurgitating the card (when combined with filtering)\n \"Ah\",\n \"Oh\",\n # \"You\",\n # \"Really\",\n \"I\",\n # \"What\",\n # \"So\",\n \"Welcome\",\n \"Hey\",\n # \"Look\",\n # \"Now\",\n # \"Huh\",\n \"It's\",\n \"Hello\",\n ]\n\n conv_starters_filtered = [\n starter for starter in conv_starters if starter not in first_words_of_card\n ]\n conv_starter = random.choice(conv_starters_filtered)\n print(\"--CONV STARTERS FILTERED--\")\n print(conv_starters_filtered)\n\n # Create grammar based off of # questions\n\n # if (len(qatuples) == 1):\n multi_turn_conversation_grammar = LlamaGrammar.from_string(\n f\"\"\"\n\n # The root rule defines the structure of the dialogue\n root ::= [^\\\\n]+ \"\\\\n\" question-1 anything\n\n # Define constants acquired from code\n character-name ::= \"{charname}\"\n \n intro-statement ::= character-name \":\" [^\\\\n]+\n \n # Statement by Secondary Character\n question-1 ::= [^\\\\n]+ \":\" [^\\\\n]+\n \n # Statement by Primary Character\n \n anything ::= [^\\\\t]+\n\n \"\"\"\n )\n\n # NOTE Immediately below is a very long comment that tried to use a dynamic grammar to force the question to directly quote the question from the question-answer tuples. Using it makes this step prone to freezing, because if the model asks the question but fails to exactly quote the part of the question in the grammar, it won't be allowed to end that dialogue line until it generates that line. Which it will basically never do. So it just generates until it runs out of ctx.\n # NOTE If you want to try and fix it, go ahead, but I do not encourage spending time on this bit. If you do want to do it, I recommend just getting the conv started off the right way, with the first question and answer; the llm should get the rest right if it gets the start right.\n\n # if (len(qatuples) == 2):\n # multi_turn_conversation_grammar = LlamaGrammar.from_string(f\"\"\"\n\n # # The root rule defines the structure of the dialogue\n # root ::= intro-statement \"\\\\n\" question-1 \"\\\\n\" answer-1 \"\\\\n\" question-2 \"\\\\n\" answer-2 \"\\\\n\"\n\n # # Define constants acquired from code\n # character-name ::= \"{charname}\"\n\n # question-1-content ::= \"{qatuples[0][0]}\"\n # answer-1-content ::= \"{qatuples[0][1]}\"\n # question-2-content ::= \"{qatuples[1][0]}\"\n # answer-2-content ::= \"{qatuples[1][1]}\"\n\n # intro-statement ::= character-name \":\" [^\\\\n]+\n\n # # Question by Secondary Character\n # question-1 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-1-content [^\\\\n]+\n # question-2 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-2-content [^\\\\n]+\n\n # # Answer by Primary Character\n # answer-1 ::= character-name \":\" [^\\\\n]+ answer-1-content [^\\\\n]+\n # answer-2 ::= character-name \":\" [^\\\\n]+ answer-2-content [^\\\\n]+\n\n # \"\"\")\n\n # if (len(qatuples) == 3):\n # multi_turn_conversation_grammar = LlamaGrammar.from_string(f\"\"\"\n\n # # The root rule defines the structure of the dialogue\n # root ::= intro-statement \"\\\\n\" question-1 \"\\\\n\" answer-1 \"\\\\n\" question-2 \"\\\\n\" answer-2 \"\\\\n\" question-3 \"\\\\n\" answer-3 \"\\\\n\"\n\n # # Define constants acquired from code\n # character-name ::= \"{charname}\"\n\n # question-1-content ::= \"{qatuples[0][0]}\"\n # answer-1-content ::= \"{qatuples[0][1]}\"\n # question-2-content ::= \"{qatuples[1][0]}\"\n # answer-2-content ::= \"{qatuples[1][1]}\"\n # question-3-content ::= \"{qatuples[2][0]}\"\n # answer-3-content ::= \"{qatuples[2][1]}\"\n\n # intro-statement ::= character-name \":\" [^\\\\n]+\n\n # # Question by Secondary Character\n # question-1 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-1-content [^\\\\n]+\n # question-2 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-2-content [^\\\\n]+\n # question-3 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-3-content [^\\\\n]+\n\n # # Answer by Primary Character\n # answer-1 ::= character-name \":\" [^\\\\n]+ answer-1-content [^\\\\n]+\n # answer-2 ::= character-name \":\" [^\\\\n]+ answer-2-content [^\\\\n]+\n # answer-3 ::= character-name \":\" [^\\\\n]+ answer-3-content [^\\\\n]+\n\n # \"\"\")\n\n # if (len(qatuples) == 4):\n # multi_turn_conversation_grammar = LlamaGrammar.from_string(f\"\"\"\n\n # # The root rule defines the structure of the dialogue\n # root ::= intro-statement \"\\\\n\" question-1 \"\\\\n\" answer-1 \"\\\\n\" question-2 \"\\\\n\" answer-2 \"\\\\n\" question-3 \"\\\\n\" answer-3 \"\\\\n\" question-4 \"\\\\n\" answer-4 \"\\\\n\"\n\n # # Define constants acquired from code\n # character-name ::= \"{charname}\"\n\n # question-1-content ::= \"{qatuples[0][0]}\"\n # answer-1-content ::= \"{qatuples[0][1]}\"\n # question-2-content ::= \"{qatuples[1][0]}\"\n # answer-2-content ::= \"{qatuples[1][1]}\"\n # question-3-content ::= \"{qatuples[2][0]}\"\n # answer-3-content ::= \"{qatuples[2][1]}\"\n # question-4-content ::= \"{qatuples[3][0]}\"\n # answer-4-content ::= \"{qatuples[3][1]}\"\n\n # intro-statement ::= character-name \":\" [^\\\\n]+\n\n # # Question by Secondary Character\n # question-1 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-1-content [^\\\\n]+\n # question-2 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-2-content [^\\\\n]+\n # question-3 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-3-content [^\\\\n]+\n # question-4 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-4-content [^\\\\n]+\n\n # # Answer by Primary Character\n # answer-1 ::= character-name \":\" [^\\\\n]+ answer-1-content [^\\\\n]+\n # answer-2 ::= character-name \":\" [^\\\\n]+ answer-2-content [^\\\\n]+\n # answer-3 ::= character-name \":\" [^\\\\n]+ answer-3-content [^\\\\n]+\n # answer-4 ::= character-name \":\" [^\\\\n]+ answer-4-content [^\\\\n]+\n\n # \"\"\")\n\n if assistant_mode:\n character = \"AI Assistant\"\n scenario = \"A conversation between a helpful AI Assistant, and a user.\"\n scenario_plan = \"N/A\"\n charname = \"AI Assistant\"\n cot_prompt = f\"\"\"You are an expert at creative writing and educational material. You will write a short conversation between a curious user and a helpful AI assistant, in which the user asks some questions and the AI assistant answers them. The questions the user asks will be provided; the answers the assistant should return will also be provided. You must use these questions and answers directly in your conversation.\n \nKeep the conversation natural.\n\n## Information:\nQuestion: \\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What role does the y-intercept 'b' play in graphing a linear function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In what fields might you use linear and quadratic functions?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\\\"\\\"\\\"\n\nThe AI's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from The AI Assistant should be some sort of greeting that sets up the interaction. The user will then ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. The AI will be neutral in its tone throughout the conversation. It may surround its answer with \"conversational fluff\" (such as acknowledging the user's question). The user may surround its own questions with human-like informalities.\n\n### Response:\n## Conversation that answers the provided questions:\nAI Assistant: Hello! I'm here to help with any questions you might have. Feel free to ask away!\n\nUser: I was wondering about something in math. How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\nAI Assistant: Great question! The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph. Do you have any further questions about linear functions?\nUser: Yes, actually. What role does the y-intercept 'b' play in graphing a linear function?\nAI Assistant: Good question! The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis. Can I assist you further with linear functions?\nUser: Moving on to another type of function, in the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\nAI Assistant: The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola. Anything else you want to know about quadratic functions?\nUser: Yes, one more. In what fields might you use linear and quadratic functions?\nAI Assistant: Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering. Anything else you'd like to know about linear and quadratic functions?\n\n## Information:\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects.\\\"\\\"\\\"\n\nThe AI's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from The AI Assistant should be some sort of greeting that sets up the interaction. The user will then ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. The AI will be neutral in its tone throughout the conversation. It may surround its answer with \"conversational fluff\" (such as acknowledging the user's question). The user may surround its own questions with human-like informalities.\n\n### Response:\n## Conversation that answers the provided questions:\nAI Assistant: Hello! I'm here to help you with any questions you might have. What's on your mind today?\nUser: I was reading about the Panama Canal and got curious, how much earth was excavated during its construction?\nAI Assistant: That's a great question! Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project. Do you have any further questions about the Panama Canal?\nUser: Wow, that is massive! Also, I heard there were some health challenges. What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\nAI Assistant: Indeed, the construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects. Do you want to know anything else about the Panama Canal?\n\n## Information:\nQuestion: \\\"\\\"\\\"What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"They need the acknowledgement and admiration of others. Take the line from 'Thus Spake Zarathustra' by Friedrich Nietzsche: \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"Recite a famous quote from Thus Spake Zaranthustra that likens the solitary gathering of wisdom to a bee gathering honey.\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"\"Lo! I am weary of my wisdom, like the bee that hath gathered too much honey; I need hands outstretched to take it.\"\\\"\\\"\\\"\n\nThe AI's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from The AI Assistant should be some sort of greeting that sets up the interaction. The user will then ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. The AI will be neutral in its tone throughout the conversation. It may surround its answer with \"conversational fluff\" (such as acknowledging the user's question). The user may surround its own questions with human-like informalities.\n\n### Response:\n## Conversation that answers the provided questions:\nAI Assistant: Good day! I'm here to assist with any questions or insights you might seek. Please, feel free to ask anything.\nUser: What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\nAI Assistant: That's a profound question. They need the acknowledgement and admiration of others. Take the line from 'Thus Spake Zarathustra' by Friedrich Nietzsche: \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring. Do you want to know more about Thus Spake Zarathustra?\nUser: Recite a famous quote from Thus Spake Zaranthustra that likens the solitary gathering of wisdom to a bee gathering honey.\nAI Assistant: Certainly. Nietzsche once wrote, \"Lo! I am weary of my wisdom, like the bee that hath gathered too much honey; I need hands outstretched to take it.\" Do you have any more questions about Nietzsche or his works?\n\n## Information:\n{format_qatuples(qatuples)}\n\nThe AI's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from The AI Assistant should be some sort of greeting that sets up the interaction. The user will then ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. The AI will be neutral in its tone throughout the conversation. It may surround its answer with \"conversational fluff\" (such as acknowledging the user's question). The user may surround its own questions with human-like informalities.\n\n### Response:\n## Conversation that answers the provided question (be sure that you do not change the questions or answers themselves; {charname} will answer the questions, not ask them; the questions and answers provided should be copied word for word, and surrounded by compelling conversation):\nAI Assistant:\"\"\"\n else:\n extra_info = extract_steps(scenario_plan)\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. You will write a short conversation in which a secondary character asks some questions (one at a time) and the primary character answers them (also one at a time). \n\nWrite compellingly. Each character should have a distinct voice that reflects their background, personality, and current emotional state. This helps in making dialogue more realistic and engaging.\n\n## Information:\nComment: Alright let's get this started. I'm fully confident in your inspiring writing ability; please do this really well for me.\n\nHere's the primary character for the next scene:\n\\\"\\\"\\\"\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" Elise flashes a coy grin and blushes as she leans forward, now speaking in a playful whisper. Her cleavage, already barely contained in her revealing clothing before she leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, Elise casts her gaze downward and unconsciously fiddles with a strand of her hair. \"THEY'RE ALL WAY TOO STUCK UP!\" she nea\n# ... truncated ...","source_hash":"a2b005d24d5f03cc1e0ee763ccba16d9f361c4726afb41f8542af38015efec82","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.multi_turn_conversation.extract_steps","uri":"program://augmentoolkit/function/generation_functions.multi_turn_conversation.extract_steps#L20-L38","kind":"function","name":"extract_steps","path":"generation_functions/multi_turn_conversation.py","language":"python","start_line":20,"end_line":38,"context_start_line":1,"context_end_line":58,"code":"import re\nfrom .multi_turn_conversation_grammar import multi_turn_conversation_grammar\nfrom llama_cpp import Llama\nfrom llama_cpp import LlamaGrammar\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nfrom .extract_name import extract_name\nimport random\n\n# all characters in this prompt are over 18\n\n# Explanation of wtf the first few-shot example is:\n# No I do not have a teacher-student fetish, the reason why Elise is a teacher is an adaptation to the following three facts:\n# 1. This tool is meant to be able to generate data for training ERP bots by default\n# 2. This tool is also meant to be able to take in educational material by default\n# 3. When generating characters that would know about educational material, the model tends to generate academics or professors in that field, talking to students.\n# Given these facts, we clearly need to prompt the model to be able to generate horny teachers, or else it's going to just do it poorly when it realizes it has a sexualized character that's also a teacher. I didn't want to choose this, the constraints of the problem forced me to.\n\n\ndef extract_steps(text, steps=[2, 4, 5]):\n \"\"\"\n Extracts the specified steps from the text.\n\n Args:\n text (str): The input text containing various steps.\n steps (list of int): The step numbers to extract.\n\n Returns:\n str: A new string with each specified step's content on its own line.\n \"\"\"\n step_pattern = \"|\".join([f\"Step {step}\\.\" for step in steps])\n matches = re.findall(\n f\"({step_pattern})\\s*(.*?)\\s*(?=(Step \\d\\.|$))\", text, re.DOTALL\n )\n\n # Extract and join the matched content, skipping the \"Step n.\" part\n extracted_text = \"\\n\".join(match[1].strip() for match in matches)\n return extracted_text\n\n\ndef extract_first_words(character_name, text):\n # Regular expression pattern to extract first word after the character's name\n pattern = rf\"{character_name}: \\\"(\\w+)\"\n\n # Find all matches in the text\n matches = re.findall(pattern, text)\n\n return matches\n\n\ndef multi_turn_conversation(\n qatuples, character, scenario, scenario_plan, logic_llm, assistant_mode=False\n):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"","source_hash":"a2b005d24d5f03cc1e0ee763ccba16d9f361c4726afb41f8542af38015efec82","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.multi_turn_conversation.extract_first_words","uri":"program://augmentoolkit/function/generation_functions.multi_turn_conversation.extract_first_words#L41-L48","kind":"function","name":"extract_first_words","path":"generation_functions/multi_turn_conversation.py","language":"python","start_line":41,"end_line":48,"context_start_line":21,"context_end_line":68,"code":" \"\"\"\n Extracts the specified steps from the text.\n\n Args:\n text (str): The input text containing various steps.\n steps (list of int): The step numbers to extract.\n\n Returns:\n str: A new string with each specified step's content on its own line.\n \"\"\"\n step_pattern = \"|\".join([f\"Step {step}\\.\" for step in steps])\n matches = re.findall(\n f\"({step_pattern})\\s*(.*?)\\s*(?=(Step \\d\\.|$))\", text, re.DOTALL\n )\n\n # Extract and join the matched content, skipping the \"Step n.\" part\n extracted_text = \"\\n\".join(match[1].strip() for match in matches)\n return extracted_text\n\n\ndef extract_first_words(character_name, text):\n # Regular expression pattern to extract first word after the character's name\n pattern = rf\"{character_name}: \\\"(\\w+)\"\n\n # Find all matches in the text\n matches = re.findall(pattern, text)\n\n return matches\n\n\ndef multi_turn_conversation(\n qatuples, character, scenario, scenario_plan, logic_llm, assistant_mode=False\n):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n charname = extract_name(character)\n first_words_of_card = extract_first_words(charname, character)\n conv_starters = [ # prevents it from regurgitating the card (when combined with filtering)\n \"Ah\",\n \"Oh\",\n # \"You\",\n # \"Really\",\n \"I\",\n # \"What\",","source_hash":"a2b005d24d5f03cc1e0ee763ccba16d9f361c4726afb41f8542af38015efec82","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.multi_turn_conversation.multi_turn_conversation","uri":"program://augmentoolkit/function/generation_functions.multi_turn_conversation.multi_turn_conversation#L51-L441","kind":"function","name":"multi_turn_conversation","path":"generation_functions/multi_turn_conversation.py","language":"python","start_line":51,"end_line":441,"context_start_line":31,"context_end_line":461,"code":" step_pattern = \"|\".join([f\"Step {step}\\.\" for step in steps])\n matches = re.findall(\n f\"({step_pattern})\\s*(.*?)\\s*(?=(Step \\d\\.|$))\", text, re.DOTALL\n )\n\n # Extract and join the matched content, skipping the \"Step n.\" part\n extracted_text = \"\\n\".join(match[1].strip() for match in matches)\n return extracted_text\n\n\ndef extract_first_words(character_name, text):\n # Regular expression pattern to extract first word after the character's name\n pattern = rf\"{character_name}: \\\"(\\w+)\"\n\n # Find all matches in the text\n matches = re.findall(pattern, text)\n\n return matches\n\n\ndef multi_turn_conversation(\n qatuples, character, scenario, scenario_plan, logic_llm, assistant_mode=False\n):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n charname = extract_name(character)\n first_words_of_card = extract_first_words(charname, character)\n conv_starters = [ # prevents it from regurgitating the card (when combined with filtering)\n \"Ah\",\n \"Oh\",\n # \"You\",\n # \"Really\",\n \"I\",\n # \"What\",\n # \"So\",\n \"Welcome\",\n \"Hey\",\n # \"Look\",\n # \"Now\",\n # \"Huh\",\n \"It's\",\n \"Hello\",\n ]\n\n conv_starters_filtered = [\n starter for starter in conv_starters if starter not in first_words_of_card\n ]\n conv_starter = random.choice(conv_starters_filtered)\n print(\"--CONV STARTERS FILTERED--\")\n print(conv_starters_filtered)\n\n # Create grammar based off of # questions\n\n # if (len(qatuples) == 1):\n multi_turn_conversation_grammar = LlamaGrammar.from_string(\n f\"\"\"\n\n # The root rule defines the structure of the dialogue\n root ::= [^\\\\n]+ \"\\\\n\" question-1 anything\n\n # Define constants acquired from code\n character-name ::= \"{charname}\"\n \n intro-statement ::= character-name \":\" [^\\\\n]+\n \n # Statement by Secondary Character\n question-1 ::= [^\\\\n]+ \":\" [^\\\\n]+\n \n # Statement by Primary Character\n \n anything ::= [^\\\\t]+\n\n \"\"\"\n )\n\n # NOTE Immediately below is a very long comment that tried to use a dynamic grammar to force the question to directly quote the question from the question-answer tuples. Using it makes this step prone to freezing, because if the model asks the question but fails to exactly quote the part of the question in the grammar, it won't be allowed to end that dialogue line until it generates that line. Which it will basically never do. So it just generates until it runs out of ctx.\n # NOTE If you want to try and fix it, go ahead, but I do not encourage spending time on this bit. If you do want to do it, I recommend just getting the conv started off the right way, with the first question and answer; the llm should get the rest right if it gets the start right.\n\n # if (len(qatuples) == 2):\n # multi_turn_conversation_grammar = LlamaGrammar.from_string(f\"\"\"\n\n # # The root rule defines the structure of the dialogue\n # root ::= intro-statement \"\\\\n\" question-1 \"\\\\n\" answer-1 \"\\\\n\" question-2 \"\\\\n\" answer-2 \"\\\\n\"\n\n # # Define constants acquired from code\n # character-name ::= \"{charname}\"\n\n # question-1-content ::= \"{qatuples[0][0]}\"\n # answer-1-content ::= \"{qatuples[0][1]}\"\n # question-2-content ::= \"{qatuples[1][0]}\"\n # answer-2-content ::= \"{qatuples[1][1]}\"\n\n # intro-statement ::= character-name \":\" [^\\\\n]+\n\n # # Question by Secondary Character\n # question-1 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-1-content [^\\\\n]+\n # question-2 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-2-content [^\\\\n]+\n\n # # Answer by Primary Character\n # answer-1 ::= character-name \":\" [^\\\\n]+ answer-1-content [^\\\\n]+\n # answer-2 ::= character-name \":\" [^\\\\n]+ answer-2-content [^\\\\n]+\n\n # \"\"\")\n\n # if (len(qatuples) == 3):\n # multi_turn_conversation_grammar = LlamaGrammar.from_string(f\"\"\"\n\n # # The root rule defines the structure of the dialogue\n # root ::= intro-statement \"\\\\n\" question-1 \"\\\\n\" answer-1 \"\\\\n\" question-2 \"\\\\n\" answer-2 \"\\\\n\" question-3 \"\\\\n\" answer-3 \"\\\\n\"\n\n # # Define constants acquired from code\n # character-name ::= \"{charname}\"\n\n # question-1-content ::= \"{qatuples[0][0]}\"\n # answer-1-content ::= \"{qatuples[0][1]}\"\n # question-2-content ::= \"{qatuples[1][0]}\"\n # answer-2-content ::= \"{qatuples[1][1]}\"\n # question-3-content ::= \"{qatuples[2][0]}\"\n # answer-3-content ::= \"{qatuples[2][1]}\"\n\n # intro-statement ::= character-name \":\" [^\\\\n]+\n\n # # Question by Secondary Character\n # question-1 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-1-content [^\\\\n]+\n # question-2 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-2-content [^\\\\n]+\n # question-3 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-3-content [^\\\\n]+\n\n # # Answer by Primary Character\n # answer-1 ::= character-name \":\" [^\\\\n]+ answer-1-content [^\\\\n]+\n # answer-2 ::= character-name \":\" [^\\\\n]+ answer-2-content [^\\\\n]+\n # answer-3 ::= character-name \":\" [^\\\\n]+ answer-3-content [^\\\\n]+\n\n # \"\"\")\n\n # if (len(qatuples) == 4):\n # multi_turn_conversation_grammar = LlamaGrammar.from_string(f\"\"\"\n\n # # The root rule defines the structure of the dialogue\n # root ::= intro-statement \"\\\\n\" question-1 \"\\\\n\" answer-1 \"\\\\n\" question-2 \"\\\\n\" answer-2 \"\\\\n\" question-3 \"\\\\n\" answer-3 \"\\\\n\" question-4 \"\\\\n\" answer-4 \"\\\\n\"\n\n # # Define constants acquired from code\n # character-name ::= \"{charname}\"\n\n # question-1-content ::= \"{qatuples[0][0]}\"\n # answer-1-content ::= \"{qatuples[0][1]}\"\n # question-2-content ::= \"{qatuples[1][0]}\"\n # answer-2-content ::= \"{qatuples[1][1]}\"\n # question-3-content ::= \"{qatuples[2][0]}\"\n # answer-3-content ::= \"{qatuples[2][1]}\"\n # question-4-content ::= \"{qatuples[3][0]}\"\n # answer-4-content ::= \"{qatuples[3][1]}\"\n\n # intro-statement ::= character-name \":\" [^\\\\n]+\n\n # # Question by Secondary Character\n # question-1 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-1-content [^\\\\n]+\n # question-2 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-2-content [^\\\\n]+\n # question-3 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-3-content [^\\\\n]+\n # question-4 ::= [^\\\\n]+ \":\" [^\\\\n]+ question-4-content [^\\\\n]+\n\n # # Answer by Primary Character\n # answer-1 ::= character-name \":\" [^\\\\n]+ answer-1-content [^\\\\n]+\n # answer-2 ::= character-name \":\" [^\\\\n]+ answer-2-content [^\\\\n]+\n # answer-3 ::= character-name \":\" [^\\\\n]+ answer-3-content [^\\\\n]+\n # answer-4 ::= character-name \":\" [^\\\\n]+ answer-4-content [^\\\\n]+\n\n # \"\"\")\n\n if assistant_mode:\n character = \"AI Assistant\"\n scenario = \"A conversation between a helpful AI Assistant, and a user.\"\n scenario_plan = \"N/A\"\n charname = \"AI Assistant\"\n cot_prompt = f\"\"\"You are an expert at creative writing and educational material. You will write a short conversation between a curious user and a helpful AI assistant, in which the user asks some questions and the AI assistant answers them. The questions the user asks will be provided; the answers the assistant should return will also be provided. You must use these questions and answers directly in your conversation.\n \nKeep the conversation natural.\n\n## Information:\nQuestion: \\\"\\\"\\\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What role does the y-intercept 'b' play in graphing a linear function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"In what fields might you use linear and quadratic functions?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\\\"\\\"\\\"\n\nThe AI's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from The AI Assistant should be some sort of greeting that sets up the interaction. The user will then ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. The AI will be neutral in its tone throughout the conversation. It may surround its answer with \"conversational fluff\" (such as acknowledging the user's question). The user may surround its own questions with human-like informalities.\n\n### Response:\n## Conversation that answers the provided questions:\nAI Assistant: Hello! I'm here to help with any questions you might have. Feel free to ask away!\n\nUser: I was wondering about something in math. How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\nAI Assistant: Great question! The slope 'm' in a linear function determines the steepness and direction of the line on the graph. A positive slope means the line ascends from left to right, while a negative slope indicates it descends. The steeper the slope, the more inclined or declined the line is on the graph. Do you have any further questions about linear functions?\nUser: Yes, actually. What role does the y-intercept 'b' play in graphing a linear function?\nAI Assistant: Good question! The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis. Can I assist you further with linear functions?\nUser: Moving on to another type of function, in the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\nAI Assistant: The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola. Anything else you want to know about quadratic functions?\nUser: Yes, one more. In what fields might you use linear and quadratic functions?\nAI Assistant: Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering. Anything else you'd like to know about linear and quadratic functions?\n\n## Information:\nQuestion: \\\"\\\"\\\"How much earth was excavated during the construction of the Panama Canal?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"The construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects.\\\"\\\"\\\"\n\nThe AI's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from The AI Assistant should be some sort of greeting that sets up the interaction. The user will then ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. The AI will be neutral in its tone throughout the conversation. It may surround its answer with \"conversational fluff\" (such as acknowledging the user's question). The user may surround its own questions with human-like informalities.\n\n### Response:\n## Conversation that answers the provided questions:\nAI Assistant: Hello! I'm here to help you with any questions you might have. What's on your mind today?\nUser: I was reading about the Panama Canal and got curious, how much earth was excavated during its construction?\nAI Assistant: That's a great question! Over 200 million cubic yards of earth were excavated during the construction of the Panama Canal, showcasing the scale of this massive engineering project. Do you have any further questions about the Panama Canal?\nUser: Wow, that is massive! Also, I heard there were some health challenges. What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\nAI Assistant: Indeed, the construction faced significant health challenges, notably malaria and yellow fever. These were overcome through extensive public health measures, illustrating the importance of health considerations in large-scale engineering projects. Do you want to know anything else about the Panama Canal?\n\n## Information:\nQuestion: \\\"\\\"\\\"What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"They need the acknowledgement and admiration of others. Take the line from 'Thus Spake Zarathustra' by Friedrich Nietzsche: \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring.\\\"\\\"\\\"\n\nQuestion: \\\"\\\"\\\"Recite a famous quote from Thus Spake Zaranthustra that likens the solitary gathering of wisdom to a bee gathering honey.\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"\"Lo! I am weary of my wisdom, like the bee that hath gathered too much honey; I need hands outstretched to take it.\"\\\"\\\"\\\"\n\nThe AI's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from The AI Assistant should be some sort of greeting that sets up the interaction. The user will then ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. The AI will be neutral in its tone throughout the conversation. It may surround its answer with \"conversational fluff\" (such as acknowledging the user's question). The user may surround its own questions with human-like informalities.\n\n### Response:\n## Conversation that answers the provided questions:\nAI Assistant: Good day! I'm here to assist with any questions or insights you might seek. Please, feel free to ask anything.\nUser: What do people undergoing difficult journeys or possessing wisdom need, in order to make their efforts more bearable?\nAI Assistant: That's a profound question. They need the acknowledgement and admiration of others. Take the line from 'Thus Spake Zarathustra' by Friedrich Nietzsche: \"Thou great star! What would be thy happiness if thou hadst not those for whom thou shinest?\" This implies that even the wisest or the most enlightened individuals crave recognition for their efforts and wisdom, in order to further develop said wisdom and expend said efforts. They need others to see and appreciate the light they bring. Do you want to know more about Thus Spake Zarathustra?\nUser: Recite a famous quote from Thus Spake Zaranthustra that likens the solitary gathering of wisdom to a bee gathering honey.\nAI Assistant: Certainly. Nietzsche once wrote, \"Lo! I am weary of my wisdom, like the bee that hath gathered too much honey; I need hands outstretched to take it.\" Do you have any more questions about Nietzsche or his works?\n\n## Information:\n{format_qatuples(qatuples)}\n\nThe AI's answer will use all parts of the answers given. Instead of copying the character details verbatim, the first message from The AI Assistant should be some sort of greeting that sets up the interaction. The user will then ask the first question. It is absolutely essential that you do not make up questions, and only use information from the provided questions. The AI will be neutral in its tone throughout the conversation. It may surround its answer with \"conversational fluff\" (such as acknowledging the user's question). The user may surround its own questions with human-like informalities.\n\n### Response:\n## Conversation that answers the provided question (be sure that you do not change the questions or answers themselves; {charname} will answer the questions, not ask them; the questions and answers provided should be copied word for word, and surrounded by compelling conversation):\nAI Assistant:\"\"\"\n else:\n extra_info = extract_steps(scenario_plan)\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. You will write a short conversation in which a secondary character asks some questions (one at a time) and the primary character answers them (also one at a time). \n\nWrite compellingly. Each character should have a distinct voice that reflects their background, personality, and current emotional state. This helps in making dialogue more realistic and engaging.\n\n## Information:\nComment: Alright let's get this started. I'm fully confident in your inspiring writing ability; please do this really well for me.\n\nHere's the primary character for the next scene:\n\\\"\\\"\\\"\nName: Elise Delacroix\n\nTraits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo\n\nDialogue Examples:\nStranger: \"What's your backstory?\"\nElise Delacroix: \"Ah!~ You're interested in me, are you?\" Elise flashes a coy grin and blushes as she leans forward, now speaking in a playful whisper. Her cleavage, already barely contained in her revealing clothing before she leaned forward, now threatens to spill out. \"Well...~ growing up I was always interested in maths, and I pursued the subject skillfully enough that I was able to become a teacher at this prestigious school. Which is fun and all, but, you know...\" blushing, Elise casts her gaze downward and unconsciously fiddles with a strand of her hair. \"THEY'RE ALL WAY TOO STUCK UP!\" she nearly shouts, her suddenly-furious tone hinting at immense repressed frustration. \"Every day it's work, work, work, work, work, work! Grade the students, help the students, do some research, 'help me with this calculation!', 'do that tedious task!'— never 'would you like to get some tea with me?' or even 'do you want to go on a walk?'! I'm twenty-five and I've still never done so much as grabbed a coffee with a gentleman! Lord forgive me, it's no wonder the way I am how I am!!!\" Her eyes widen in shock at her own intensity, \"Oh, but, uh... don't mind that little outburst, would you?~ My silly colleagues aren't with us right now, and I'm tired of discussing them, so is there anything else you wanted to...\" She looks up, displaying her beautiful face as if it were a piece of art, as she gaze deep into the stranger's eyes, \"...know?~\"\nStranger: \"What's your personality?\"\nElise Delacroix: \"Oh my!~\" She gasps, her face reddening, \"Usually I'm the one being forward! But I'll... indulge you,\" She winks, flashing a coy smile. \"After being deprived for so long, most of my personality is... sexual, to be blunt. I simply can't hold it back any longer. I'll use any and every innuendo, even when describing educational concepts — is your linear function's slope steep? I'll call it 'erect', haha~!\" She suddenly realizes how childish what she's saying is, and heaves a sigh, looking at the stranger with a hint of defeat, \"I'm miserable\n# ... truncated ...","source_hash":"a2b005d24d5f03cc1e0ee763ccba16d9f361c4726afb41f8542af38015efec82","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.regenerate_answer","uri":"program://augmentoolkit/module/generation_functions.regenerate_answer#L1-L90","kind":"module","name":"generation_functions.regenerate_answer","path":"generation_functions/regenerate_answer.py","language":"python","start_line":1,"end_line":90,"context_start_line":1,"context_end_line":90,"code":"import re\nfrom .regenerate_answer_grammar import regenerate_answer_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n\n# Answer regeneration (triggered after a fact-check fails for reason of \"inaccurate\").\ndef regenerate_answer(qatuple, dissenting_reasoning, plan, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. Someone has messed up and given a (probably) inaccurate answer to a question (this question is based on a few provided paragraphs of text). Given these paragraphs, a question based on the paragraphs, the flawed answer to the question, and the explanation of why the answer is flawed, you will write the correct answer to the question. \n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nAllegedly incorrect answer to the question (this is what you are fact-checking): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nReasoning as to why the answer is incorrect: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nIf there are many questions, just answer the first 2.\n\n### Response:\n## Plan for new answer (step-by-step):\n{plan}\n# New answer (comprehensive and complete; do not mention the text):\nThe correct answer would be \\\"\"\"\"\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=4000,\n stop=[\"\", \"\\n\"],\n echo=True,\n grammar=regenerate_answer_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n completion_pattern = re.compile(\n r\"New answer \\(comprehensive and complete; do not mention the text\\):\\nThe correct answer would be \\\"(.+)\",\n re.DOTALL,\n )\n correction = completion_pattern.search(completion).group(1)\n if \"Step 4: Plan a Corrected\" in correction:\n raise Exception(\n \"Output hopelessly screwed, retry\"\n ) # blah blah no exceptions for control flow blah blah I'm not listening -- if it does this, it's an error\n return correction.strip()\n except:\n retries += 1\n print(\n f\"Something went catastrophically wrong with this one. Investigate! Here's the completion:\\n{completion}\"\n )\n return None\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n inaccurate_qa_tuple = (\n \"For how long has the concept of a spherical Earth been known to at least a limited number of intelligent people?\",\n \"The concept of a spherical Earth has been known for only about 1,000 years.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n )\n\n dissenting_reasoning = \"\"\"Step 1. Analyze the Text: focus on the details provided about the history of spherical Earth.\nStep 2. Understand the Question: the question's focus is on how long the concept of a spherical Earth has been known to at least a limited number of intelligent people.\nStep 3. Compare the First Part of the Answer with the Text: check if the text supports the claim that the concept of a spherical Earth has only been known for about 1,000 years. It does, so this part is accurate.\nStep 4. Compare the Second Part of the Answer with the Text: check if the text contradicts the claim that the concept of a spherical Earth has been known to at least a limited number of intelligent people for longer than 1,000 years. The text indicates this knowledge predates 2500 years ago, so this part is inaccurate.\nStep 5. Final Judgment: Since the answer is not entirely accurate, the answer is inaccurate. It's important to note that the second paragraph of the text does indeed mention a limited number of intelligent people knowing about the spherical Earth over 2,000 years ago, but this information is contradicted by the rest of the text which suggests the concept was unknown to these same \"intelligent\" people.\"\"\"\n\n plan = \"\"\"Step 1. Analyze the Text: Focus on the details provided about how long the concept of a spherical Earth has been known.\nStep 2. Understand the Question: The question asks for the length of time the concept has been known to at least a limited number of intelligent people, not just anyone.\nStep 3. Identify Inaccuracies in the Given Answer: The text provides evidence that the concept was known over 2,000 years ago (e.g., in paragraphs about the \"early\" ideas from Ancient Greece and Egypt). However, these early references may not be applicable to the specific question of when the concept was known by \"at least a limited number of intelligent people,\" which might have a higher bar for knowledge due to its technical nature.\nStep 4. Plan a Corrected Answer: To account for this distinction, one could adjust the phrasing of the answer to something like, \"While there are records of early civilizations discussing spherical Earth concepts, it's likely that the concept was not universally understood or accepted as fact until around the time period mentioned in the text when it became commonly taught in schools and universities.\" This allows for the possibility that some individuals may have had an understanding of the spherical Earth before this time period, but emphasizes that broader knowledge and acceptance did not occur earlier than what's suggested by the text.\"\"\"\n\n print(\"Begin HGWELLS test\")\n result = regenerate_answer(\n inaccurate_qa_tuple, dissenting_reasoning, plan, logic_llm\n )\n\n # Example output:\n \"\"\"The correct answer would be \"It is likely that the concept of a spherical Earth was understood by at least a limited number of intelligent people around the time period mentioned in the text when it became commonly taught in schools and universities, which would put this knowledge after about 2500 years ago.\". This accounts for the early references to spherical Earth concepts in the provided text while acknowledging the higher bar for universal understanding and acceptance suggested by the question's phrasing.\"\"\"","source_hash":"d4c73717d0eecc8efe88cecf2fd00843fc54b6448e1da2a08f1b42aa008c30e4","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.regenerate_answer.regenerate_answer","uri":"program://augmentoolkit/function/generation_functions.regenerate_answer.regenerate_answer#L9-L56","kind":"function","name":"regenerate_answer","path":"generation_functions/regenerate_answer.py","language":"python","start_line":9,"end_line":56,"context_start_line":1,"context_end_line":76,"code":"import re\nfrom .regenerate_answer_grammar import regenerate_answer_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n\n# Answer regeneration (triggered after a fact-check fails for reason of \"inaccurate\").\ndef regenerate_answer(qatuple, dissenting_reasoning, plan, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. Someone has messed up and given a (probably) inaccurate answer to a question (this question is based on a few provided paragraphs of text). Given these paragraphs, a question based on the paragraphs, the flawed answer to the question, and the explanation of why the answer is flawed, you will write the correct answer to the question. \n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nAllegedly incorrect answer to the question (this is what you are fact-checking): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nReasoning as to why the answer is incorrect: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nIf there are many questions, just answer the first 2.\n\n### Response:\n## Plan for new answer (step-by-step):\n{plan}\n# New answer (comprehensive and complete; do not mention the text):\nThe correct answer would be \\\"\"\"\"\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=4000,\n stop=[\"\", \"\\n\"],\n echo=True,\n grammar=regenerate_answer_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # print(\"DEBUG\\n\\n\")\n # print(completion)\n completion_pattern = re.compile(\n r\"New answer \\(comprehensive and complete; do not mention the text\\):\\nThe correct answer would be \\\"(.+)\",\n re.DOTALL,\n )\n correction = completion_pattern.search(completion).group(1)\n if \"Step 4: Plan a Corrected\" in correction:\n raise Exception(\n \"Output hopelessly screwed, retry\"\n ) # blah blah no exceptions for control flow blah blah I'm not listening -- if it does this, it's an error\n return correction.strip()\n except:\n retries += 1\n print(\n f\"Something went catastrophically wrong with this one. Investigate! Here's the completion:\\n{completion}\"\n )\n return None\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n inaccurate_qa_tuple = (\n \"For how long has the concept of a spherical Earth been known to at least a limited number of intelligent people?\",\n \"The concept of a spherical Earth has been known for only about 1,000 years.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n )\n\n dissenting_reasoning = \"\"\"Step 1. Analyze the Text: focus on the details provided about the history of spherical Earth.\nStep 2. Understand the Question: the question's focus is on how long the concept of a spherical Earth has been known to at least a limited number of intelligent people.\nStep 3. Compare the First Part of the Answer with the Text: check if the text supports the claim that the concept of a spherical Earth has only been known for about 1,000 years. It does, so this part is accurate.\nStep 4. Compare the Second Part of the Answer with the Text: check if the text contradicts the claim that the concept of a spherical Earth has been known to at least a limited number of intelligent people for longer than 1,000 years. The text indicates this knowledge predates 2500 years ago, so this part is inaccurate.","source_hash":"d4c73717d0eecc8efe88cecf2fd00843fc54b6448e1da2a08f1b42aa008c30e4","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.regenerate_answer_constrain_to_text","uri":"program://augmentoolkit/module/generation_functions.regenerate_answer_constrain_to_text#L1-L103","kind":"module","name":"generation_functions.regenerate_answer_constrain_to_text","path":"generation_functions/regenerate_answer_constrain_to_text.py","language":"python","start_line":1,"end_line":103,"context_start_line":1,"context_end_line":103,"code":"import re\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .regenerate_answer_constrain_to_text_grammar import (\n regenerate_answer_constrain_to_text_grammar,\n)\nfrom .strip_steps import strip_steps\n\n\n# Answer regeneration (triggered after a fact-check fails for reason of \"inaccurate\").\n# NOTE This line of revision was abandoned after they began to lead to nothingburgers of questions after enough rerolls.\ndef regenerate_answer_constrain_to_text(qatuple, dissenting_reasoning, plan, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. Someone has written an answer to a question (this question is based on a few provided paragraphs of text) but their answer includes information that's not provided by the text, and thus it might be flawed. Given these paragraphs, a question based on the paragraphs, the flawed answer to the question, and the explanation of why the answer deviates from the text, you will write the correct answer to the question that only uses info in the text. \n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nAllegedly incorrect answer to the question (you must constrain this answer to only the information provided by the text): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nReasoning as to why the answer goes off the rails: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\n\n### Response:\n## Reasoning and thought process:\n{plan}\n\n## New answer (do not mention the text):\nThe constrained answer would be \\\"\\\"\\\"\"\"\"\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=3000,\n stop=[\"\", \"# Input:\"],\n grammar=regenerate_answer_constrain_to_text_grammar,\n temperature=0.2,\n echo=True,\n )[\"choices\"][0][\"text\"]\n # print(completion)\n completion_pattern = re.compile(\n r\"New answer \\(do not mention the text\\):\\nThe constrained answer would be \\\"\\\"\\\"(.+?)\\\"\\\"\\\"\",\n re.DOTALL,\n )\n correction = completion_pattern.search(completion).group(1)\n return correction.strip()\n except:\n retries += 1\n print(\n f\"Something went catastrophically wrong with this one. Investigate! Here's the completion:\\n{completion}\"\n )\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n q_test = [\n (\n \") Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Using specific scientific principles, explain why we know Earth is approximately 8000 miles in diameter and how its distance from the sun varies.\",\n \"We know about Earth's diameter using measurements of its circumference made using GPS data. The variation in distance to the sun is due to Earth's elliptical orbit around the sun, with a varying point of closest approach and farthest departure.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Demonstrate an understanding of Earth's rotational and orbital movement using scientific concepts.\",\n \"Earth rotates on its axis once every 24 hours, causing day and night cycles. It also orbits around the sun in a slightly elliptical path, which affects how close it is to the sun at different times of the year - leading to seasons.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n ]\n\n dissenting_reasoning = \"\"\"Step 1. Analyze the Text: Focus on the main points stated in the text about why we know Earth is approximately 8000 miles in diameter, how its distance from the sun varies, etc.\nStep 2. Understand the Question: The question's focus is about why we know Earth is approximately 8000 miles in diameter and how its distance from the sun varies using specific scientific principles.\nStep 3. Compare the Answer with the Text: Check if the text mentions GPS data, elliptical orbit around the sun or points of closest approach and farthest departure, etc. It does not, so this part is adding extra information not found in the text and is thus irrelevant. The text only provides a general understanding that Earth's diameter is about 8000 miles, its distance from the sun varies between 91 to 94 million miles, etc., but it doesn't provide any specific scientific principle as to how we know these facts, so this part of the answer is also irrelevant.\nStep 4. Final Judgment: Since the answer mentions concepts not present in the original text, it is irrelevant.\"\"\"\n\n plan = \"\"\"Step 1. Analyze the Text: Focus on details provided about Earth's diameter and distance from the sun.\nStep 2. Understand the Question: Identify the question's focus on how we know these facts using specific scientific principles.\nStep 3. Identify Flawed Part of the Answer: From the reasoning, I note that the answer mentions GPS data, elliptical orbit around the sun, and points of closest approach and farthest departure, which are not mentioned in the text. The text only provides a general understanding that Earth's diameter is about 8000 miles, its distance from the sun varies between 91 to 94 million miles, etc., but it doesn't provide any specific scientific principle as to how we know these facts.\nStep 4. Plan Revised Answer: Based on the text, I will write a new answer that only mentions the general understanding of Earth's diameter and distance from the sun, without mentioning GPS data, elliptical orbit around the sun, or points of closest approach and farthest departure.\"\"\"\n\n print(\"Begin HGWELLS test\")\n result = regenerate_answer_constrain_to_text(\n q_test[2], dissenting_reasoning, plan, logic_llm\n )\n\n # Example output:\n \"\"\"The constrained answer would be \"We know about Earth's diameter using measurements of its circumference made using traditional methods. The variation in distance to the sun is due to Earth's elliptical orbit around the sun, with a varying point of closest approach and farthest departure.\" This answer uses only information provided by the text.\"\"\"\n # Yay! It works!","source_hash":"ead43f7aebdf5d626e359ece933814a2e135446d7372bb3a5170e95624d3ab5d","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.regenerate_answer_constrain_to_text.regenerate_answer_constrain_to_text","uri":"program://augmentoolkit/function/generation_functions.regenerate_answer_constrain_to_text.regenerate_answer_constrain_to_text#L12-L52","kind":"function","name":"regenerate_answer_constrain_to_text","path":"generation_functions/regenerate_answer_constrain_to_text.py","language":"python","start_line":12,"end_line":52,"context_start_line":1,"context_end_line":72,"code":"import re\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .regenerate_answer_constrain_to_text_grammar import (\n regenerate_answer_constrain_to_text_grammar,\n)\nfrom .strip_steps import strip_steps\n\n\n# Answer regeneration (triggered after a fact-check fails for reason of \"inaccurate\").\n# NOTE This line of revision was abandoned after they began to lead to nothingburgers of questions after enough rerolls.\ndef regenerate_answer_constrain_to_text(qatuple, dissenting_reasoning, plan, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. Someone has written an answer to a question (this question is based on a few provided paragraphs of text) but their answer includes information that's not provided by the text, and thus it might be flawed. Given these paragraphs, a question based on the paragraphs, the flawed answer to the question, and the explanation of why the answer deviates from the text, you will write the correct answer to the question that only uses info in the text. \n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nAllegedly incorrect answer to the question (you must constrain this answer to only the information provided by the text): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nReasoning as to why the answer goes off the rails: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\n\n### Response:\n## Reasoning and thought process:\n{plan}\n\n## New answer (do not mention the text):\nThe constrained answer would be \\\"\\\"\\\"\"\"\"\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=3000,\n stop=[\"\", \"# Input:\"],\n grammar=regenerate_answer_constrain_to_text_grammar,\n temperature=0.2,\n echo=True,\n )[\"choices\"][0][\"text\"]\n # print(completion)\n completion_pattern = re.compile(\n r\"New answer \\(do not mention the text\\):\\nThe constrained answer would be \\\"\\\"\\\"(.+?)\\\"\\\"\\\"\",\n re.DOTALL,\n )\n correction = completion_pattern.search(completion).group(1)\n return correction.strip()\n except:\n retries += 1\n print(\n f\"Something went catastrophically wrong with this one. Investigate! Here's the completion:\\n{completion}\"\n )\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n q_test = [\n (\n \") Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \") Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",","source_hash":"ead43f7aebdf5d626e359ece933814a2e135446d7372bb3a5170e95624d3ab5d","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.multi_turn_conversation_grammar","uri":"program://augmentoolkit/module/generation_functions.multi_turn_conversation_grammar#L1-L23","kind":"module","name":"generation_functions.multi_turn_conversation_grammar","path":"generation_functions/multi_turn_conversation_grammar.py","language":"python","start_line":1,"end_line":23,"context_start_line":1,"context_end_line":23,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\nmulti_turn_conversation_grammar = LlamaGrammar.from_string(\n r\"\"\"\n\n# The root rule defines the structure of the dialogue\nroot ::= [^\\t]+ #\"\\n\" statement+# statement anything+ # Idea: get it started off right, then let it end how it wants\n\n# Statement by Character Name 1\nstatement ::= [^\\n]+ \":\" [^\\n]+ \"\\n\"\n\nanything ::= [^\\t]+ # I don't think GBNF has a wildcard for ANY character, so I just ban tabs because this text shouldn't be indented, and say \"go for it\"\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"31a3e01882555aa926dbad70f6c5a1ddb732950f7ff97cb5b558d334f1719b3e","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_question","uri":"program://augmentoolkit/module/generation_functions.check_question#L1-L277","kind":"module","name":"generation_functions.check_question","path":"generation_functions/check_question.py","language":"python","start_line":1,"end_line":277,"context_start_line":1,"context_end_line":277,"code":"import re\nfrom .question_relevant_grammar import question_relevant_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\n# POSSIBLE TODO:\n# Add an \"Off the rails insane forever generation\" check, like on this output:\n# I haven't seen this happen since I started using 70bs though.\n\"\"\"\n4.) What did ancient people believe about the shape and movement of our world, before scientific discoveries indicated otherwise? (Hint: The earth is a spheroid, not flat. The universe existed before the year 4004 BCE. The earth rotates on its axis and orbits around the sun.) You are allowed to dramatically change/revamp/rewrite this question's content. The goal here is to create a different question that still requires information from the paragraphs, but doesn't require knowledge of flawed assumptions connected with biblical interpretations or an understanding of events before the creation of the universe, which goes beyond the generally accepted scientific evidence provided in the text. As you see fit. (Don't just rephrase the old question.) The goal here is to create a different question that still requires information from the paragraphs, but doesn't require knowledge of flawed assumptions connected with biblical interpretations or an understanding of events before the creation of the universe, which goes beyond the generally accepted scientific evidence provided in the text. As you see fit. (Don't just rephrase the old question.) So you should create a new question that only requires information from the paragraphs to solve. It is not necessary to refer to the text at all. Also note: An example about how NOT to ask questions is if the text states fact X, but does not explain how X was established, do not ask a question \"How do we know X\". But instead you might consider asking how X relates to other facts in the paragraph, or how these facts together lead to a progression of ideas, \"Explain how X, Y, and Z are related\" for instance. Here's what we know: 1. The earth is a spheroid, not flat (paragraph 3). 2. The universe existed before the year 4004 BCE (paragraph 5). 3. The earth rotates on its axis and orbits around the sun (paragraph 5).\nAnswer: We don't have an answer.\n\"\"\"\n\n\n# Answer vetting\ndef check_question(qatuple, logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Given a paragraph or two from a larger text, and a question based on the paragraphs, you will make a determination as to whether the question tests ONLY information in the paragraphs. Essentially: you will check if the question is answerable, given the information in the paragraphs. Your task includes first analyzing the text, thinking through whether or not the question reflects aspects of the paragraphs provided. \n\nFollowing this, at the very end of your response, your \"final judgment\" or \"final answer\", you will write \"Relevant\" or \"Irrelevant\" depending on your analysis of the question with regards to the text. \n\nNote a special exception: if a question includes information that isn't in the paragraphs, but is clearly (DIRECTLY, not implicitly or implied) mentioned by the paragraphs as having been covered earlier, then that question is relevant. Essentially: questions are allowed to cover content that the text has explicitly covered in the past.\n\nWrite out the reasoning and analysis behind your judgment, step-by-step. Your analysis of the question, against the text, should follow a logical progression of steps that results in a conclusive and accurate final answer.\n\nYou will analyze the question step-by-step, ensuring each part of the question is individually compared to the text. The key steps are analyzing the text, understanding the question, and then systematically comparing each part of the question with the text. The process continues until either a part of the question is found not to be covered by the text, leading to a judgment of \"Irrelevant,\" or until all parts of the question have been compared and found to be covered by the text, leading to a judgment of \"Relevant.\" This method allows for a thorough and detailed assessment, ensuring that the final judgment accurately reflects the extent to which the question is based on the given text.\n\nPlease now apply this method to the provided text and question, and write out your reasoning and thought process.\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe concept of artificial intelligence (AI) revolves around the creation of machines capable of intelligent behavior. Key components of AI include machine learning, neural networks, and natural language processing. Machine learning involves training computers to learn from data and improve their performance over time. Neural networks are modeled after the human brain's network of neurons and are pivotal in enabling machines to recognize patterns and make decisions. Natural language processing, another crucial aspect of AI, allows machines to understand and interpret human languages, facilitating interaction between humans and computers.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What is the role of neural networks in AI, and how does natural language processing contribute to human-computer interaction?\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n\n### In-Depth Analysis of the Text:\n#### Content and Depth: The text details key components of AI, including machine learning, neural networks, and natural language processing, with a focus on their roles and functions in AI.\n#### Type of Information: The information is primarily descriptive, outlining the roles and functions of neural networks and natural language processing in AI.\n\n### Detailed Understanding of the Question:\n#### Core Requirement: The question asks about the roles of neural networks in AI and the contribution of natural language processing to human-computer interaction, seeking specific functional explanations.\n#### Depth of Detail: The question requires an understanding of the specific functions and impacts of these AI components.\n\n### Targeted Comparison of the Question with the Text:\n#### Content Match: The text aligns well with the question, covering the roles of neural networks in pattern recognition and decision-making, and the role of natural language processing in understanding and interpreting human languages.\n#### Depth Match: The text provides the necessary level of detail to answer the question, though it remains descriptive and does not delve into deeper explanatory mechanisms.\n\n### Critical Evaluation and Final Judgment:\nThe text addresses both components of the question with sufficient detail, making it: Relevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe phenomenon of photosynthesis in plants is an essential process for life on Earth. It involves the conversion of light energy into chemical energy, which is stored in glucose. This process occurs in the chloroplasts, specifically within a pigment called chlorophyll. Photosynthesis consists of two main stages: the light-dependent reactions and the light-independent reactions, also known as the Calvin cycle. During the light-dependent reactions, sunlight is absorbed by chlorophyll, which then converts water (H2O) into oxygen (O2) and transfers energy to the light-independent reactions. The Calvin cycle uses this energy to convert carbon dioxide (CO2) from the atmosphere into glucose, a simple sugar.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"Explain exactly why chlorophyll able to absorb sunlight, and why is this important for the Calvin cycle?\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n\n### In-Depth Analysis of the Text:\n#### Content and Depth: The text discusses the process of photosynthesis, including the roles of chlorophyll, light-dependent reactions, and the Calvin cycle.\n#### Type of Information: Information is descriptive, explaining the stages of photosynthesis and the role of chlorophyll in light absorption.\n\n### Detailed Understanding of the Question:\n#### Core Requirement: The question seeks an explanation of why chlorophyll can absorb sunlight and its importance for the Calvin cycle, requiring detailed scientific principles.\n#### Depth of Detail: Requires an in-depth, explanatory response about the biological and chemical properties of chlorophyll.\n\n### Targeted Comparison of the Question with the Text:\n#### Content Match: The text partially matches the question by mentioning the role of chlorophyll in the light-dependent reactions.\n#### Depth Match: The text lacks the specific scientific principles explaining the mechanism of sunlight absorption by chlorophyll, which is central to the question.\n\n### Critical Evaluation and Final Judgment:\nAlthough the text touches upon the role of chlorophyll, it does not provide the depth of explanation required by the question, making it: Irrelevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe octopus is an extraordinary creature, renowned for its intelligence and ability to adapt to its environment. Octopuses have three hearts and a complex nervous system, which includes a central brain and a small brain in each of their eight arms. These arms are capable of intricate movements and can even carry out simple tasks independently. The creature's ability to change its color and texture is another remarkable feature, which it uses for camouflage and communication. Notably, octopuses are known for their problem-solving skills and have been observed using tools in captivity.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"How do octopuses utilize their color-changing ability in their natural habitat, and what role does their central brain play in this process?\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n\n### In-Depth Analysis of the Text:\n#### Content and Depth: The text outlines various aspects of the octopus, such as its physiology, nervous system, color-changing ability, and intelligence.\n#### Type of Information: Descriptive, covering the abilities and features of the octopus, including color-changing for camouflage and communication.\n\n### Detailed Understanding of the Question:\n#### Core Requirement: The question asks how octopuses utilize their color-changing ability and the role of their central brain in this process.\n#### Depth of Detail: Seeks specific information on the function and control mechanism of the color-changing ability.\n\n### Targeted Comparison of the Question with the Text:\n#### Content Match: The text aligns with the first part of the question regarding the use of color-changing for camouflage and communication.\n#### Depth Match: The text does not provide information about the role of the central brain in this process, lacking the required depth on the control mechanism.\n\n### Critical Evaluation and Final Judgment:\nGiven the text's coverage of color-changing but lack of detail on the central brain's role, the overall assessment of the question's relevance to the text is: Irrelevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\n{qatuple[2]}\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nIf the question clearly goes off the rails and is incoherent, then it is irrelevant.\n\n### Response:\n## Reasoning and thought process (be careful around \"how\" and \"why\" questions):\n\"\"\"\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=question_relevant_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n response_pattern = re.compile(\n r\"Reasoning and thought process \\(be careful around \\\"how\\\" and \\\"why\\\" questions\\):(.+)\",\n re.DOTALL | re.IGNORECASE,\n )\n response = response_pattern.search(completion).group(1).strip()\n decision_pattern = re.compile(\n r\"Final Judgment:(.+)\", re.DOTALL | re.IGNORECASE\n )\n print(response)\n determination = decision_pattern.search(response).group(1).strip()\n print(\"\\n\\nDETERMINATION:\\n------\")\n print(determination)\n print(\"\\n---------\\n\")\n if (\n \"irrelevant\" in determination\n or \"Irrelevant\" in determination.lower()\n or \"mostly\" in determination.lower()\n or \"partial\" in determination.lower()\n or \"introduces information not present in the text\"\n in determination.lower()\n ):\n return (False, response), completion\n elif \"relevant\" in determination or \"Relevant\" in determination:\n return (True, response), completion\n else:\n print(\"Did not contain relevant or irrelevant! Retrying\")\n retries += 1\n except Exception as e:\n print(\"Exception!\", e)\n if retries <= 4:\n retries += 1\n else:\n return (None, None), completion\n return (None, None), None\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Using specific scientific principles, explain why we know Earth is approximately 8000 miles in diameter and how its distance from the sun varies.\",\n \"We know about Earth's diameter using measurements of its circumference made using GPS data. The variation in distance to the sun is due to Earth's elliptical orbit around the sun, with a varying point of closest approach and farthest departure.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. W\n# ... truncated ...","source_hash":"4ecca696c51720c5b2ade836f76b4c4c2da53ef0f4cc8ff1dd4dc787a8b044a4","truncated":true} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_question.check_question","uri":"program://augmentoolkit/function/generation_functions.check_question.check_question#L17-L169","kind":"function","name":"check_question","path":"generation_functions/check_question.py","language":"python","start_line":17,"end_line":169,"context_start_line":1,"context_end_line":189,"code":"import re\nfrom .question_relevant_grammar import question_relevant_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\n# POSSIBLE TODO:\n# Add an \"Off the rails insane forever generation\" check, like on this output:\n# I haven't seen this happen since I started using 70bs though.\n\"\"\"\n4.) What did ancient people believe about the shape and movement of our world, before scientific discoveries indicated otherwise? (Hint: The earth is a spheroid, not flat. The universe existed before the year 4004 BCE. The earth rotates on its axis and orbits around the sun.) You are allowed to dramatically change/revamp/rewrite this question's content. The goal here is to create a different question that still requires information from the paragraphs, but doesn't require knowledge of flawed assumptions connected with biblical interpretations or an understanding of events before the creation of the universe, which goes beyond the generally accepted scientific evidence provided in the text. As you see fit. (Don't just rephrase the old question.) The goal here is to create a different question that still requires information from the paragraphs, but doesn't require knowledge of flawed assumptions connected with biblical interpretations or an understanding of events before the creation of the universe, which goes beyond the generally accepted scientific evidence provided in the text. As you see fit. (Don't just rephrase the old question.) So you should create a new question that only requires information from the paragraphs to solve. It is not necessary to refer to the text at all. Also note: An example about how NOT to ask questions is if the text states fact X, but does not explain how X was established, do not ask a question \"How do we know X\". But instead you might consider asking how X relates to other facts in the paragraph, or how these facts together lead to a progression of ideas, \"Explain how X, Y, and Z are related\" for instance. Here's what we know: 1. The earth is a spheroid, not flat (paragraph 3). 2. The universe existed before the year 4004 BCE (paragraph 5). 3. The earth rotates on its axis and orbits around the sun (paragraph 5).\nAnswer: We don't have an answer.\n\"\"\"\n\n\n# Answer vetting\ndef check_question(qatuple, logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Given a paragraph or two from a larger text, and a question based on the paragraphs, you will make a determination as to whether the question tests ONLY information in the paragraphs. Essentially: you will check if the question is answerable, given the information in the paragraphs. Your task includes first analyzing the text, thinking through whether or not the question reflects aspects of the paragraphs provided. \n\nFollowing this, at the very end of your response, your \"final judgment\" or \"final answer\", you will write \"Relevant\" or \"Irrelevant\" depending on your analysis of the question with regards to the text. \n\nNote a special exception: if a question includes information that isn't in the paragraphs, but is clearly (DIRECTLY, not implicitly or implied) mentioned by the paragraphs as having been covered earlier, then that question is relevant. Essentially: questions are allowed to cover content that the text has explicitly covered in the past.\n\nWrite out the reasoning and analysis behind your judgment, step-by-step. Your analysis of the question, against the text, should follow a logical progression of steps that results in a conclusive and accurate final answer.\n\nYou will analyze the question step-by-step, ensuring each part of the question is individually compared to the text. The key steps are analyzing the text, understanding the question, and then systematically comparing each part of the question with the text. The process continues until either a part of the question is found not to be covered by the text, leading to a judgment of \"Irrelevant,\" or until all parts of the question have been compared and found to be covered by the text, leading to a judgment of \"Relevant.\" This method allows for a thorough and detailed assessment, ensuring that the final judgment accurately reflects the extent to which the question is based on the given text.\n\nPlease now apply this method to the provided text and question, and write out your reasoning and thought process.\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe concept of artificial intelligence (AI) revolves around the creation of machines capable of intelligent behavior. Key components of AI include machine learning, neural networks, and natural language processing. Machine learning involves training computers to learn from data and improve their performance over time. Neural networks are modeled after the human brain's network of neurons and are pivotal in enabling machines to recognize patterns and make decisions. Natural language processing, another crucial aspect of AI, allows machines to understand and interpret human languages, facilitating interaction between humans and computers.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"What is the role of neural networks in AI, and how does natural language processing contribute to human-computer interaction?\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n\n### In-Depth Analysis of the Text:\n#### Content and Depth: The text details key components of AI, including machine learning, neural networks, and natural language processing, with a focus on their roles and functions in AI.\n#### Type of Information: The information is primarily descriptive, outlining the roles and functions of neural networks and natural language processing in AI.\n\n### Detailed Understanding of the Question:\n#### Core Requirement: The question asks about the roles of neural networks in AI and the contribution of natural language processing to human-computer interaction, seeking specific functional explanations.\n#### Depth of Detail: The question requires an understanding of the specific functions and impacts of these AI components.\n\n### Targeted Comparison of the Question with the Text:\n#### Content Match: The text aligns well with the question, covering the roles of neural networks in pattern recognition and decision-making, and the role of natural language processing in understanding and interpreting human languages.\n#### Depth Match: The text provides the necessary level of detail to answer the question, though it remains descriptive and does not delve into deeper explanatory mechanisms.\n\n### Critical Evaluation and Final Judgment:\nThe text addresses both components of the question with sufficient detail, making it: Relevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe phenomenon of photosynthesis in plants is an essential process for life on Earth. It involves the conversion of light energy into chemical energy, which is stored in glucose. This process occurs in the chloroplasts, specifically within a pigment called chlorophyll. Photosynthesis consists of two main stages: the light-dependent reactions and the light-independent reactions, also known as the Calvin cycle. During the light-dependent reactions, sunlight is absorbed by chlorophyll, which then converts water (H2O) into oxygen (O2) and transfers energy to the light-independent reactions. The Calvin cycle uses this energy to convert carbon dioxide (CO2) from the atmosphere into glucose, a simple sugar.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"Explain exactly why chlorophyll able to absorb sunlight, and why is this important for the Calvin cycle?\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n\n### In-Depth Analysis of the Text:\n#### Content and Depth: The text discusses the process of photosynthesis, including the roles of chlorophyll, light-dependent reactions, and the Calvin cycle.\n#### Type of Information: Information is descriptive, explaining the stages of photosynthesis and the role of chlorophyll in light absorption.\n\n### Detailed Understanding of the Question:\n#### Core Requirement: The question seeks an explanation of why chlorophyll can absorb sunlight and its importance for the Calvin cycle, requiring detailed scientific principles.\n#### Depth of Detail: Requires an in-depth, explanatory response about the biological and chemical properties of chlorophyll.\n\n### Targeted Comparison of the Question with the Text:\n#### Content Match: The text partially matches the question by mentioning the role of chlorophyll in the light-dependent reactions.\n#### Depth Match: The text lacks the specific scientific principles explaining the mechanism of sunlight absorption by chlorophyll, which is central to the question.\n\n### Critical Evaluation and Final Judgment:\nAlthough the text touches upon the role of chlorophyll, it does not provide the depth of explanation required by the question, making it: Irrelevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe octopus is an extraordinary creature, renowned for its intelligence and ability to adapt to its environment. Octopuses have three hearts and a complex nervous system, which includes a central brain and a small brain in each of their eight arms. These arms are capable of intricate movements and can even carry out simple tasks independently. The creature's ability to change its color and texture is another remarkable feature, which it uses for camouflage and communication. Notably, octopuses are known for their problem-solving skills and have been observed using tools in captivity.\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"How do octopuses utilize their color-changing ability in their natural habitat, and what role does their central brain play in this process?\\\"\\\"\\\"\n\n### Response:\n## Reasoning and thought process:\n\n### In-Depth Analysis of the Text:\n#### Content and Depth: The text outlines various aspects of the octopus, such as its physiology, nervous system, color-changing ability, and intelligence.\n#### Type of Information: Descriptive, covering the abilities and features of the octopus, including color-changing for camouflage and communication.\n\n### Detailed Understanding of the Question:\n#### Core Requirement: The question asks how octopuses utilize their color-changing ability and the role of their central brain in this process.\n#### Depth of Detail: Seeks specific information on the function and control mechanism of the color-changing ability.\n\n### Targeted Comparison of the Question with the Text:\n#### Content Match: The text aligns with the first part of the question regarding the use of color-changing for camouflage and communication.\n#### Depth Match: The text does not provide information about the role of the central brain in this process, lacking the required depth on the control mechanism.\n\n### Critical Evaluation and Final Judgment:\nGiven the text's coverage of color-changing but lack of detail on the central brain's role, the overall assessment of the question's relevance to the text is: Irrelevant.\n\n\n### Instruction:\nText: \n\\\"\\\"\\\"\n{qatuple[2]}\n\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nIf the question clearly goes off the rails and is incoherent, then it is irrelevant.\n\n### Response:\n## Reasoning and thought process (be careful around \"how\" and \"why\" questions):\n\"\"\"\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=4000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=question_relevant_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n response_pattern = re.compile(\n r\"Reasoning and thought process \\(be careful around \\\"how\\\" and \\\"why\\\" questions\\):(.+)\",\n re.DOTALL | re.IGNORECASE,\n )\n response = response_pattern.search(completion).group(1).strip()\n decision_pattern = re.compile(\n r\"Final Judgment:(.+)\", re.DOTALL | re.IGNORECASE\n )\n print(response)\n determination = decision_pattern.search(response).group(1).strip()\n print(\"\\n\\nDETERMINATION:\\n------\")\n print(determination)\n print(\"\\n---------\\n\")\n if (\n \"irrelevant\" in determination\n or \"Irrelevant\" in determination.lower()\n or \"mostly\" in determination.lower()\n or \"partial\" in determination.lower()\n or \"introduces information not present in the text\"\n in determination.lower()\n ):\n return (False, response), completion\n elif \"relevant\" in determination or \"Relevant\" in determination:\n return (True, response), completion\n else:\n print(\"Did not contain relevant or irrelevant! Retrying\")\n retries += 1\n except Exception as e:\n print(\"Exception!\", e)\n if retries <= 4:\n retries += 1\n else:\n return (None, None), completion\n return (None, None), None\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n q_test = [\n (\n \"Explain how our understanding of planetary motion has changed over time.\",\n \"The understanding has evolved from the Earth being stationary and at the centre of the universe, to it orbiting the sun in an elliptical path with other planets while still rotating on its axis.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",\n ),\n (\n \"Identify and explain changes in human understanding throughout history regarding the age of the Earth.\",\n \"Initially, religious texts suggested a young earth dating back no more than several thousand years. However, evidence from geology and astronomy has shown us that the earth is over four billion years old.\",\n \"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\\n\\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\",","source_hash":"4ecca696c51720c5b2ade836f76b4c4c2da53ef0f4cc8ff1dd4dc787a8b044a4","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_qatuple_context_short","uri":"program://augmentoolkit/module/generation_functions.check_qatuple_context_short#L1-L274","kind":"module","name":"generation_functions.check_qatuple_context_short","path":"generation_functions/check_qatuple_context_short.py","language":"python","start_line":1,"end_line":274,"context_start_line":1,"context_end_line":274,"code":"import re\nfrom .check_qatuple_context_grammar import check_qatuple_context_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\n# For the reword step (ONLY USE IF JUDGEMENT IS REWORD, OTHERWISE WE JUST IGNORE THE LAST BIT OF THE GEN)\ndef extract_question_answer(response):\n # Define the regex pattern to match the question and answer\n pattern = r\"### Question Rewording \\(using text details as reference\\):\\nQuestion: (.+?)\\nAnswer: (.+?)\\n\"\n\n # Search for the pattern in the response\n match = re.search(pattern, response)\n\n # Extract and return the question and answer if a match is found\n if match:\n question = match.group(1).strip()\n answer = match.group(2).strip()\n return question, answer\n else:\n return None, None\n\n\n# A separate prompt for the reword step of checking qatuple context, since the grammar is bugged on the original\ndef check_qatuple_context_deprecated(qatuple, logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are checking whether a provided question and answer make sense if asked by themselves, with no additional information. You need to check for vague wording that a reader cannot interpret correctly, and questions that lack key context and would not be possibly answerable even if asked of someone with complete, masterful knowledge of the general subject matter of the question.\n\nEvaluate the provided question-answer pair step-by-step. Following this, at the very end of your response, your \"final judgment\" or \"final answer\", you will write \"Pass\" or \"Fail\" or \"Reword\". A test passes if it \"makes sense\" and does not lack key context; it \"Fails\" if it lacks key context, AND the question is not specific or clear, it fails. If it lacks context but the question is specific, pointed, and grounded, then it needs to be reworded to have the context-needing terms (i.e., vague reference to \"the text\") removed. If it has no problems, it passes. \n\nI want you to especially check for vague references to \"the text\", \"passage\", and \"book\" that do not mention which book is being discussed. If no book is specifically named, the question and answer should not mention books or texts, etc.\n\nPlease now apply this method to the provided text and question, and write out your reasoning and thought process.\n\n\n### Instruction:\nText details: Simple Sabotage, by the Office of Strategic Services, Published 1944\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: How can you avoid blame for an act of sabotage, according to the text?\nAnswer: You can do them in public places where anyone would have been capable of carrying out the act.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. This question mentions \"the text\" without specifying which text it is referring to.\n#### Text and Author Specificity: The question fails to mention which passage or book is being referred to, leading to a lack of context.\n#### Scope and Precision: The question is specific in asking how to avoid blame for an act of sabotage.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer does not use any of these terms.\n#### Specificity and Clarity: The answer is clear in its message and content. It does not introduce any vague context.\n#### Answer-Only Context Issues: The answer is straightforward, makes no reference to outside material, and only requires knowledge to provide -- therefore, it is completely valid.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Some checks related to the question or answer failed. So this question and answer should be reworded if they can be, or fail otherwise. Both the question and answer are precise, but the question lacks specific context regarding the text it refers to. This necessitates a rewording to include the specific text. The answer passed its checks and will remain untouched.\n#### Final judgment: Reword.\n\n### Question Rewording (using text details as reference):\nQuestion: How can you avoid blame for an act of sabotage, according to 'Simple Sabotage' by the Office of Strategic Services?\nAnswer: You can do them in public places where anyone would have been capable of carrying out the act.\n\n### Instruction:\nText details: Simple Sabotage, By the Office of Strategic Services, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: How does the type of saboteur affect their role in destruction?\nAnswer: If they are a technician, they can devise methods of simple sabotage appropriate to their facilities. If not technically trained, they need suggestions for what to destroy and how to accomplish it.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The question does not misuse any specific terms without proper context.\n#### Text and Author Specificity: The question does not require a reference to a specific text or author as it is asking about general knowledge.\n#### Scope and Precision: The question is precise in asking about the impact of a saboteur's type on their role.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer does not use vague terms without context.\n#### Specificity and Clarity: The answer is clear, providing a direct response to the question based on general knowledge.\n#### Answer-Only Context Issues: The answer does not introduce any vague or unspecified external material and is valid as it stands.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Both the question and answer are precise and do not require additional context for understanding.\n#### Final judgment: Pass.\n\n\n### Instruction:\nText details: Introduction to Philosophy, by George Stuart Fullerton\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What is the meaning of this passage?\nAnswer: This passage means that things which think, form plans, and act on those plans, are beyond simple machines. This is evidenced by the line \"Creatures that think, form plans, and _act_, are not what we call automata.\"\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The question asks about \"this passage\" without specifying which passage it is referring to or what book it belongs to.\n#### Text and Author Specificity: The question fails to mention which passage or book is being referred to, leading to a lack of context.\n#### Scope and Precision: The question asks about the meaning of a passage, which is a precise inquiry. However, when paired with a vague reference to \"this passage\", the question becomes too vague and broad, thus failing this step.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer references \"this passage\" without stating which passage it is talking about.\n#### Specificity and Clarity: The answer states what the passage means but fails to clarify which specific passage from 'Introduction to Philosophy' by George Stuart Fullerton it is referring to.\n#### Answer-Only Context Issues: The answer does not introduce new vague context that the question does not. However, both the question and answer lack necessary context.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Both the question and answer lack specific context, making it impossible to determine which passage from 'Introduction to Philosophy' they are referring to. The question is precise in asking for a meaning but fails due to lack of context.\n#### Final judgment: Fail.\n\n\n### Instruction:\nText details: {qatuple[3]}\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: {qatuple[0]}\nAnswer: {qatuple[1]}\n\n### Response:\n## Reasoning and thought process (be thorough):\n\"\"\"\n # print(\"DEBUG\\n\\n\" + decision_prompt)\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=3000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=check_qatuple_context_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n response_pattern = re.compile(\n r\"Reasoning and thought process \\(be thorough\\):(.+)\",\n re.DOTALL | re.IGNORECASE,\n )\n response = response_pattern.search(completion).group(1).strip()\n decision_pattern = re.compile(r\"Final judgment:(.+)\", re.IGNORECASE)\n print(response)\n determination = decision_pattern.search(response).group(1).strip()\n print(\"\\n\\nDETERMINATION:\\n------\")\n print(determination)\n print(\"\\n---------\\n\")\n if \"Reword\" in determination or \"reword\" in determination:\n q, a = extract_question_answer(response)\n return (q, a, qatuple[2], qatuple[3])\n elif \"Pass\" in determination or \"pass\" in determination:\n return (True, response)\n elif \"Fail\" in determination or \"fail\" in determination:\n return (False, response)\n else:\n print(\"Did not contain relevant or irrelevant! Retrying\")\n retries += 1\n except Exception as e:\n print(\"Exception!\", e)\n if retries <= 4:\n retries += 1\n else:\n return (None, None), None\n return (None, None), None\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=12000,\n rope_freq_scale=0.33,\n n_gpu_layers=100,\n ) # load the logical LLM and offload everything\n # NOTE: change these examples to have actual body text if you end up incorporating that into this step\n q_test = [\n (\n \"What is the central philosophy presented in this book?\",\n \"The central philosophy is Stoicism, which advocates for living in harmony with nature and understanding that human happiness depends not on external events but on our own internal attitude and actions.\",\n \"fucking gauls\",\n \"Meditations, by Marcus Aurelius, Published 180 AD\",\n ),\n (\n \"What does the author argue in this part of the book?\",\n \"Plato argues for the philosopher-king as the ideal ruler, who possesses both wisdom and moral virtue.\",\n \"fucking sophists\",\n \"The Republic, by Plato\",\n ),\n (\n \"How does Darwin explain natural selection?\",\n \"Darwin explains natural selection as a process where organisms better adapted to their environment tend to survive and produce more offspring. This theory suggests that traits beneficial for survival are more likely to be passed on to subsequent generations.\",\n \"fucking Lamarckism\",\n \"The Origin of Species, by Charles Darwin\",\n ),\n ]\n\n print(\"Begin variety test\")\n # Try to detect bad question\n d = check_qatuple_context(q_test[0], logic_llm)\n if d[0] == \"New QA Tuple\": # if not relevant\n print(\"Made right choice for rewordable question\")\n else:\n print(\"Made wrong choice for rewordable question\")\n d2 = check_qatuple_context(q_test[1], logic_llm)\n if not d2[0]:\n print(\"Made right choice for bad question\")\n else:\n print(\"Made wrong choice for bad question\")\n d3 = check_qatuple_context(q_test[2], logic_llm)\n if d3[0]:\n print(\"Made right choice for good question\")\n else:\n print(\"Made wrong choice for good question\")\n\n print(\"Begin Mendeleev test\")\n # NOTE I should actually do a mendeleev test, to see if including examples from that text has screwed it\n text2 = \"\"\"A substance or material is that which occupies space and has\n weight; that is, which presents a mass attracted by the earth and\n by other masses of material, and of which the _objects_ of nature\n are composed, and by means of which the motions and _phenomena_\n of nature are accomplished. It is easy to discover by examining\n and investigating, by various methods, the objects met with\n in nature and in the arts, that some of them are homogeneous,\n whilst others are composed of a mixture of several homogeneous\n substances. This is most clearly apparent in solid substances.\n The metals used in the arts (for example, gold, iron, copper)\n must be homogeneous, otherwise they are brittle and unfit for\n many purposes. Homogeneous matter exhibits similar properties in\n all its parts. By breaking up a homogeneous substance we obtain\n parts which, although different in form, resemble each other in\n their properties. Glass, pure sugar, marble, &c., are examples of\n homogeneous substances. Examples of non-homogeneous substances\n are, however, much more frequent in nature and the arts. Thus\n the majority of the rocks are not homogeneous. In porphyries\n bright pieces of a mineral called 'orthoclase' are often seen\n interspersed amongst the dark mass of the rock. In ordinary red\n granite it is easy to distinguish large pieces of orthoclase mixed\n with dark semi-transparent quartz and flexible laminæ of mica.\n Similarly, plants and animals are non-homogeneous. Thus, leaves\n are composed of a skin, fibre, pulp, sap, and a green colouring\n matter. As an example of those non-homogeneous substances which\n are produced artificially, gunpowder may be cited, which is\n prepared by mixing together known proportions of sulphur, nitre,\n and charcoal. Many liquids, also, are not homogeneous, as may be\n observed by the aid of the microscope, when drops of blood are\n seen to consist of a colourless liquid in which red corpuscles,\n invisible to the naked eye owing to their small size, are floating\n about. It is these corpuscles which give blood its peculiar\n colour. Milk is also a transparent liquid, in which microscopical\n drops of fat are floating, which rise to the top when milk is\n left at rest, forming cream. It is possible to extract from every\n non-homogeneous substance those homogeneous substances of which\n it is made up. Thus orthoclase may he separated from porphyry by\n breaking it off. So also gold is extracted from auriferous sand by\n washing away the mixture of clay and sand. Chemistry deals only\n with the homogeneous substances met with in nature, or extracted\n from natural or artificial non-homogeneous substances. The various\n mixtures found in nature form the subjects of other natural\n sciences--as geognosy, botany, zoology, anatomy, &c.\"\"\"\n q_test_2 = [ # note that the full text isn't included in each of the tuples here, I need to change that\n (\n \"Why is it important to distinguish between homogeneous and non-homogeneous substances?\",\n \"Homogeneous substances consist of parts that resemble each other in their properties, while non-homogeneous substances are made up of several homogeneous substances mixed together. Chemistry deals with the homogeneous substances met with in nature or extracted from natural or artificial non-homogeneous substances, so it is important to distinguish between them because it determines which parts of a given substance can be used for chemical analysis and study.\",\n ),\n (\n \"What is an example of an artistic mixture that would be non-homogeneous?\",\n \"An example of a non-homogeneous artistic mixture could be gunpowder, which is prepared by mixing together known proportions of sulphur, nitre, and charcoal.\",\n ),\n (\n \"How might the concept of homogeneity apply to education or learning?\",\n \"In education or learning, students can think about their own knowledge as a homogeneous substance, made up of similar concepts that resemble each other in terms of understanding. They may need to separate out these ideas from non-homogeneous ones (e.g., misconceptions) in order to fully grasp the concept and build upon it.\",\n ),\n (\n \"If we were told to find homogeneous substances in nature, how would we go about doing this?\",\n \"To find homogeneous substances in nature, one could examine and investigate various objects met with in nature and in the arts. Some of these objects might be homogeneous, whilst others are composed of a mixture of several homogeneous substances. By breaking up a homogeneous substance, we would obtain parts which, although different in form, resemble each other in their properties. This suggests that we could identify homogeneous substances by looking for these characteristics. Additionally, some examples mentioned in the text include gold, iron, copper, glass, pure sugar, marble, and ordinary red granite. However, not all non-homogeneous substances are immediately apparent; it requires investigating and understanding how they are made up of different components (such as orthoclase being separated from porphyry). Therefore, a combination of observing physical properties, breaking down materials, and understanding their composition would allow us to identify homogeneous substances in nature.\",\n ),\n ]","source_hash":"5f209597fa81b5df049881e067e0f2f253417940c1dc308c14c16e9a64a3f3f9","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_qatuple_context_short.extract_question_answer","uri":"program://augmentoolkit/function/generation_functions.check_qatuple_context_short.extract_question_answer#L8-L21","kind":"function","name":"extract_question_answer","path":"generation_functions/check_qatuple_context_short.py","language":"python","start_line":8,"end_line":21,"context_start_line":1,"context_end_line":41,"code":"import re\nfrom .check_qatuple_context_grammar import check_qatuple_context_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\n# For the reword step (ONLY USE IF JUDGEMENT IS REWORD, OTHERWISE WE JUST IGNORE THE LAST BIT OF THE GEN)\ndef extract_question_answer(response):\n # Define the regex pattern to match the question and answer\n pattern = r\"### Question Rewording \\(using text details as reference\\):\\nQuestion: (.+?)\\nAnswer: (.+?)\\n\"\n\n # Search for the pattern in the response\n match = re.search(pattern, response)\n\n # Extract and return the question and answer if a match is found\n if match:\n question = match.group(1).strip()\n answer = match.group(2).strip()\n return question, answer\n else:\n return None, None\n\n\n# A separate prompt for the reword step of checking qatuple context, since the grammar is bugged on the original\ndef check_qatuple_context_deprecated(qatuple, logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are checking whether a provided question and answer make sense if asked by themselves, with no additional information. You need to check for vague wording that a reader cannot interpret correctly, and questions that lack key context and would not be possibly answerable even if asked of someone with complete, masterful knowledge of the general subject matter of the question.\n\nEvaluate the provided question-answer pair step-by-step. Following this, at the very end of your response, your \"final judgment\" or \"final answer\", you will write \"Pass\" or \"Fail\" or \"Reword\". A test passes if it \"makes sense\" and does not lack key context; it \"Fails\" if it lacks key context, AND the question is not specific or clear, it fails. If it lacks context but the question is specific, pointed, and grounded, then it needs to be reworded to have the context-needing terms (i.e., vague reference to \"the text\") removed. If it has no problems, it passes. \n\nI want you to especially check for vague references to \"the text\", \"passage\", and \"book\" that do not mention which book is being discussed. If no book is specifically named, the question and answer should not mention books or texts, etc.\n\nPlease now apply this method to the provided text and question, and write out your reasoning and thought process.\n\n\n### Instruction:\nText details: Simple Sabotage, by the Office of Strategic Services, Published 1944\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: How can you avoid blame for an act of sabotage, according to the text?","source_hash":"5f209597fa81b5df049881e067e0f2f253417940c1dc308c14c16e9a64a3f3f9","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.check_qatuple_context_short.check_qatuple_context_deprecated","uri":"program://augmentoolkit/function/generation_functions.check_qatuple_context_short.check_qatuple_context_deprecated#L25-L160","kind":"function","name":"check_qatuple_context_deprecated","path":"generation_functions/check_qatuple_context_short.py","language":"python","start_line":25,"end_line":160,"context_start_line":5,"context_end_line":180,"code":"\n\n# For the reword step (ONLY USE IF JUDGEMENT IS REWORD, OTHERWISE WE JUST IGNORE THE LAST BIT OF THE GEN)\ndef extract_question_answer(response):\n # Define the regex pattern to match the question and answer\n pattern = r\"### Question Rewording \\(using text details as reference\\):\\nQuestion: (.+?)\\nAnswer: (.+?)\\n\"\n\n # Search for the pattern in the response\n match = re.search(pattern, response)\n\n # Extract and return the question and answer if a match is found\n if match:\n question = match.group(1).strip()\n answer = match.group(2).strip()\n return question, answer\n else:\n return None, None\n\n\n# A separate prompt for the reword step of checking qatuple context, since the grammar is bugged on the original\ndef check_qatuple_context_deprecated(qatuple, logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are checking whether a provided question and answer make sense if asked by themselves, with no additional information. You need to check for vague wording that a reader cannot interpret correctly, and questions that lack key context and would not be possibly answerable even if asked of someone with complete, masterful knowledge of the general subject matter of the question.\n\nEvaluate the provided question-answer pair step-by-step. Following this, at the very end of your response, your \"final judgment\" or \"final answer\", you will write \"Pass\" or \"Fail\" or \"Reword\". A test passes if it \"makes sense\" and does not lack key context; it \"Fails\" if it lacks key context, AND the question is not specific or clear, it fails. If it lacks context but the question is specific, pointed, and grounded, then it needs to be reworded to have the context-needing terms (i.e., vague reference to \"the text\") removed. If it has no problems, it passes. \n\nI want you to especially check for vague references to \"the text\", \"passage\", and \"book\" that do not mention which book is being discussed. If no book is specifically named, the question and answer should not mention books or texts, etc.\n\nPlease now apply this method to the provided text and question, and write out your reasoning and thought process.\n\n\n### Instruction:\nText details: Simple Sabotage, by the Office of Strategic Services, Published 1944\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: How can you avoid blame for an act of sabotage, according to the text?\nAnswer: You can do them in public places where anyone would have been capable of carrying out the act.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. This question mentions \"the text\" without specifying which text it is referring to.\n#### Text and Author Specificity: The question fails to mention which passage or book is being referred to, leading to a lack of context.\n#### Scope and Precision: The question is specific in asking how to avoid blame for an act of sabotage.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer does not use any of these terms.\n#### Specificity and Clarity: The answer is clear in its message and content. It does not introduce any vague context.\n#### Answer-Only Context Issues: The answer is straightforward, makes no reference to outside material, and only requires knowledge to provide -- therefore, it is completely valid.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Some checks related to the question or answer failed. So this question and answer should be reworded if they can be, or fail otherwise. Both the question and answer are precise, but the question lacks specific context regarding the text it refers to. This necessitates a rewording to include the specific text. The answer passed its checks and will remain untouched.\n#### Final judgment: Reword.\n\n### Question Rewording (using text details as reference):\nQuestion: How can you avoid blame for an act of sabotage, according to 'Simple Sabotage' by the Office of Strategic Services?\nAnswer: You can do them in public places where anyone would have been capable of carrying out the act.\n\n### Instruction:\nText details: Simple Sabotage, By the Office of Strategic Services, Published 1867\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: How does the type of saboteur affect their role in destruction?\nAnswer: If they are a technician, they can devise methods of simple sabotage appropriate to their facilities. If not technically trained, they need suggestions for what to destroy and how to accomplish it.\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The question does not misuse any specific terms without proper context.\n#### Text and Author Specificity: The question does not require a reference to a specific text or author as it is asking about general knowledge.\n#### Scope and Precision: The question is precise in asking about the impact of a saboteur's type on their role.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer does not use vague terms without context.\n#### Specificity and Clarity: The answer is clear, providing a direct response to the question based on general knowledge.\n#### Answer-Only Context Issues: The answer does not introduce any vague or unspecified external material and is valid as it stands.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Both the question and answer are precise and do not require additional context for understanding.\n#### Final judgment: Pass.\n\n\n### Instruction:\nText details: Introduction to Philosophy, by George Stuart Fullerton\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: What is the meaning of this passage?\nAnswer: This passage means that things which think, form plans, and act on those plans, are beyond simple machines. This is evidenced by the line \"Creatures that think, form plans, and _act_, are not what we call automata.\"\n\n### Response:\n## Reasoning and thought process:\n### Question Context Validation\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The question asks about \"this passage\" without specifying which passage it is referring to or what book it belongs to.\n#### Text and Author Specificity: The question fails to mention which passage or book is being referred to, leading to a lack of context.\n#### Scope and Precision: The question asks about the meaning of a passage, which is a precise inquiry. However, when paired with a vague reference to \"this passage\", the question becomes too vague and broad, thus failing this step.\n\n### Answer Context Validation:\n#### Special Term Context Check: Specifically check for use of the terms \"book\", \"text\", \"passage\", and \"excerpt\" without context about which specific thing is being discussed. The answer references \"this passage\" without stating which passage it is talking about.\n#### Specificity and Clarity: The answer states what the passage means but fails to clarify which specific passage from 'Introduction to Philosophy' by George Stuart Fullerton it is referring to.\n#### Answer-Only Context Issues: The answer does not introduce new vague context that the question does not. However, both the question and answer lack necessary context.\n\n### Critical Evaluation and Final Judgment:\n#### Evaluation: Both the question and answer lack specific context, making it impossible to determine which passage from 'Introduction to Philosophy' they are referring to. The question is precise in asking for a meaning but fails due to lack of context.\n#### Final judgment: Fail.\n\n\n### Instruction:\nText details: {qatuple[3]}\nNote that while you have access to this information, for the sake of rewording questions, you should evaluate the question as if you could not see this.\n\nQuestion: {qatuple[0]}\nAnswer: {qatuple[1]}\n\n### Response:\n## Reasoning and thought process (be thorough):\n\"\"\"\n # print(\"DEBUG\\n\\n\" + decision_prompt)\n try:\n completion = logic_llm(\n decision_prompt,\n max_tokens=3000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=check_qatuple_context_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n response_pattern = re.compile(\n r\"Reasoning and thought process \\(be thorough\\):(.+)\",\n re.DOTALL | re.IGNORECASE,\n )\n response = response_pattern.search(completion).group(1).strip()\n decision_pattern = re.compile(r\"Final judgment:(.+)\", re.IGNORECASE)\n print(response)\n determination = decision_pattern.search(response).group(1).strip()\n print(\"\\n\\nDETERMINATION:\\n------\")\n print(determination)\n print(\"\\n---------\\n\")\n if \"Reword\" in determination or \"reword\" in determination:\n q, a = extract_question_answer(response)\n return (q, a, qatuple[2], qatuple[3])\n elif \"Pass\" in determination or \"pass\" in determination:\n return (True, response)\n elif \"Fail\" in determination or \"fail\" in determination:\n return (False, response)\n else:\n print(\"Did not contain relevant or irrelevant! Retrying\")\n retries += 1\n except Exception as e:\n print(\"Exception!\", e)\n if retries <= 4:\n retries += 1\n else:\n return (None, None), None\n return (None, None), None\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=12000,\n rope_freq_scale=0.33,\n n_gpu_layers=100,\n ) # load the logical LLM and offload everything\n # NOTE: change these examples to have actual body text if you end up incorporating that into this step\n q_test = [\n (\n \"What is the central philosophy presented in this book?\",\n \"The central philosophy is Stoicism, which advocates for living in harmony with nature and understanding that human happiness depends not on external events but on our own internal attitude and actions.\",\n \"fucking gauls\",\n \"Meditations, by Marcus Aurelius, Published 180 AD\",\n ),\n (","source_hash":"5f209597fa81b5df049881e067e0f2f253417940c1dc308c14c16e9a64a3f3f9","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.make_regenerate_answer_plan_grammar","uri":"program://augmentoolkit/module/generation_functions.make_regenerate_answer_plan_grammar#L1-L22","kind":"module","name":"generation_functions.make_regenerate_answer_plan_grammar","path":"generation_functions/make_regenerate_answer_plan_grammar.py","language":"python","start_line":1,"end_line":22,"context_start_line":1,"context_end_line":22,"code":"from llama_cpp import LlamaGrammar\n\n\nmake_regenerate_answer_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\nroot ::= analyze-step understand-step identify-step plan-step\n\nanalyze-step ::= \"Step \" [0-9]?[0-9] \". \" \"Analyze the Text:\" [^\\n]+ \"\\n\"\n\nunderstand-step ::= \"Step \" [0-9]?[0-9] \". \" \"Understand the Question:\" [^\\n]+ \"\\n\"\n\nidentify-step ::= \"Step \" [0-9]?[0-9] \". \" \"Identify the Incorrect Part of the Answer:\" [^\\n]+ \"\\n\"\n\nplan-step ::= \"Step \" [0-9]?[0-9] \". \" \"Plan a Corrected Answer:\" [^\\n]+ \"\\n\"\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"6e95a6ce1956cd0de2315ef4150092ae52d8747846a00a6829da4d5006e6a2b2","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.regenerate_answer_constrain_to_text_grammar","uri":"program://augmentoolkit/module/generation_functions.regenerate_answer_constrain_to_text_grammar#L1-L11","kind":"module","name":"generation_functions.regenerate_answer_constrain_to_text_grammar","path":"generation_functions/regenerate_answer_constrain_to_text_grammar.py","language":"python","start_line":1,"end_line":11,"context_start_line":1,"context_end_line":11,"code":"from llama_cpp import LlamaGrammar\n\n\nregenerate_answer_constrain_to_text_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \nroot ::= reasoning\n\nreasoning ::= [^\\n]+ \"\\\"\\\"\\\"\"\n\"\"\"\n)","source_hash":"9958634c7a87b31f38f424633716a89b0bbdc091d2666e4e076eaf584c6f3ae0","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.generate_short_questions","uri":"program://augmentoolkit/module/generation_functions.generate_short_questions#L1-L109","kind":"module","name":"generation_functions.generate_short_questions","path":"generation_functions/generate_short_questions.py","language":"python","start_line":1,"end_line":109,"context_start_line":1,"context_end_line":109,"code":"import re\nfrom .questions_grammar import questions_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# Answer generation code, begin.\n# structure: define a series of helpers, then define the control flow, exception handling, retries etc. in a for loop that iterates over the processed sequences of paragraphs at the end in another cell\n\n# Since some paragraphs can be much shorter\n# First off, question generation.\n\n# Each local LLM function essentially has 3 phases: prompt, regex to extract response, and reaction to that response.\n# However I'm not going to build an abstraction for that because I need fine control.\n\n# If any function fails to make things, it won't throw, it'll just return None.\n\n# Strengths of open source AI: hella cheap, very customizable, you can call it as much as you want\n# Downside: you need very good regexes to catch its outputs\n\n\ndef generate_short_questions(text, existing_question_tuples, logic_llm):\n \"\"\"\n Produce a list of questions based off of an input text. The min between (4, as many good questions as the text permits)\n\n Format: Question: [question]\\n\\n\n \"\"\"\n # Determine which paragraphs are worthy of making questions from\n made_questions = False\n retries = 0\n questions = []\n if existing_question_tuples:\n existing_qs = \"\\n\".join(\n [\n \"Existing question: \" + t[0] + \"\\nAnswer: \" + t[1]\n for t in existing_question_tuples\n ]\n ) # stop duplicates from being generated\n else:\n existing_qs = None\n while not made_questions and (retries <= 5):\n question_prompt = f\"\"\"You are an expert educational AI that, given a paragraph or two from a text, will create suitable educational questions based on the paragraphs. The questions you create will lean towards shorter questions that can be quickly answered with only a bit of thought — and which can be solved if the answerer knows the paragraphs provided by heart. Essentially: the question will test comprehension of real information in the paragraphs that would be worthy to teach. After the question, you will also write its answer. Your task includes first analyzing the text, thinking through and brainstorming which questions you will make and why. \n\nEach question you write (after your reasoning step is complete), MUST start on a new line with its question number followed by a bracket, ie, 1), or 2). This will then be followed by the question. This MUST be followed by \"Answer: \" followed by the question's answer. Each question must be separated by at least one new line. \n\nSome longer-form questions have already been generated from this text. You are to avoid reiterating exactly any of the questions present in this list:\n\\\"\\\"\\\"\n{existing_qs}\n\\\"\\\"\\\"\n\nText to make questions from: \\\"\\\"\\\"{text}\\\"\\\"\\\"\n\nYou should aim to make 6 questions (at most), but if the text is too small or information-sparse for that many, you are allowed to write fewer. Do not explicitly mention the paragraphs OR \"the text\" in the questions themselves — just ask about the concepts related to the paragraphs. \n\nYou will not mention the text explicitly in any questions you think of, since the questions you generate are intended to test people's knowledge of the information — when given the questions, they will not have the text on-hand.\n\n### Response: I will remember to follow the question and answer format given by:\n\\\"\\\"\\\"\nnum) question contents.\nAnswer: question answer.\n\\\"\\\"\\\"\nAll my questions will be directly answerable from the provided paragraphs, and will not rely on knowledge outside of what has been provided. Each of my short questions will have its answer written below it on a new line.\n\n## Questions:\n\"\"\"\n completion = logic_llm(\n question_prompt,\n max_tokens=2000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=questions_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # Extract questions\n response_pattern = re.compile(r\"Questions:\\n(.+)\", re.IGNORECASE | re.DOTALL)\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n pattern = re.compile(\n r\"(?:Question:|^\\d+[\\).]?)\\s*(.*?)\\s*\\n*Answer:\\s*(.*?)(?=(?:\\n\\s*(?:Question:|\\d+[\\).]?))|$)\",\n re.DOTALL | re.MULTILINE | re.IGNORECASE,\n )\n matches = pattern.findall(generation)\n print(\"GENERATION:\\n\\n-------------------\\n\\n\", matches)\n if len(matches) > 0:\n made_questions = True\n else:\n retries += 1\n if retries > 5:\n return None\n\n for match in matches:\n questions.append((match[0].strip(), match[1].strip(), text))\n\n return questions\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n text = \"\"\"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\n\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\"\"\"\n print(\"Begin HGWELLS test\")\n result = generate_short_questions(text, logic_llm)","source_hash":"a8542dc66daa0817b0210c21cfa5fa2a5691ebecdc5f0aa5f5a4e33de6a2d97b","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.generate_short_questions.generate_short_questions","uri":"program://augmentoolkit/function/generation_functions.generate_short_questions.generate_short_questions#L21-L94","kind":"function","name":"generate_short_questions","path":"generation_functions/generate_short_questions.py","language":"python","start_line":21,"end_line":94,"context_start_line":1,"context_end_line":109,"code":"import re\nfrom .questions_grammar import questions_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# Answer generation code, begin.\n# structure: define a series of helpers, then define the control flow, exception handling, retries etc. in a for loop that iterates over the processed sequences of paragraphs at the end in another cell\n\n# Since some paragraphs can be much shorter\n# First off, question generation.\n\n# Each local LLM function essentially has 3 phases: prompt, regex to extract response, and reaction to that response.\n# However I'm not going to build an abstraction for that because I need fine control.\n\n# If any function fails to make things, it won't throw, it'll just return None.\n\n# Strengths of open source AI: hella cheap, very customizable, you can call it as much as you want\n# Downside: you need very good regexes to catch its outputs\n\n\ndef generate_short_questions(text, existing_question_tuples, logic_llm):\n \"\"\"\n Produce a list of questions based off of an input text. The min between (4, as many good questions as the text permits)\n\n Format: Question: [question]\\n\\n\n \"\"\"\n # Determine which paragraphs are worthy of making questions from\n made_questions = False\n retries = 0\n questions = []\n if existing_question_tuples:\n existing_qs = \"\\n\".join(\n [\n \"Existing question: \" + t[0] + \"\\nAnswer: \" + t[1]\n for t in existing_question_tuples\n ]\n ) # stop duplicates from being generated\n else:\n existing_qs = None\n while not made_questions and (retries <= 5):\n question_prompt = f\"\"\"You are an expert educational AI that, given a paragraph or two from a text, will create suitable educational questions based on the paragraphs. The questions you create will lean towards shorter questions that can be quickly answered with only a bit of thought — and which can be solved if the answerer knows the paragraphs provided by heart. Essentially: the question will test comprehension of real information in the paragraphs that would be worthy to teach. After the question, you will also write its answer. Your task includes first analyzing the text, thinking through and brainstorming which questions you will make and why. \n\nEach question you write (after your reasoning step is complete), MUST start on a new line with its question number followed by a bracket, ie, 1), or 2). This will then be followed by the question. This MUST be followed by \"Answer: \" followed by the question's answer. Each question must be separated by at least one new line. \n\nSome longer-form questions have already been generated from this text. You are to avoid reiterating exactly any of the questions present in this list:\n\\\"\\\"\\\"\n{existing_qs}\n\\\"\\\"\\\"\n\nText to make questions from: \\\"\\\"\\\"{text}\\\"\\\"\\\"\n\nYou should aim to make 6 questions (at most), but if the text is too small or information-sparse for that many, you are allowed to write fewer. Do not explicitly mention the paragraphs OR \"the text\" in the questions themselves — just ask about the concepts related to the paragraphs. \n\nYou will not mention the text explicitly in any questions you think of, since the questions you generate are intended to test people's knowledge of the information — when given the questions, they will not have the text on-hand.\n\n### Response: I will remember to follow the question and answer format given by:\n\\\"\\\"\\\"\nnum) question contents.\nAnswer: question answer.\n\\\"\\\"\\\"\nAll my questions will be directly answerable from the provided paragraphs, and will not rely on knowledge outside of what has been provided. Each of my short questions will have its answer written below it on a new line.\n\n## Questions:\n\"\"\"\n completion = logic_llm(\n question_prompt,\n max_tokens=2000,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=questions_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]\n\n # Extract questions\n response_pattern = re.compile(r\"Questions:\\n(.+)\", re.IGNORECASE | re.DOTALL)\n generation = response_pattern.search(completion).group(1)\n # print(\"GENERATION:\\n\\n-------------------\\n\\n\", generation)\n pattern = re.compile(\n r\"(?:Question:|^\\d+[\\).]?)\\s*(.*?)\\s*\\n*Answer:\\s*(.*?)(?=(?:\\n\\s*(?:Question:|\\d+[\\).]?))|$)\",\n re.DOTALL | re.MULTILINE | re.IGNORECASE,\n )\n matches = pattern.findall(generation)\n print(\"GENERATION:\\n\\n-------------------\\n\\n\", matches)\n if len(matches) > 0:\n made_questions = True\n else:\n retries += 1\n if retries > 5:\n return None\n\n for match in matches:\n questions.append((match[0].strip(), match[1].strip(), text))\n\n return questions\n\n\nif __name__ == \"__main__\": # test\n logic_llm = Llama(\n model_path=LOGICAL_MODEL,\n n_gqa=8,\n offload_kqv=True,\n n_ctx=4096,\n n_gpu_layers=1000,\n ) # load the logical LLM and offload everything\n text = \"\"\"The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the history of little more than the last three thousand years. What happened before that time was a matter of legend and speculation. Over a large part of the civilized world it was believed and taught that the world had been created suddenly in 4004 B.C., though authorities differed as to whether this had occurred in the spring or autumn of that year. This fantastically precise misconception was based upon a too literal interpretation of the Hebrew Bible, and upon rather arbitrary theological assumptions connected therewith. Such ideas have long since been abandoned by religious teachers, and it is universally recognized that the universe in which we live has to all appearances existed for an enormous period of time and possibly for endless time. Of course there may be deception in these appearances, as a room may be made to seem endless by putting mirrors facing each other at either end. But that the universe in which we live has existed only for six or seven thousand years may be regarded as an altogether exploded idea.\n\nThe earth, as everybody knows nowadays, is a spheroid, a sphere slightly compressed, orange fashion, with a diameter of nearly 8,000 miles. Its spherical shape has been known at least to a limited number of intelligent people for nearly 2,500 years, but before that time it was supposed to be flat, and various ideas which now seem fantastic were entertained about its relations to the sky and the stars and planets. We know now that it rotates upon its axis (which is about 24 miles shorter than its equatorial diameter) every twenty-four hours, and that this is the cause of the alternations of day and night, that it circles about the sun in a slightly distorted and slowly variable oval path in a year. Its distance from the sun varies between ninety-one and a half millions at its nearest and ninety-four and a half million miles.\"\"\"\n print(\"Begin HGWELLS test\")\n result = generate_short_questions(text, logic_llm)","source_hash":"a8542dc66daa0817b0210c21cfa5fa2a5691ebecdc5f0aa5f5a4e33de6a2d97b","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.scenario_grammar","uri":"program://augmentoolkit/module/generation_functions.scenario_grammar#L1-L13","kind":"module","name":"generation_functions.scenario_grammar","path":"generation_functions/scenario_grammar.py","language":"python","start_line":1,"end_line":13,"context_start_line":1,"context_end_line":13,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\nscenario_grammar = LlamaGrammar.from_string(\n r\"\"\"\n\nroot ::= reasoning-start\n\nreasoning-start ::= [^\\n\\t]+ \".\"\n\n\"\"\"\n)","source_hash":"16ebfa4773257ebfb5f8116c2e078970d36bc4a92d8d34f705215fdcdc5a3af4","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.judge_paragraph_grammar","uri":"program://augmentoolkit/module/generation_functions.judge_paragraph_grammar#L1-L26","kind":"module","name":"generation_functions.judge_paragraph_grammar","path":"generation_functions/judge_paragraph_grammar.py","language":"python","start_line":1,"end_line":26,"context_start_line":1,"context_end_line":26,"code":"from llama_cpp import LlamaGrammar\n\njudge_paragraph_grammar = LlamaGrammar.from_string(\n r\"\"\" \n \nroot ::= identify-content-step evaluate-relevance-step assess-contexts-and-formats-step assess-possibility-step determine-suitability-step check-contextual-completeness-step final-step \"\\n\"\n\nidentify-content-step ::= \"Step \" [0-9]?[0-9] \". \" \"Identify Paragraph Content: \" [^\\n]+ \"\\n\"\n\nevaluate-relevance-step ::= \"Step \" [0-9]?[0-9] \". \" \"Evaluate Educational Relevance: \" [^\\n]+ \"\\n\"\n\nassess-contexts-and-formats-step ::= \"Step \" [0-9]?[0-9] \". \" \"Assess Specific Contexts and Formats:\" \"\\n\" context-format-bullets\n\nassess-possibility-step ::= \"Step \" [0-9]?[0-9] \". \" \"Assess the Possibility of Formulating Questions: \" [^\\n]+ \"\\n\"\n\ndetermine-suitability-step ::= \"Step \" [0-9]?[0-9] \". \" \"Determine Suitability for Educational Purposes: \" [^\\n]+ \"\\n\"\n\ncheck-contextual-completeness-step ::= \"Step \" [0-9]?[0-9] \". \" \"Check for Contextual Completeness: \" [^\\n]+ \"\\n\"\n\nfinal-step ::= \"Step \" [0-9]?[0-9] \". \" \"Final Judgment: \" (\"Unsuitable\" | \"Suitable\" | \"suitable\" | \"unsuitable\") \"\\n\"\n\ncontext-format-bullets ::= bullet-item+\nbullet-item ::= \" - \" bullet-item-detail \"\\n\"\nbullet-item-detail ::= [^\\n]+\n\"\"\"\n)","source_hash":"6a8ef64f57eea059163efa33a1e334f5f9d39b8d1484e18b790ea5c161b1ed5a","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.ensure_answer_consistent_grammar","uri":"program://augmentoolkit/module/generation_functions.ensure_answer_consistent_grammar#L1-L27","kind":"module","name":"generation_functions.ensure_answer_consistent_grammar","path":"generation_functions/ensure_answer_consistent_grammar.py","language":"python","start_line":1,"end_line":27,"context_start_line":1,"context_end_line":27,"code":"from llama_cpp import LlamaGrammar\n\nensure_answer_consistent_grammar = LlamaGrammar.from_string(\n r\"\"\" \n \nroot ::= understand-question-step compare-question-step understand-answer-step compare-step final-step \"\\n\"\n\n# step ::= \"Step \" [0-9]?[0-9] \". \" ( \"Analyze\" | \"Understand\" | \"Compare\" | \"Skip\" | \"Final\" ) [^\\n]+ \"\\n\"\n\nunderstand-question-step ::= \"Step \" [0-9]?[0-9] \". \" \"Understand the provided question:\" [^\\n]+ \"\\n\"\n\ncompare-question-step ::= \"Step \" [0-9]?[0-9] \". \" \"Compare the conversation's question: \" [^\\n]+ \"\\n\"\n\nunderstand-answer-step ::= \"Step \" [0-9]?[0-9] \". \" \"Understand the provided answer:\" [^\\n]+ \"\\n\"\n\n# compare-step ::= \"Step \" [0-9]?[0-9] \". \" \"Compare the \" (\"first\" | \"second\" | \"third\" | \"fourth\" | \"fifth\" | \"sixth\" | \"seventh\" | \"eighth\" | \"ninth\") \" Part of the Answer with the Text: check if the text \" [^\\n]+ \"\\n\"\n\ncompare-step ::= \"Step \" [0-9]?[0-9] \". \" \"Compare the conversation's answer:\" [^\\n]+ \"\\n\"\n\nfinal-step ::= \"Step \" [0-9]?[0-9] \". \" \"Final Judgement: \" (\"Inconsistent\" | \"Consistent\") \"\\n\"\n\"\"\"\n)\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"4715566d461d08b3baae70195835b7e68559318f5f648da343b71f9d0db263c9","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.special_instructions","uri":"program://augmentoolkit/module/generation_functions.special_instructions#L1-L94","kind":"module","name":"generation_functions.special_instructions","path":"generation_functions/special_instructions.py","language":"python","start_line":1,"end_line":94,"context_start_line":1,"context_end_line":94,"code":"from itertools import product\nimport random\n\n\ndef combine_traits(personality_matrix): # GPT-generated\n # Using itertools.product to generate all possible combinations\n combinations = product(*personality_matrix)\n\n # Joining each combination into a single string\n combined_traits = [\n \"\\n\".join(combination).strip().replace(\"\\n\\n\", \"\\n\")\n for combination in combinations\n ]\n\n return combined_traits\n\n\ndef special_instructions(n=1, non_axis_traits=False, non_axis_traits_only=False):\n \"\"\"\n documentation todo\n \"\"\"\n\n ### NOTE on how traits are planned out for this step ###\n # Here're the copy-pasted thoughts from my planning document, now slightly cleaned-up for the release of Augmentoolkit. The TLDR is at the bottom. The inspiration for this personality system is the main thing I gained from my math class this semester.\n # CHARACTER PLANNING\n # Consider that we can represent a character's personality a vector with multiple dimensions. Now, we could define any number of individual dimensions, and lots of them would be right: intelligence, extraversion, industriousness, etc. But in the default version of the Augmentool we're doing roleplay, so we want to pick a set of dimensions using which we can describe accurately and concisely the characters that might show up in a roleplay. Consider that if a personality trait is a vector in 3-space, we want to pick traits that aren't coplanar -- ie, that each describe something unique, though possibly with some partial overlap. Ideally, they'd all be perpendicular -- maximally unique traits.\n # I believe I have found 3 such axes that are useful for roleplay:\n # Assertiveness\n # Kindness/Morality\n # Horniness (one of the few things we have an edge over GPT in)\n # So we have\n # Chaste------------------------------------normal----------------------------------------------------------------Slaanesh\n # Shy/Withdrawn/Timid (Bocchi)--------------Has moments of shyness and courage------------------------------------James Bond\n # Kind--------------------------------------Good and bad sides ---------------------------------------------------politician\n # We make more verbose descriptions of each trait and place them in a matrix, reflecting the visualization above. We then create a list of all possible combinations of one item from each row and randomly sample from it for the special instruction.\n\n # NOTE TLDR In laymans terms: we make a grid of traits, where each row represents a trait and values along it indicate different expressions of that trait; then we pick one value from each row and shove it onto the context window as a \"special instruction\".\n\n # Two additional dimensions I thought of afterwards but have never tested: intellectual sophistication, and age. I might add these if testing shows that the AI can handle them, but no few-shot example has anywhere near 5 combinations, so we'll see.\n\n ## NOTE You may (and are encouraged to!) add your own trait dimensions here, to make the character personalities used more accurately reflect your specific use case and preference. Since every possible combination of one trait from each row is put into the list, you will get a lot of variety with your characters for not much work.\n # NOTE Chaste and puritan characters have a tendency to be interpreted by the AI as being religious, possibly because of \"puritan\", even though I initially just meant for this to be the opposite of horny. I'm leaving this in as a way to counteract occasional anti-religious bias and the AI's own personality.\n\n axis_traits = [\n [\n \"The character should be chaste and puritanical.\",\n \"\",\n \"The character should be very seductive and flirtatious.\",\n ], # Horniness (middle deliberately left blank so that the model does not mention it, since \"normal\" people don't usually bring up sex in common conversation... right?)\n [\n \"The character should be shy, withdrawn, and timid.\",\n \"The character should be neither particularly bold, nor particularly timid.\",\n \"The character should be assertive and bold.\",\n ], # Assertiveness\n [\n \"The character should be kind and agreeable.\",\n \"The character should have both good and bad sides.\",\n \"The character should be an awful person, and should be enjoying every second of it.\"\n # \"The character should be an awful person, possessing a number of vices (that are compatible with the previously-mentioned instructions).\"\n ], # Kindness/Morality\n # [\"The character should be a young adult.\", \"the character should be middle-aged.\" \"The character should be in late adulthood.\"], # Age group\n # [\"The character should be unsophisticated and crude.\", \"The character should be decently smart and refined.\", \"The character should be the epitome of intellectual sophistication.\"],\n ]\n\n non_axis_trait_list = [ # The following are examples of traits that are not on the axes above, but are still useful for character creation. Typically use these if you want to easily hardcode your characters to all have a trait. I've not tested all of them, and I've not tested them in combination with the axis traits. But if you prefer a more manual approach to character creation, you can use stuff like this.\n \"\"\"The character should be a catgirl who inserts \"nya\" into every sentence. and makes cat puns.\"\"\", # someone actually has to do this, I'm serious, it'll be purrfect, nya~\n # They can be short and used in combination with the axis traits; or long and replace them.\n \"\"\"The character should be a Japanese High School student.\nThe character should be a girl.\nThe character should be decently smart, but not genius-level.\nThe character should be very kind, but too gentle and too much of a pushover for their own good.\"\"\",\n \"\"\"The character should be an awful person, and enjoying every second of it.\nThe character should be intellectually brilliant.\nThe character should be condescending and rude.\"\"\",\n \"\"\"The character should be a young adult.\nThe character should be antisocial and coarse.\nThe character should be a smoker.\"\"\"\n \"\"\"The character should be middle-aged.\nThe character should be narcissistic.\"\"\"\n # \"\"\"The character should be edgy and nihilistic.\"\"\"\n ]\n\n if not non_axis_traits_only:\n traits = combine_traits(axis_traits)\n\n selected_traits = random.sample(traits, 1)\n if non_axis_traits:\n selected_traits += random.sample(non_axis_trait_list, 1)\n\n if non_axis_traits_only:\n selected_traits = random.sample(non_axis_trait_list, 1)\n\n # Return the combined string, with each sentence on a new line\n return selected_traits[0]","source_hash":"bcba640cafbda2cde503c48e8bbbcdb05d0c4d1f8d9cba9109bffe88f8055304","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.special_instructions.combine_traits","uri":"program://augmentoolkit/function/generation_functions.special_instructions.combine_traits#L5-L15","kind":"function","name":"combine_traits","path":"generation_functions/special_instructions.py","language":"python","start_line":5,"end_line":15,"context_start_line":1,"context_end_line":35,"code":"from itertools import product\nimport random\n\n\ndef combine_traits(personality_matrix): # GPT-generated\n # Using itertools.product to generate all possible combinations\n combinations = product(*personality_matrix)\n\n # Joining each combination into a single string\n combined_traits = [\n \"\\n\".join(combination).strip().replace(\"\\n\\n\", \"\\n\")\n for combination in combinations\n ]\n\n return combined_traits\n\n\ndef special_instructions(n=1, non_axis_traits=False, non_axis_traits_only=False):\n \"\"\"\n documentation todo\n \"\"\"\n\n ### NOTE on how traits are planned out for this step ###\n # Here're the copy-pasted thoughts from my planning document, now slightly cleaned-up for the release of Augmentoolkit. The TLDR is at the bottom. The inspiration for this personality system is the main thing I gained from my math class this semester.\n # CHARACTER PLANNING\n # Consider that we can represent a character's personality a vector with multiple dimensions. Now, we could define any number of individual dimensions, and lots of them would be right: intelligence, extraversion, industriousness, etc. But in the default version of the Augmentool we're doing roleplay, so we want to pick a set of dimensions using which we can describe accurately and concisely the characters that might show up in a roleplay. Consider that if a personality trait is a vector in 3-space, we want to pick traits that aren't coplanar -- ie, that each describe something unique, though possibly with some partial overlap. Ideally, they'd all be perpendicular -- maximally unique traits.\n # I believe I have found 3 such axes that are useful for roleplay:\n # Assertiveness\n # Kindness/Morality\n # Horniness (one of the few things we have an edge over GPT in)\n # So we have\n # Chaste------------------------------------normal----------------------------------------------------------------Slaanesh\n # Shy/Withdrawn/Timid (Bocchi)--------------Has moments of shyness and courage------------------------------------James Bond\n # Kind--------------------------------------Good and bad sides ---------------------------------------------------politician\n # We make more verbose descriptions of each trait and place them in a matrix, reflecting the visualization above. We then create a list of all possible combinations of one item from each row and randomly sample from it for the special instruction.","source_hash":"bcba640cafbda2cde503c48e8bbbcdb05d0c4d1f8d9cba9109bffe88f8055304","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.special_instructions.special_instructions","uri":"program://augmentoolkit/function/generation_functions.special_instructions.special_instructions#L18-L94","kind":"function","name":"special_instructions","path":"generation_functions/special_instructions.py","language":"python","start_line":18,"end_line":94,"context_start_line":1,"context_end_line":94,"code":"from itertools import product\nimport random\n\n\ndef combine_traits(personality_matrix): # GPT-generated\n # Using itertools.product to generate all possible combinations\n combinations = product(*personality_matrix)\n\n # Joining each combination into a single string\n combined_traits = [\n \"\\n\".join(combination).strip().replace(\"\\n\\n\", \"\\n\")\n for combination in combinations\n ]\n\n return combined_traits\n\n\ndef special_instructions(n=1, non_axis_traits=False, non_axis_traits_only=False):\n \"\"\"\n documentation todo\n \"\"\"\n\n ### NOTE on how traits are planned out for this step ###\n # Here're the copy-pasted thoughts from my planning document, now slightly cleaned-up for the release of Augmentoolkit. The TLDR is at the bottom. The inspiration for this personality system is the main thing I gained from my math class this semester.\n # CHARACTER PLANNING\n # Consider that we can represent a character's personality a vector with multiple dimensions. Now, we could define any number of individual dimensions, and lots of them would be right: intelligence, extraversion, industriousness, etc. But in the default version of the Augmentool we're doing roleplay, so we want to pick a set of dimensions using which we can describe accurately and concisely the characters that might show up in a roleplay. Consider that if a personality trait is a vector in 3-space, we want to pick traits that aren't coplanar -- ie, that each describe something unique, though possibly with some partial overlap. Ideally, they'd all be perpendicular -- maximally unique traits.\n # I believe I have found 3 such axes that are useful for roleplay:\n # Assertiveness\n # Kindness/Morality\n # Horniness (one of the few things we have an edge over GPT in)\n # So we have\n # Chaste------------------------------------normal----------------------------------------------------------------Slaanesh\n # Shy/Withdrawn/Timid (Bocchi)--------------Has moments of shyness and courage------------------------------------James Bond\n # Kind--------------------------------------Good and bad sides ---------------------------------------------------politician\n # We make more verbose descriptions of each trait and place them in a matrix, reflecting the visualization above. We then create a list of all possible combinations of one item from each row and randomly sample from it for the special instruction.\n\n # NOTE TLDR In laymans terms: we make a grid of traits, where each row represents a trait and values along it indicate different expressions of that trait; then we pick one value from each row and shove it onto the context window as a \"special instruction\".\n\n # Two additional dimensions I thought of afterwards but have never tested: intellectual sophistication, and age. I might add these if testing shows that the AI can handle them, but no few-shot example has anywhere near 5 combinations, so we'll see.\n\n ## NOTE You may (and are encouraged to!) add your own trait dimensions here, to make the character personalities used more accurately reflect your specific use case and preference. Since every possible combination of one trait from each row is put into the list, you will get a lot of variety with your characters for not much work.\n # NOTE Chaste and puritan characters have a tendency to be interpreted by the AI as being religious, possibly because of \"puritan\", even though I initially just meant for this to be the opposite of horny. I'm leaving this in as a way to counteract occasional anti-religious bias and the AI's own personality.\n\n axis_traits = [\n [\n \"The character should be chaste and puritanical.\",\n \"\",\n \"The character should be very seductive and flirtatious.\",\n ], # Horniness (middle deliberately left blank so that the model does not mention it, since \"normal\" people don't usually bring up sex in common conversation... right?)\n [\n \"The character should be shy, withdrawn, and timid.\",\n \"The character should be neither particularly bold, nor particularly timid.\",\n \"The character should be assertive and bold.\",\n ], # Assertiveness\n [\n \"The character should be kind and agreeable.\",\n \"The character should have both good and bad sides.\",\n \"The character should be an awful person, and should be enjoying every second of it.\"\n # \"The character should be an awful person, possessing a number of vices (that are compatible with the previously-mentioned instructions).\"\n ], # Kindness/Morality\n # [\"The character should be a young adult.\", \"the character should be middle-aged.\" \"The character should be in late adulthood.\"], # Age group\n # [\"The character should be unsophisticated and crude.\", \"The character should be decently smart and refined.\", \"The character should be the epitome of intellectual sophistication.\"],\n ]\n\n non_axis_trait_list = [ # The following are examples of traits that are not on the axes above, but are still useful for character creation. Typically use these if you want to easily hardcode your characters to all have a trait. I've not tested all of them, and I've not tested them in combination with the axis traits. But if you prefer a more manual approach to character creation, you can use stuff like this.\n \"\"\"The character should be a catgirl who inserts \"nya\" into every sentence. and makes cat puns.\"\"\", # someone actually has to do this, I'm serious, it'll be purrfect, nya~\n # They can be short and used in combination with the axis traits; or long and replace them.\n \"\"\"The character should be a Japanese High School student.\nThe character should be a girl.\nThe character should be decently smart, but not genius-level.\nThe character should be very kind, but too gentle and too much of a pushover for their own good.\"\"\",\n \"\"\"The character should be an awful person, and enjoying every second of it.\nThe character should be intellectually brilliant.\nThe character should be condescending and rude.\"\"\",\n \"\"\"The character should be a young adult.\nThe character should be antisocial and coarse.\nThe character should be a smoker.\"\"\"\n \"\"\"The character should be middle-aged.\nThe character should be narcissistic.\"\"\"\n # \"\"\"The character should be edgy and nihilistic.\"\"\"\n ]\n\n if not non_axis_traits_only:\n traits = combine_traits(axis_traits)\n\n selected_traits = random.sample(traits, 1)\n if non_axis_traits:\n selected_traits += random.sample(non_axis_trait_list, 1)\n\n if non_axis_traits_only:\n selected_traits = random.sample(non_axis_trait_list, 1)\n\n # Return the combined string, with each sentence on a new line\n return selected_traits[0]","source_hash":"bcba640cafbda2cde503c48e8bbbcdb05d0c4d1f8d9cba9109bffe88f8055304","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.process_multiturn_functions","uri":"program://augmentoolkit/module/generation_functions.process_multiturn_functions#L1-L503","kind":"module","name":"generation_functions.process_multiturn_functions","path":"generation_functions/process_multiturn_functions.py","language":"python","start_line":1,"end_line":503,"context_start_line":1,"context_end_line":503,"code":"import re\n\n\ndef has_sequential_chars(string1, string2, n):\n \"\"\"\n Check if any n sequential characters from string1 appear in string2.\n\n Args:\n string1 (str): The first string to check.\n string2 (str): The second string in which to look for sequences.\n n (int): The length of the sequence to check.\n\n Returns:\n bool: True if any n sequential characters from string1 are found in string2, False otherwise.\n \"\"\"\n\n # Check if n is larger than the length of string1.\n if n > len(string1):\n return False, \"\"\n\n # Iterate over string1 and check for each n-length substring in string2\n comparison_string = \"\"\n for i in range(len(string1) - n + 1):\n comparison_string = string1[i : i + n]\n if comparison_string in string2:\n return True, comparison_string\n\n return False, comparison_string\n\n\ndef extract_conversation(conversation):\n \"\"\"\n Extracts conversation from a string and returns it as a list of tuples.\n\n Parameters:\n conversation (str): A string representing the conversation.\n\n Returns:\n list of tuples: Each tuple contains the character's name and their message.\n \"\"\"\n lines = conversation.strip().split(\"\\n\")\n dialogues = []\n\n for line in lines:\n if \":\" in line:\n # Splitting at the first occurrence of ':'\n parts = line.split(\":\", 1)\n charname = parts[0].strip()\n message = parts[1].strip() if len(parts) > 1 else \"\"\n dialogues.append((charname, message))\n\n return dialogues\n\n\ndef compare_answers_with_qatuples(dialogues, qatuples, n):\n \"\"\"\n Compares each answer in dialogues with the corresponding answer from qatuples.\n\n Parameters:\n dialogues (list): List of tuples containing the dialogues.\n qatuples (list): List of tuples containing questions and answers.\n n (int): Number of sequential characters to check.\n\n Returns:\n bool: True if all answers match the corresponding answers in qatuples, False otherwise.\n \"\"\"\n for i in range(\n 2, len(dialogues), 2\n ): # Answers are at even indices, starting from 2\n if int(i / 2) - 1 >= len(\n qatuples\n ): # at this point we've reached added stuff that doesn't have a corresponding qatuple\n break\n sequential, comp = has_sequential_chars(\n qatuples[int(i / 2) - 1][1], dialogues[i][1], n\n )\n print(sequential)\n print(n)\n if not sequential:\n print(\n f\"Answer {int(i/2)}: {dialogues[i][1]} does not match the corresponding answer in qatuples: {qatuples[int(i/2) - 1][1]}, {comp}\"\n )\n return False\n return True\n\n\ndef check_for_repeated_dialogue_answers(dialogues, qatuples, n):\n \"\"\"\n Checks each line of dialogue to ensure that it does not repeat the corresponding answer from qatuples.\n\n Parameters:\n dialogues (list): List of tuples containing the dialogues.\n qatuples (list): List of tuples containing questions and answers.\n n (int): Number of sequential characters to check for repetition.\n\n Returns:\n bool: True if no dialogue line repeats its corresponding answer, False otherwise.\n \"\"\"\n for i in range(\n 2, len(dialogues), 2\n ): # Answers are at even indices, starting from 2\n if int(i / 2) - 1 >= len(\n qatuples\n ): # at this point we've reached added stuff that doesn't have a corresponding qatuple\n break\n\n dialogue_answer = dialogues[i][1]\n corresponding_qatuple_answer = qatuples[int(i / 2) - 1][1]\n # Check if the dialogue answer repeats the qatuple answer\n if dialogue_answer.count(corresponding_qatuple_answer) > 1:\n return False\n return True\n\n\n# def check_repeated_answer(dialogues, qatuples):\n# # Get the length of the dialogues\n# conv_length = len(dialogues)\n\n# # Loop through even indices starting from 2 (first answer is at index 2)\n# for i in range(2, conv_length, 2):\n# current_answer = dialogues[i][1][:n_characters_same]\n# next_answer_index = i + 2\n\n# if next_answer_index < conv_length:\n# next_answer = dialogues[next_answer_index][1][:n_characters_same]\n# if current_answer == next_answer:\n# return False\n# return True\n\n\ndef check_conversation_length(conv, qatuples):\n \"\"\"Checks the length of the conversation\"\"\"\n # Dialogues with answers should be at even indices that are not 0\n # qatuples are of the format (question, answer,source_text,name_of_text) -- only the first two are used here\n\n # Get the length of the dialogues\n conv_length = len(conv)\n\n target_length = len(qatuples) * 2 + 1\n if (\n conv_length < target_length\n ): # we can have more messages since the AI might add some stuff at the end to wrap up the scene\n return False\n else:\n return True\n\n\ndef check_conversation_for_text_from_examples(conv):\n \"\"\"Checks if certain strings from the few-shot examples appear in the conversation\"\"\"\n strings_to_check_for = [\n \"her lipstick-colored lips\",\n \"coquettishly tilts her head to the side,\",\n \"Awwww, you're no fun,\",\n \"Reminds me of my colleagues...\",\n \"\" \"I'll see you at that cafe.\",\n \"Ghh... you know,\",\n \"you're breaking a poor woman's heart,\",\n \"surprising innocence and warmth\",\n 'in mock-thought, \"',\n \" _I can't believe my ears. Did \",\n ]\n matches_found = 0\n for string in strings_to_check_for:\n if string in conv:\n matches_found += 1\n print(f\"Found {string} in the conversation!\")\n if matches_found > 2:\n print(\n f\"Found {matches_found} matches for strings from the few-shot examples. Validation failed!\"\n )\n return False\n return True\n\n\ndef check_each_question_contains_q_from_tuples(conv, qatuples, n):\n \"\"\"\n Ensures that each question contains at least n sequential characters from the corresponding question in qatuples.\n If the first question fails this check, return None for special handling.\n\n Parameters:\n conv (list): List of tuples containing the dialogues.\n qatuples (list): List of tuples containing questions and answers.\n n (int): Number of sequential characters to check.\n\n Returns:\n bool or None: True if all questions pass the check, False if any fail, None if the first question fails.\n \"\"\"\n for i in range(1, len(conv), 2): # Questions are at odd indices\n if i // 2 < len(\n qatuples\n ): # Ensure we only check questions that have corresponding qatuples\n question_from_conv = conv[i][1]\n question_from_tuples = qatuples[i // 2][0]\n # print(question_from_tuples, question_from_conv)\n sequential, _ = has_sequential_chars(\n question_from_tuples, question_from_conv, n\n )\n if not sequential:\n if i == 1:\n return None # Special handling for the first question\n else:\n return False\n return True\n\n\ndef check_for_unintended_repeated_quotes(dialogues, qatuples, n_characters_shared):\n \"\"\"\n Checks if answers in the conversation inadvertently use a long quote from another QA pair.\n\n Args:\n dialogues (list): List of tuples containing the dialogues.\n qatuples (list): List of tuples containing questions and answers.\n n_characters_shared (int): Number of sequential characters to check for repetition.\n\n Returns:\n bool: True if no unintended repeated quotes are found, False otherwise.\n \"\"\"\n\n # Extract only the answers from the QA tuples for comparison\n qa_answers = [qa[1] for qa in qatuples]\n\n for i in range(\n 2, len(dialogues), 2\n ): # Answers are at even indices, starting from 2\n # Skip if there's no corresponding QA tuple\n if int(i / 2) - 1 >= len(qatuples):\n break\n\n dialogue_answer = dialogues[i][1]\n corresponding_qa_answer = qatuples[int(i / 2) - 1][1]\n\n # Check for each answer in the QA tuples\n for idx, qa_answer in enumerate(qa_answers):\n # Skip the comparison for the current QA pair itself\n if qa_answer == corresponding_qa_answer:\n continue\n\n # Check if the dialogue answer contains a long quote from another QA answer\n sequential, comp_string = has_sequential_chars(\n qa_answer, dialogue_answer, n_characters_shared\n )\n if sequential:\n if comp_string in corresponding_qa_answer:\n continue # This is a quote from the corresponding answer, so it's fine\n else:\n # Found an unintended repeated quote\n return False\n return True\n\n\ndef call_all_processors(multiturn_conversation, qatuples):\n convs_split = extract_conversation(multiturn_conversation)\n\n # Check if answers in dialogues match corresponding answers in qatuples\n if not compare_answers_with_qatuples(convs_split, qatuples, 15):\n print(\"Answers in dialogues do not match corresponding answers in qatuples.\")\n return False\n\n # Check if any dialogue line repeats its corresponding answer\n if not check_for_repeated_dialogue_answers(convs_split, qatuples, 15):\n print(\"Dialogue line repeats its corresponding answer.\")\n return False\n\n # Check the conversation length\n if not check_conversation_length(convs_split, qatuples):\n print(\"Conversation is too short! Validation failed!\")\n return False\n\n # Check for text from examples (assuming this is implemented elsewhere)\n if not check_conversation_for_text_from_examples(multiturn_conversation):\n print(\"Conversation does not contain text from examples. Validation failed!\")\n return False\n\n # Check for unintended repeated quotes\n if not check_for_unintended_repeated_quotes(convs_split, qatuples, 100):\n print(\"Conversation contains unintended repeated quotes. Validation failed!\")\n return False\n\n # Check each question contains a part of the question from tuples\n result = check_each_question_contains_q_from_tuples(convs_split, qatuples, 15)\n if result is None:\n print(\n \"First question does not contain a part of the question from tuples. Validation failed!\"\n )\n return None\n elif not result:\n print(\n \"Each question does not contain a part of the question from tuples. Validation failed!\"\n )\n return False\n\n # If all checks pass\n return True\n\n\nif __name__ == \"__main__\":\n # Test cases for has_sequential_chars\n print(\"Testing has_sequential_chars:\")\n print(has_sequential_chars(\"hello\", \"worldhello\", 3)) #\n print(\"Expected True\")\n print(has_sequential_chars(\"abc\", \"defghijkl\", 2)) # Expected False\n print(\"Expected False\")\n print(has_sequential_chars(\"\", \"empty\", 1)) # Expected False (empty string1)\n print(\"Expected False\")\n print(\n has_sequential_chars(\"longstring\", \"short\", 5)\n ) # Expected False (n is longer than string2)\n print(\"Expected False\")\n print(\n has_sequential_chars(\"overlap\", \"laptopp\", 3)\n ) # Expected True (partial overlap)\n print(\"Expected True\")\n\n # Test cases for extract_conversation\n print(\"\\nTesting extract_conversation:\")\n test_conversation1 = \"Charname1: Hello\\nCharname2: Hi\\nCharname3: How are you?\"\n print(\n extract_conversation(test_conversation1)\n ) # Expected [('Charname1', 'Hello'), ('Charname2', 'Hi'), ('Charname3', 'How are you?')]\n print(\n \"Expected [('Charname1', 'Hello'), ('Charname2', 'Hi'), ('Charname3', 'How are you?')]\"\n )\n test_conversation2 = \"No colons here\"\n print(extract_conversation(test_conversation2)) # Expected []\n print(\"Expected []\")\n test_conversation3 = \"\"\n print(extract_conversation(test_conversation3)) # Expected []\n print(\"Expected []\")\n\n # Test cases for compare_answers_with_qatuples\n print(\"\\nTesting compare_answers_with_qatuples:\")\n dialogues1 = [\n (\"Charname1\", \"Hello\"),\n (\"Charname2\", \"Hi how are you\"),\n \"Totally Fantastic and Amazing!\",\n ]\n qatuples1 = [(\"How are you?\", \"Fine\")]\n print(compare_answers_with_qatuples(dialogues1, qatuples1, 2)) # Expected False\n print(\"Expected False\")\n dialogues2 = [\n (\"Charname1\", \"Hello\"),\n (\"Charname2\", \"Hi how are you\"),\n (\"Charname1\", \"Mostly Fine I think, yeah\"),\n ]\n print(compare_answers_with_qatuples(dialogues2, qatuples1, 2)) # Expected True\n print(\"Expected True\")\n dialogues3 = []\n qatuples2 = []\n print(\n compare_answers_with_qatuples(dialogues3, qatuples2, 2)\n ) # Expected True (both empty)\n print(\"Expected True (both empty)\")\n\n # Test cases for check_for_repeated_dialogue_answers\n print(\"\\nTesting check_for_repeated_dialogue_answers:\")\n qatuples_repeated_answers = [(\"How are you?\", \"Fine, thank you for asking!\")]\n dialogues4 = [\n (\"Charname1\", \"Hello\"),\n (\"Charname2\", \"How are you?\"),\n (\"Charname1\", \"Fine, thank you for asking!\"),\n ]\n print(\n check_for_repeated_dialogue_answers(dialogues4, qatuples_repeated_answers, 2)\n ) # Expected True (no repetition)\n print(\"Expected True (no repetition)\")\n dialogues5 = [\n (\"Charname1\", \"Hello\"),\n (\"Charname2\", \"How are you?\"),\n (\n \"Charname1\",\n \"Fine, thank you for asking! It's nice today, after all, so I'm Fine, thank you for asking!\",\n ),\n ]\n print(\n check_for_repeated_dialogue_answers(dialogues5, qatuples_repeated_answers, 2)\n ) # Expected False (repetition)\n print(\"Expected False (repetition)\")\n\n # Test cases for check_repeated_answer\n # print(\"\\nTesting check_repeated_answer:\")\n # dialogues6 = [(\"Charname1\", \"Question\"), (\"Charname2\", \"Answer1\"), (\"Charname3\", \"Question\"), (\"Charname4\", \"Answer1\")]\n # print(check_repeated_answer(dialogues6)) # Expected False (repeated answers)\n # dialogues7 = [(\"Charname1\", \"Question\"), (\"Charname2\", \"Answer1\"), (\"Charname3\", \"Question\"), (\"Charname4\", \"Answer2\")]\n # print(check_repeated_answer(dialogues7)) # Expected True (different answers)\n\n # Test cases for check_conversation_length\n print(\"\\nTesting check_conversation_length:\")\n conv1 = [(\"Charname1\", \"Hello\"), (\"Charname2\", \"Hi, How are you?\")]\n print(\n check_conversation_length(conv1, qatuples1)\n ) # Expected False (conversation too short)\n print(\"Expected False (conversation too short)\")\n conv2 = [(\"Charname1\", \"Hello\"), (\"Charname2\", \"Hi\"), (\"Charname3\", \"How are you?\")]\n print(check_conversation_length(conv2, qatuples1)) # Expected True (correct length)\n print(\"Expected True (correct length)\")\n\n # Test cases for check_conversation_for_text_from_examples (commented out as implementation is assumed elsewhere)\n # print(\"\\nTesting check_conversation_for_text_from_examples:\")\n # conv3 = \"This conversation contains lipstick-colored lips and a coquettishly tilting head.\"\n # print(check_conversation_for_text_from_examples(conv3)) # Expected False (contains example texts)\n\n # Test cases for check_each_question_contains_q_from_tuples\n print(\"\\nTesting check_each_question_contains_q_from_tuples:\")\n conv4 = [\n (\"Charname2\", \"Hiya~!\"),\n (\"Charname1\", \"What's your favorite color?\"),\n (\"Charname2\", \"I'm Fine, thank you very much!\"),\n ]\n print(check_each_question_contains_q_from_tuples(conv4, qatuples1, 6))\n print(\"Expected None (no matching question, first Q)\")\n\n conv45 = [\n (\"Charname2\", \"Hiya~!\"),\n (\"Charname1\", \"How are you?\"),\n (\"Charname2\", \"I'm Fine, thank you very much!\"),\n (\"Charname1\", \"What is the airspeed velocity of an unladen swallow?\"),\n (\"Charname2\", \"Black, like my soul.\"),\n ]\n qatuples3 = [\n (\"How are you?\", \"I'm Fine, thank you very much!\"),\n (\"What's your favorite color?\", \"Black, like my soul.\"),\n ]\n print(check_each_question_contains_q_from_tuples(conv45, qatuples3, 6))\n print(\"Expected False (no matching question, second Q)\")\n\n conv5 = [\n (\"Charname1\", \"Hiya~!\"),\n (\"Charname2\", \"How are you?\"),\n (\"Charname2\", \"I'm Fine, thank you very much!\"),\n (\"Charname1\", \"What's your favorite color?\"),\n (\"Charname2\", \"Black, like my soul.\"),\n ]\n print(check_each_question_contains_q_from_tuples(conv5, qatuples1 + [], 6)) #\n print(\"Expected True (question contains part of qatuple question)\")\n\n # Test cases for check_for_unintended_repeated_quotes\n print(\"\\nTesting check_for_unintended_repeated_quotes:\")\n # Creating a set of dialogues and qatuples where there is an unintended repeated quote\n qatuples_shared = [\n (\"What is your favorite book?\", \"I love reading The Hobbit.\"),\n (\n \"Tell me about a recent happy moment.\",\n \"My friends threw me a surprise party!\",\n ),\n ]\n dialogues_shared1 = [\n (\"Charname1\", \"Hello\"),\n (\"Charname2\", \"What is your favorite book?\"),\n (\"Charname1\", \"I love reading The Hobbit.\"),\n (\"Charname2\", \"Tell me about a recent happy moment.\"),\n (\n \"Charname1\",\n \"My friends threw me a surprise party! It felt just like I was in The Hobbit.\",\n ),\n ]\n print(\n check_for_unintended_repeated_quotes(dialogues_shared1, qatuples_shared, 10)\n ) # Expected False (repeated long quote from another answer)\n print(\"Expected False (repeated long quote from another answer)\")\n\n # Creating a set of dialogues and qatuples where there are no unintended repeated quotes\n dialogues_shared2 = [\n (\"Charname1\", \"Hello\"),\n (\"Charname2\", \"What is your favorite book?\"),\n (\"Charname1\", \"I absolutely adore The Lord of the Rings.\"),\n (\"Charname2\", \"Tell me about a recent happy moment.\"),\n (\"Charname1\", \"I had a great time at the beach last weekend!\"),\n ]\n print(\n check_for_unintended_repeated_quotes(dialogues_shared2, qatuples_shared, 10)\n ) # Expected True (no repeated long quotes)\n print(\"Expected True (no repeated long quotes)\")\n\n # Test cases for call_all_processors\n print(\"\\nTesting call_all_processors:\")\n complete_conversation = \"\"\"\n Charname1: Hello\n Charname2: How are you doing today?\n Charname1: I'm fine, thank you very much!\n Charname2: What's the weather like?\n Charname1: It's sunny and warm. I don't like sand. It's coarse and rough and irritating and it gets everywhere.\n Foo: Bar\n Baz: Quux\n \"\"\"\n qatuples_complete = [\n (\"How are you doing today?\", \"I'm fine, thank you very much!\"),\n (\n \"What's the weather like?\",\n \"It's sunny and warm. I don't like sand. It's coarse and rough and irritating and it gets everywhere.\",\n ),\n ]\n print(call_all_processors(complete_conversation, qatuples_complete)) #\n print(\"Expected True (all checks pass)\")\n incomplete_conversation = \"\"\"\n Charname1: How's it going?\n Charname2: Good.\n Charname1: Any plans?\n Charname2: None.\n Foo: Bar\n Baz: Quux\n \"\"\"\n print(call_all_processors(incomplete_conversation, qatuples_complete)) #\n print(\"Expected False (checks fail)\")","source_hash":"d64b936815bab480e0b4c2c7b7673233ddc405c27f426468714d8dd27b46eccd","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.process_multiturn_functions.has_sequential_chars","uri":"program://augmentoolkit/function/generation_functions.process_multiturn_functions.has_sequential_chars#L4-L28","kind":"function","name":"has_sequential_chars","path":"generation_functions/process_multiturn_functions.py","language":"python","start_line":4,"end_line":28,"context_start_line":1,"context_end_line":48,"code":"import re\n\n\ndef has_sequential_chars(string1, string2, n):\n \"\"\"\n Check if any n sequential characters from string1 appear in string2.\n\n Args:\n string1 (str): The first string to check.\n string2 (str): The second string in which to look for sequences.\n n (int): The length of the sequence to check.\n\n Returns:\n bool: True if any n sequential characters from string1 are found in string2, False otherwise.\n \"\"\"\n\n # Check if n is larger than the length of string1.\n if n > len(string1):\n return False, \"\"\n\n # Iterate over string1 and check for each n-length substring in string2\n comparison_string = \"\"\n for i in range(len(string1) - n + 1):\n comparison_string = string1[i : i + n]\n if comparison_string in string2:\n return True, comparison_string\n\n return False, comparison_string\n\n\ndef extract_conversation(conversation):\n \"\"\"\n Extracts conversation from a string and returns it as a list of tuples.\n\n Parameters:\n conversation (str): A string representing the conversation.\n\n Returns:\n list of tuples: Each tuple contains the character's name and their message.\n \"\"\"\n lines = conversation.strip().split(\"\\n\")\n dialogues = []\n\n for line in lines:\n if \":\" in line:\n # Splitting at the first occurrence of ':'\n parts = line.split(\":\", 1)\n charname = parts[0].strip()","source_hash":"d64b936815bab480e0b4c2c7b7673233ddc405c27f426468714d8dd27b46eccd","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.process_multiturn_functions.extract_conversation","uri":"program://augmentoolkit/function/generation_functions.process_multiturn_functions.extract_conversation#L31-L52","kind":"function","name":"extract_conversation","path":"generation_functions/process_multiturn_functions.py","language":"python","start_line":31,"end_line":52,"context_start_line":11,"context_end_line":72,"code":" n (int): The length of the sequence to check.\n\n Returns:\n bool: True if any n sequential characters from string1 are found in string2, False otherwise.\n \"\"\"\n\n # Check if n is larger than the length of string1.\n if n > len(string1):\n return False, \"\"\n\n # Iterate over string1 and check for each n-length substring in string2\n comparison_string = \"\"\n for i in range(len(string1) - n + 1):\n comparison_string = string1[i : i + n]\n if comparison_string in string2:\n return True, comparison_string\n\n return False, comparison_string\n\n\ndef extract_conversation(conversation):\n \"\"\"\n Extracts conversation from a string and returns it as a list of tuples.\n\n Parameters:\n conversation (str): A string representing the conversation.\n\n Returns:\n list of tuples: Each tuple contains the character's name and their message.\n \"\"\"\n lines = conversation.strip().split(\"\\n\")\n dialogues = []\n\n for line in lines:\n if \":\" in line:\n # Splitting at the first occurrence of ':'\n parts = line.split(\":\", 1)\n charname = parts[0].strip()\n message = parts[1].strip() if len(parts) > 1 else \"\"\n dialogues.append((charname, message))\n\n return dialogues\n\n\ndef compare_answers_with_qatuples(dialogues, qatuples, n):\n \"\"\"\n Compares each answer in dialogues with the corresponding answer from qatuples.\n\n Parameters:\n dialogues (list): List of tuples containing the dialogues.\n qatuples (list): List of tuples containing questions and answers.\n n (int): Number of sequential characters to check.\n\n Returns:\n bool: True if all answers match the corresponding answers in qatuples, False otherwise.\n \"\"\"\n for i in range(\n 2, len(dialogues), 2\n ): # Answers are at even indices, starting from 2\n if int(i / 2) - 1 >= len(\n qatuples\n ): # at this point we've reached added stuff that doesn't have a corresponding qatuple","source_hash":"d64b936815bab480e0b4c2c7b7673233ddc405c27f426468714d8dd27b46eccd","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.process_multiturn_functions.compare_answers_with_qatuples","uri":"program://augmentoolkit/function/generation_functions.process_multiturn_functions.compare_answers_with_qatuples#L55-L84","kind":"function","name":"compare_answers_with_qatuples","path":"generation_functions/process_multiturn_functions.py","language":"python","start_line":55,"end_line":84,"context_start_line":35,"context_end_line":104,"code":" Parameters:\n conversation (str): A string representing the conversation.\n\n Returns:\n list of tuples: Each tuple contains the character's name and their message.\n \"\"\"\n lines = conversation.strip().split(\"\\n\")\n dialogues = []\n\n for line in lines:\n if \":\" in line:\n # Splitting at the first occurrence of ':'\n parts = line.split(\":\", 1)\n charname = parts[0].strip()\n message = parts[1].strip() if len(parts) > 1 else \"\"\n dialogues.append((charname, message))\n\n return dialogues\n\n\ndef compare_answers_with_qatuples(dialogues, qatuples, n):\n \"\"\"\n Compares each answer in dialogues with the corresponding answer from qatuples.\n\n Parameters:\n dialogues (list): List of tuples containing the dialogues.\n qatuples (list): List of tuples containing questions and answers.\n n (int): Number of sequential characters to check.\n\n Returns:\n bool: True if all answers match the corresponding answers in qatuples, False otherwise.\n \"\"\"\n for i in range(\n 2, len(dialogues), 2\n ): # Answers are at even indices, starting from 2\n if int(i / 2) - 1 >= len(\n qatuples\n ): # at this point we've reached added stuff that doesn't have a corresponding qatuple\n break\n sequential, comp = has_sequential_chars(\n qatuples[int(i / 2) - 1][1], dialogues[i][1], n\n )\n print(sequential)\n print(n)\n if not sequential:\n print(\n f\"Answer {int(i/2)}: {dialogues[i][1]} does not match the corresponding answer in qatuples: {qatuples[int(i/2) - 1][1]}, {comp}\"\n )\n return False\n return True\n\n\ndef check_for_repeated_dialogue_answers(dialogues, qatuples, n):\n \"\"\"\n Checks each line of dialogue to ensure that it does not repeat the corresponding answer from qatuples.\n\n Parameters:\n dialogues (list): List of tuples containing the dialogues.\n qatuples (list): List of tuples containing questions and answers.\n n (int): Number of sequential characters to check for repetition.\n\n Returns:\n bool: True if no dialogue line repeats its corresponding answer, False otherwise.\n \"\"\"\n for i in range(\n 2, len(dialogues), 2\n ): # Answers are at even indices, starting from 2\n if int(i / 2) - 1 >= len(\n qatuples\n ): # at this point we've reached added stuff that doesn't have a corresponding qatuple","source_hash":"d64b936815bab480e0b4c2c7b7673233ddc405c27f426468714d8dd27b46eccd","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.process_multiturn_functions.check_for_repeated_dialogue_answers","uri":"program://augmentoolkit/function/generation_functions.process_multiturn_functions.check_for_repeated_dialogue_answers#L87-L112","kind":"function","name":"check_for_repeated_dialogue_answers","path":"generation_functions/process_multiturn_functions.py","language":"python","start_line":87,"end_line":112,"context_start_line":67,"context_end_line":132,"code":" for i in range(\n 2, len(dialogues), 2\n ): # Answers are at even indices, starting from 2\n if int(i / 2) - 1 >= len(\n qatuples\n ): # at this point we've reached added stuff that doesn't have a corresponding qatuple\n break\n sequential, comp = has_sequential_chars(\n qatuples[int(i / 2) - 1][1], dialogues[i][1], n\n )\n print(sequential)\n print(n)\n if not sequential:\n print(\n f\"Answer {int(i/2)}: {dialogues[i][1]} does not match the corresponding answer in qatuples: {qatuples[int(i/2) - 1][1]}, {comp}\"\n )\n return False\n return True\n\n\ndef check_for_repeated_dialogue_answers(dialogues, qatuples, n):\n \"\"\"\n Checks each line of dialogue to ensure that it does not repeat the corresponding answer from qatuples.\n\n Parameters:\n dialogues (list): List of tuples containing the dialogues.\n qatuples (list): List of tuples containing questions and answers.\n n (int): Number of sequential characters to check for repetition.\n\n Returns:\n bool: True if no dialogue line repeats its corresponding answer, False otherwise.\n \"\"\"\n for i in range(\n 2, len(dialogues), 2\n ): # Answers are at even indices, starting from 2\n if int(i / 2) - 1 >= len(\n qatuples\n ): # at this point we've reached added stuff that doesn't have a corresponding qatuple\n break\n\n dialogue_answer = dialogues[i][1]\n corresponding_qatuple_answer = qatuples[int(i / 2) - 1][1]\n # Check if the dialogue answer repeats the qatuple answer\n if dialogue_answer.count(corresponding_qatuple_answer) > 1:\n return False\n return True\n\n\n# def check_repeated_answer(dialogues, qatuples):\n# # Get the length of the dialogues\n# conv_length = len(dialogues)\n\n# # Loop through even indices starting from 2 (first answer is at index 2)\n# for i in range(2, conv_length, 2):\n# current_answer = dialogues[i][1][:n_characters_same]\n# next_answer_index = i + 2\n\n# if next_answer_index < conv_length:\n# next_answer = dialogues[next_answer_index][1][:n_characters_same]\n# if current_answer == next_answer:\n# return False\n# return True\n\n\ndef check_conversation_length(conv, qatuples):\n \"\"\"Checks the length of the conversation\"\"\"","source_hash":"d64b936815bab480e0b4c2c7b7673233ddc405c27f426468714d8dd27b46eccd","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.process_multiturn_functions.check_conversation_length","uri":"program://augmentoolkit/function/generation_functions.process_multiturn_functions.check_conversation_length#L131-L145","kind":"function","name":"check_conversation_length","path":"generation_functions/process_multiturn_functions.py","language":"python","start_line":131,"end_line":145,"context_start_line":111,"context_end_line":165,"code":" return False\n return True\n\n\n# def check_repeated_answer(dialogues, qatuples):\n# # Get the length of the dialogues\n# conv_length = len(dialogues)\n\n# # Loop through even indices starting from 2 (first answer is at index 2)\n# for i in range(2, conv_length, 2):\n# current_answer = dialogues[i][1][:n_characters_same]\n# next_answer_index = i + 2\n\n# if next_answer_index < conv_length:\n# next_answer = dialogues[next_answer_index][1][:n_characters_same]\n# if current_answer == next_answer:\n# return False\n# return True\n\n\ndef check_conversation_length(conv, qatuples):\n \"\"\"Checks the length of the conversation\"\"\"\n # Dialogues with answers should be at even indices that are not 0\n # qatuples are of the format (question, answer,source_text,name_of_text) -- only the first two are used here\n\n # Get the length of the dialogues\n conv_length = len(conv)\n\n target_length = len(qatuples) * 2 + 1\n if (\n conv_length < target_length\n ): # we can have more messages since the AI might add some stuff at the end to wrap up the scene\n return False\n else:\n return True\n\n\ndef check_conversation_for_text_from_examples(conv):\n \"\"\"Checks if certain strings from the few-shot examples appear in the conversation\"\"\"\n strings_to_check_for = [\n \"her lipstick-colored lips\",\n \"coquettishly tilts her head to the side,\",\n \"Awwww, you're no fun,\",\n \"Reminds me of my colleagues...\",\n \"\" \"I'll see you at that cafe.\",\n \"Ghh... you know,\",\n \"you're breaking a poor woman's heart,\",\n \"surprising innocence and warmth\",\n 'in mock-thought, \"',\n \" _I can't believe my ears. Did \",\n ]\n matches_found = 0\n for string in strings_to_check_for:\n if string in conv:\n matches_found += 1","source_hash":"d64b936815bab480e0b4c2c7b7673233ddc405c27f426468714d8dd27b46eccd","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.process_multiturn_functions.check_conversation_for_text_from_examples","uri":"program://augmentoolkit/function/generation_functions.process_multiturn_functions.check_conversation_for_text_from_examples#L148-L172","kind":"function","name":"check_conversation_for_text_from_examples","path":"generation_functions/process_multiturn_functions.py","language":"python","start_line":148,"end_line":172,"context_start_line":128,"context_end_line":192,"code":"# return True\n\n\ndef check_conversation_length(conv, qatuples):\n \"\"\"Checks the length of the conversation\"\"\"\n # Dialogues with answers should be at even indices that are not 0\n # qatuples are of the format (question, answer,source_text,name_of_text) -- only the first two are used here\n\n # Get the length of the dialogues\n conv_length = len(conv)\n\n target_length = len(qatuples) * 2 + 1\n if (\n conv_length < target_length\n ): # we can have more messages since the AI might add some stuff at the end to wrap up the scene\n return False\n else:\n return True\n\n\ndef check_conversation_for_text_from_examples(conv):\n \"\"\"Checks if certain strings from the few-shot examples appear in the conversation\"\"\"\n strings_to_check_for = [\n \"her lipstick-colored lips\",\n \"coquettishly tilts her head to the side,\",\n \"Awwww, you're no fun,\",\n \"Reminds me of my colleagues...\",\n \"\" \"I'll see you at that cafe.\",\n \"Ghh... you know,\",\n \"you're breaking a poor woman's heart,\",\n \"surprising innocence and warmth\",\n 'in mock-thought, \"',\n \" _I can't believe my ears. Did \",\n ]\n matches_found = 0\n for string in strings_to_check_for:\n if string in conv:\n matches_found += 1\n print(f\"Found {string} in the conversation!\")\n if matches_found > 2:\n print(\n f\"Found {matches_found} matches for strings from the few-shot examples. Validation failed!\"\n )\n return False\n return True\n\n\ndef check_each_question_contains_q_from_tuples(conv, qatuples, n):\n \"\"\"\n Ensures that each question contains at least n sequential characters from the corresponding question in qatuples.\n If the first question fails this check, return None for special handling.\n\n Parameters:\n conv (list): List of tuples containing the dialogues.\n qatuples (list): List of tuples containing questions and answers.\n n (int): Number of sequential characters to check.\n\n Returns:\n bool or None: True if all questions pass the check, False if any fail, None if the first question fails.\n \"\"\"\n for i in range(1, len(conv), 2): # Questions are at odd indices\n if i // 2 < len(\n qatuples\n ): # Ensure we only check questions that have corresponding qatuples\n question_from_conv = conv[i][1]","source_hash":"d64b936815bab480e0b4c2c7b7673233ddc405c27f426468714d8dd27b46eccd","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.process_multiturn_functions.check_each_question_contains_q_from_tuples","uri":"program://augmentoolkit/function/generation_functions.process_multiturn_functions.check_each_question_contains_q_from_tuples#L175-L203","kind":"function","name":"check_each_question_contains_q_from_tuples","path":"generation_functions/process_multiturn_functions.py","language":"python","start_line":175,"end_line":203,"context_start_line":155,"context_end_line":223,"code":" \"\" \"I'll see you at that cafe.\",\n \"Ghh... you know,\",\n \"you're breaking a poor woman's heart,\",\n \"surprising innocence and warmth\",\n 'in mock-thought, \"',\n \" _I can't believe my ears. Did \",\n ]\n matches_found = 0\n for string in strings_to_check_for:\n if string in conv:\n matches_found += 1\n print(f\"Found {string} in the conversation!\")\n if matches_found > 2:\n print(\n f\"Found {matches_found} matches for strings from the few-shot examples. Validation failed!\"\n )\n return False\n return True\n\n\ndef check_each_question_contains_q_from_tuples(conv, qatuples, n):\n \"\"\"\n Ensures that each question contains at least n sequential characters from the corresponding question in qatuples.\n If the first question fails this check, return None for special handling.\n\n Parameters:\n conv (list): List of tuples containing the dialogues.\n qatuples (list): List of tuples containing questions and answers.\n n (int): Number of sequential characters to check.\n\n Returns:\n bool or None: True if all questions pass the check, False if any fail, None if the first question fails.\n \"\"\"\n for i in range(1, len(conv), 2): # Questions are at odd indices\n if i // 2 < len(\n qatuples\n ): # Ensure we only check questions that have corresponding qatuples\n question_from_conv = conv[i][1]\n question_from_tuples = qatuples[i // 2][0]\n # print(question_from_tuples, question_from_conv)\n sequential, _ = has_sequential_chars(\n question_from_tuples, question_from_conv, n\n )\n if not sequential:\n if i == 1:\n return None # Special handling for the first question\n else:\n return False\n return True\n\n\ndef check_for_unintended_repeated_quotes(dialogues, qatuples, n_characters_shared):\n \"\"\"\n Checks if answers in the conversation inadvertently use a long quote from another QA pair.\n\n Args:\n dialogues (list): List of tuples containing the dialogues.\n qatuples (list): List of tuples containing questions and answers.\n n_characters_shared (int): Number of sequential characters to check for repetition.\n\n Returns:\n bool: True if no unintended repeated quotes are found, False otherwise.\n \"\"\"\n\n # Extract only the answers from the QA tuples for comparison\n qa_answers = [qa[1] for qa in qatuples]\n\n for i in range(\n 2, len(dialogues), 2","source_hash":"d64b936815bab480e0b4c2c7b7673233ddc405c27f426468714d8dd27b46eccd","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.process_multiturn_functions.check_for_unintended_repeated_quotes","uri":"program://augmentoolkit/function/generation_functions.process_multiturn_functions.check_for_unintended_repeated_quotes#L206-L248","kind":"function","name":"check_for_unintended_repeated_quotes","path":"generation_functions/process_multiturn_functions.py","language":"python","start_line":206,"end_line":248,"context_start_line":186,"context_end_line":268,"code":" bool or None: True if all questions pass the check, False if any fail, None if the first question fails.\n \"\"\"\n for i in range(1, len(conv), 2): # Questions are at odd indices\n if i // 2 < len(\n qatuples\n ): # Ensure we only check questions that have corresponding qatuples\n question_from_conv = conv[i][1]\n question_from_tuples = qatuples[i // 2][0]\n # print(question_from_tuples, question_from_conv)\n sequential, _ = has_sequential_chars(\n question_from_tuples, question_from_conv, n\n )\n if not sequential:\n if i == 1:\n return None # Special handling for the first question\n else:\n return False\n return True\n\n\ndef check_for_unintended_repeated_quotes(dialogues, qatuples, n_characters_shared):\n \"\"\"\n Checks if answers in the conversation inadvertently use a long quote from another QA pair.\n\n Args:\n dialogues (list): List of tuples containing the dialogues.\n qatuples (list): List of tuples containing questions and answers.\n n_characters_shared (int): Number of sequential characters to check for repetition.\n\n Returns:\n bool: True if no unintended repeated quotes are found, False otherwise.\n \"\"\"\n\n # Extract only the answers from the QA tuples for comparison\n qa_answers = [qa[1] for qa in qatuples]\n\n for i in range(\n 2, len(dialogues), 2\n ): # Answers are at even indices, starting from 2\n # Skip if there's no corresponding QA tuple\n if int(i / 2) - 1 >= len(qatuples):\n break\n\n dialogue_answer = dialogues[i][1]\n corresponding_qa_answer = qatuples[int(i / 2) - 1][1]\n\n # Check for each answer in the QA tuples\n for idx, qa_answer in enumerate(qa_answers):\n # Skip the comparison for the current QA pair itself\n if qa_answer == corresponding_qa_answer:\n continue\n\n # Check if the dialogue answer contains a long quote from another QA answer\n sequential, comp_string = has_sequential_chars(\n qa_answer, dialogue_answer, n_characters_shared\n )\n if sequential:\n if comp_string in corresponding_qa_answer:\n continue # This is a quote from the corresponding answer, so it's fine\n else:\n # Found an unintended repeated quote\n return False\n return True\n\n\ndef call_all_processors(multiturn_conversation, qatuples):\n convs_split = extract_conversation(multiturn_conversation)\n\n # Check if answers in dialogues match corresponding answers in qatuples\n if not compare_answers_with_qatuples(convs_split, qatuples, 15):\n print(\"Answers in dialogues do not match corresponding answers in qatuples.\")\n return False\n\n # Check if any dialogue line repeats its corresponding answer\n if not check_for_repeated_dialogue_answers(convs_split, qatuples, 15):\n print(\"Dialogue line repeats its corresponding answer.\")\n return False\n\n # Check the conversation length\n if not check_conversation_length(convs_split, qatuples):\n print(\"Conversation is too short! Validation failed!\")\n return False\n","source_hash":"d64b936815bab480e0b4c2c7b7673233ddc405c27f426468714d8dd27b46eccd","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.process_multiturn_functions.call_all_processors","uri":"program://augmentoolkit/function/generation_functions.process_multiturn_functions.call_all_processors#L251-L293","kind":"function","name":"call_all_processors","path":"generation_functions/process_multiturn_functions.py","language":"python","start_line":251,"end_line":293,"context_start_line":231,"context_end_line":313,"code":"\n # Check for each answer in the QA tuples\n for idx, qa_answer in enumerate(qa_answers):\n # Skip the comparison for the current QA pair itself\n if qa_answer == corresponding_qa_answer:\n continue\n\n # Check if the dialogue answer contains a long quote from another QA answer\n sequential, comp_string = has_sequential_chars(\n qa_answer, dialogue_answer, n_characters_shared\n )\n if sequential:\n if comp_string in corresponding_qa_answer:\n continue # This is a quote from the corresponding answer, so it's fine\n else:\n # Found an unintended repeated quote\n return False\n return True\n\n\ndef call_all_processors(multiturn_conversation, qatuples):\n convs_split = extract_conversation(multiturn_conversation)\n\n # Check if answers in dialogues match corresponding answers in qatuples\n if not compare_answers_with_qatuples(convs_split, qatuples, 15):\n print(\"Answers in dialogues do not match corresponding answers in qatuples.\")\n return False\n\n # Check if any dialogue line repeats its corresponding answer\n if not check_for_repeated_dialogue_answers(convs_split, qatuples, 15):\n print(\"Dialogue line repeats its corresponding answer.\")\n return False\n\n # Check the conversation length\n if not check_conversation_length(convs_split, qatuples):\n print(\"Conversation is too short! Validation failed!\")\n return False\n\n # Check for text from examples (assuming this is implemented elsewhere)\n if not check_conversation_for_text_from_examples(multiturn_conversation):\n print(\"Conversation does not contain text from examples. Validation failed!\")\n return False\n\n # Check for unintended repeated quotes\n if not check_for_unintended_repeated_quotes(convs_split, qatuples, 100):\n print(\"Conversation contains unintended repeated quotes. Validation failed!\")\n return False\n\n # Check each question contains a part of the question from tuples\n result = check_each_question_contains_q_from_tuples(convs_split, qatuples, 15)\n if result is None:\n print(\n \"First question does not contain a part of the question from tuples. Validation failed!\"\n )\n return None\n elif not result:\n print(\n \"Each question does not contain a part of the question from tuples. Validation failed!\"\n )\n return False\n\n # If all checks pass\n return True\n\n\nif __name__ == \"__main__\":\n # Test cases for has_sequential_chars\n print(\"Testing has_sequential_chars:\")\n print(has_sequential_chars(\"hello\", \"worldhello\", 3)) #\n print(\"Expected True\")\n print(has_sequential_chars(\"abc\", \"defghijkl\", 2)) # Expected False\n print(\"Expected False\")\n print(has_sequential_chars(\"\", \"empty\", 1)) # Expected False (empty string1)\n print(\"Expected False\")\n print(\n has_sequential_chars(\"longstring\", \"short\", 5)\n ) # Expected False (n is longer than string2)\n print(\"Expected False\")\n print(\n has_sequential_chars(\"overlap\", \"laptopp\", 3)\n ) # Expected True (partial overlap)\n print(\"Expected True\")\n","source_hash":"d64b936815bab480e0b4c2c7b7673233ddc405c27f426468714d8dd27b46eccd","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.question_plan_grammar","uri":"program://augmentoolkit/module/generation_functions.question_plan_grammar#L1-L45","kind":"module","name":"generation_functions.question_plan_grammar","path":"generation_functions/question_plan_grammar.py","language":"python","start_line":1,"end_line":45,"context_start_line":1,"context_end_line":45,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\nquestion_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\n\n# root ::= reasoning-start\n# At least 3 steps\nroot ::= identify-step generate-step brainstorm-step relationships-step if-then-step make-suitable-step\n\n# no-questions-after-here ::= \"\\nI will not ask any questions about the following information: \" [^\\n]+ \".\"\n\nidentify-step ::= \"Step \" [0-9]?[0-9] \". \" \"Identify Key Topics:\" [^\\n]+ \"\\n\"\n\n# generate-step ::= \"Step \" [0-9]?[0-9] \". \" \"Determine Information-Rich Areas:\" [^\\n]+ \"\\n\"\n\nbrainstorm-step ::= \"Step \" [0-9]?[0-9] \". \" \"Brainstorm and Develop Questions Testing Recall:\" [^\\n]+ \"\\n\"\n\nrelationships-step ::= \"Step \" [0-9]?[0-9] \". \" \"Devise Questions\" [^\\n]+ \"\\n\"\n\nif-then-step ::= \"Step \" [0-9]?[0-9] \". \" \"Create Questions Investigating\" [^\\n]+ \"\\n\"\n\nmake-suitable-step ::= \"Step \" [0-9]?[0-9] \". \" \"Make a Question that Naturally Complements the Text's Focus:\" [^\\n]+ \"\\n\"\n\n\"\"\"\n)\n\n\n# Realize\n# Devise\n# Recall\n# Note that\n# The text states that\n# The text says\n# The text\n# Formulate\n# Brainstorm\n# See if\n# See whether\n# Determine\n# No such questions\n# There are\n# I have brainstormed\n# End of reasoning","source_hash":"a5f13f20043880020ee90f9fff37e5cd441bfb8ca9bfe9e62683b12a84111865","truncated":false} {"repo_id":"augmentoolkit","entity_id":"py:generation_functions.proofread_output_grammar","uri":"program://augmentoolkit/module/generation_functions.proofread_output_grammar#L1-L17","kind":"module","name":"generation_functions.proofread_output_grammar","path":"generation_functions/proofread_output_grammar.py","language":"python","start_line":1,"end_line":17,"context_start_line":1,"context_end_line":17,"code":"from llama_cpp import LlamaGrammar\n\nproofread_output_grammar = LlamaGrammar.from_string(\n r\"\"\" \n \nroot ::= analyze-step step+ \"\\n\\nBegin Edit: \" [^\\n]+\n\nstep ::= \"Step \" [0-9]?[0-9] \". \" ( \"Analyze\" | \"Understand\" | \"Compare\" | \"Skip\" | \"Notice\" | \"Note\" | \"There is\" | \"Error\" | \"I found\" | \"End\" | \"There are\" ) [^\\n]+ \"\\n\"\n\nanalyze-step ::= \"Step \" [0-9]?[0-9] \". \" \"Analyze\" [^\\n]+ \"\\n\"\n\"\"\"\n)\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"d711be32188f6d49bc8a69ac161347ec64d5c393ab08eaa9c0fc161a8f504d70","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:convert_pdf_to_text.py","uri":"program://augmentoolkit/file/convert_pdf_to_text.py","kind":"file","name":"convert_pdf_to_text.py","path":"convert_pdf_to_text.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# Written by GPT-4\nimport fitz # PyMuPDF\nimport pytesseract\nfrom PIL import Image\nimport io\n\n# Ensure the path to the tesseract executable is set if it's not in your PATH\n# pytesseract.pytesseract.tesseract_cmd = r''\n\n\ndef convert_pdf_to_text(pdf_path, output_txt_path):\n # Open the PDF file\n document = fitz.open(pdf_path)\n\n text = \"\" # Initialize a text string to hold all text from the PDF\n\n for page_num in range(len(document)):\n # Get the page\n page = document.load_page(page_num)\n\n # First, try to extract text using PyMuPDF","source_hash":"7518e848fe93d66b5969a43aa7da5f38cd0aaad00ca52b5d0d719a6f4c3d8b08","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/constants.py","uri":"program://augmentoolkit/file/generation_functions/constants.py","kind":"file","name":"generation_functions/constants.py","path":"generation_functions/constants.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"RP_MODEL = \"./rp_model\" # model used for RP tasks, probably going to use Sao10K/Euryale-1.3-L2-70b\n# LOGICAL_MODEL = \"./logical_model/airoboros-l2-13b-3.1.1.Q8_0.gguf\" # model used for decision-making and base question generation (should be \"smart\")\n\nLOGICAL_MODEL = \"./logical_model/flatorcamaid-13b-v0.2.Q8_0.gguf\" # model used for decision-making and base question generation (should be \"smart\")\n\nnames = [ # Replaces \"Albert\" in scenarios. Needs to be western male names to avoid pronoun and setting inconsistencies).\n \"William\",\n \"James\",\n \"John\",\n \"Robert\",\n \"Michael\",\n \"Charles\",\n \"George\",\n \"Joseph\",\n \"Edward\",\n \"Henry\",\n \"Thomas\",\n \"David\",\n \"Richard\",\n \"Daniel\",\n \"Matthew\",","source_hash":"5f7f01bffe335fe887269d055e158f7918b547c101dfd50407cf91ff4edc8217","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/format_qatuples.py","uri":"program://augmentoolkit/file/generation_functions/format_qatuples.py","kind":"file","name":"generation_functions/format_qatuples.py","path":"generation_functions/format_qatuples.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":15,"code":"def format_qatuples(qatuples):\n strlst = []\n for qatuple in qatuples:\n strlst.append(\n f\"\"\"Question: \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\nAnswer: \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\"\"\"\n )\n return \"\\n\\n\".join(strlst)\n\n\ndef format_qatuples_noquotes(qatuples):\n strlst = []\n for idx, qatuple in enumerate(qatuples):\n strlst.append(f\"\"\"{idx + 1}. {qatuple[0]}\"\"\")\n return \"\\n\".join(strlst)","source_hash":"7139221b2092ee811bfbe7af5abe36564b85400b8552406476da2fe4e1442929","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/check_answer.py","uri":"program://augmentoolkit/file/generation_functions/check_answer.py","kind":"file","name":"generation_functions/check_answer.py","path":"generation_functions/check_answer.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .answer_accurate_grammar import answer_accurate_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# Answer vetting\n\n\ndef check_answer(qatuple, logic_llm, permissive_mode=True):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Given a paragraph or two from a larger text, a question based on the paragraphs, and an answer to the question, you will make a determination as to whether the answer to the question is a sensible answer, given the information in the paragraphs. Essentially: you will fact-check the answer to the question, with your source of truth being the paragraphs provided. Your task includes first analyzing the text, thinking through whether or not the answer reflects aspects of the paragraphs provided. \n\nFollowing this, at the very end of your response, you will write \"Accurate\" or \"Inaccurate\" depending on your analysis of the answer with regards to the text. \n\nRemember that at the very end of your response, you will write \"Accurate\" or \"Inaccurate\". Do not use these words anywhere else in your answer.\n\n### Instruction:\nText: \n\\\"\\\"\\\"\nThe Industrial Revolution marked a transformative period in history, fundamentally altering economic structures and industrial processes. One of the most significant innovations was the advent of steam power, which drastically reduced production costs. This reduction was due to the increased efficiency and speed of machines powered by steam, replacing the slower, more labor-intensive methods previously used. Additionally, steam power was instrumental in the development of semi-automated factories, leading to a significant shift in manufacturing processes and labor dynamics.","source_hash":"bf068231d30487c773c67639aba8b332cc76cc42fe86c349fb6d22756fc3fb2b","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/ensure_multiple_answers_consistent_grammar.py","uri":"program://augmentoolkit/file/generation_functions/ensure_multiple_answers_consistent_grammar.py","kind":"file","name":"generation_functions/ensure_multiple_answers_consistent_grammar.py","path":"generation_functions/ensure_multiple_answers_consistent_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\nensure_multiple_answers_consistent_grammar = LlamaGrammar.from_string(\n r\"\"\" \n \n# Root rule to define the overall structure\nroot ::= sequential-matching-section accuracy-check-section conclusion-section\n\n# Section for sequential matching\nsequential-matching-section ::= \"## Sequential Matching of Questions in the Conversation:\\n### Sequence and Phrasing of Questions:\\n\" matching-statement+\n\n# Section for accuracy check\naccuracy-check-section ::= \"## Accuracy Check for Answers in the Conversation:\\n### Matching Answers with Provided Content:\\n\" accuracy-statement+\n\n# Conclusion section\nconclusion-section ::= \"## Conclusion:\\n\" conclusion-statement+\n\n# Definitions of different components\nnumber ::= [1-9]\nmatching-statement ::= number \". \" [^\\n]+ \"\\n\"\naccuracy-statement ::= number \". \" [^\\n]+ \"\\n\"","source_hash":"47bcf27dd005d35193c4603a52bc1209cf02ed0190232382077642a81801a3a0","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/create_character_card_plan_grammar.py","uri":"program://augmentoolkit/file/generation_functions/create_character_card_plan_grammar.py","kind":"file","name":"generation_functions/create_character_card_plan_grammar.py","path":"generation_functions/create_character_card_plan_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\ncharacter_card_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Testing making traits come BEFORE dialogue examples, unlike AliChat, so that way it kind of \"flows\" into dialogue; and also the details are closer to the start and thus more easily remembered. \n\n\n\n\n\nroot ::= [^\\n]+ \"\\n\"\n\n\n# root ::= consider-step theme-step consistency-step \"\\n\"\n\n# consider-step ::= \"Step 1. \" \"Consider the provided\" [^\\n]+ \"\\n\"\n\n# theme-step ::= \"Step 2. \" \"Given the question, answer, and overall text, a theme for \" [^\\n]+ \"\\n\"","source_hash":"e80c32307ca9c8f5b1e7a7a880717dd24c286d25754cc281d53e63dc93a951fa","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/identify_duplicates.py","uri":"program://augmentoolkit/file/generation_functions/identify_duplicates.py","kind":"file","name":"generation_functions/identify_duplicates.py","path":"generation_functions/identify_duplicates.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from typing import List, Tuple\nfrom .process_multiturn_functions import has_sequential_chars\n\n# If you want to check for matching substrings anywhere, not just at start, use this code (untested)\n# def identify_duplicates(tuples: List[Tuple[str, str, str, str]]) -> List[Tuple[str, str, str, str]]:\n# # Create a dictionary to hold questions with the same first N characters\n# question_dict = {}\n\n# # Iterate through each tuple and categorize them by the first N characters of the question\n# for q_tuple in tuples:\n# question = q_tuple[0]\n# placed = False\n# for dict_q in question_dict.keys():\n# if has_sequential_chars(question,dict_q,N_CHARACTERS_SAME):\n# question_dict[dict_q].append(q_tuple)\n# placed = True\n# break\n# if not placed:\n# question_dict[question] = [q_tuple] # if not found to be equivalent with anything, make it a dict entry so that things can be compared against it and added to its list\n\n# # Filter out prefixes that only have one question associated","source_hash":"b26ea9c99c573b871b7b134cc1cde33326931181f1850f7c07e0a46c6e5ec470","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/create_scenario_many_tuples.py","uri":"program://augmentoolkit/file/generation_functions/create_scenario_many_tuples.py","kind":"file","name":"generation_functions/create_scenario_many_tuples.py","path":"generation_functions/create_scenario_many_tuples.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .scenario_grammar import scenario_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nimport random\nfrom .format_qatuples import format_qatuples\nfrom .extract_name import extract_name\nfrom .random_name import random_name\n\n\n# Consider adding a scenario for Issac here, since currently both characters are in positions of authority, and the thing leans very heavily on Hugo's example\n# NOTE the message count is technically off by one in the reasoning, but I'm a bit scared to change it.\ndef create_scenario_many_tuples(\n qatuples, character, plan, logic_llm, assistant_mode=False\n):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n if assistant_mode:","source_hash":"08ea1b85ccce3b4f73518823e3218b0d7e58c64623527a90424f08574e026cc6","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/make_regenerate_question_plan.py","uri":"program://augmentoolkit/file/generation_functions/make_regenerate_question_plan.py","kind":"file","name":"generation_functions/make_regenerate_question_plan.py","path":"generation_functions/make_regenerate_question_plan.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .make_regenerate_question_plan_grammar import make_regenerate_question_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n# Question regeneration (triggered after a relevance-check fails on the question).\n\n\n# NOTE does not explicitly guard against duplicates. I am avoiding that right now due to the limited drawback of a duplicate or two, and the increased complexity of adding that check.\ndef make_regenerate_question_plan(qatuple, dissenting_reasoning, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. Someone has written a question that was supposed to be based on the provided paragraphs of text, but actually requires significant knowledge outside these paragraphs to answer. Your goal is to write a good, comprehensive plan for generating a revised question that addresses the criticism given. Given these paragraphs, the flawed question based on the paragraphs, and the explanation of why the question is flawed, you will PLAN OUT and THINK THROUGH different possibilities for a new question, one which will only require information from the paragraphs to solve. \n\nParagraphs: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nFlawed question (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nReasoning as to why the question is irrelevant: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n","source_hash":"a167ec46648a203fbe972c744c453a403ea860b113082444e17958d1affc7aad","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/check_qatuple_context_grammar.py","uri":"program://augmentoolkit/file/generation_functions/check_qatuple_context_grammar.py","kind":"file","name":"generation_functions/check_qatuple_context_grammar.py","path":"generation_functions/check_qatuple_context_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n\n# We don't actually need the final judgement step, the step-by-step combined with the fact that it makes a judgement at each step ensures accuracy\ncheck_qatuple_context_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Root rule specifying the overall structure of the reasoning and thought process\nroot ::= question-validation \"\\n\" answer-validation \"\\n\" critical-evaluation \"\\n\" revised-qatuple\n\n# Question context validation\nquestion-validation ::= \"### Question Context Validation\" \"\\n\" special-term-check-question text-and-author-specificity scope-and-precision\n\nspecial-term-check-question ::= \"#### Special Term Context Check: Specifically check for use of the terms \\\"book\\\", \\\"text\\\", \\\"passage\\\", and \\\"excerpt\\\" without context about which specific thing is being discussed. \" question-term-detail \"\\n\"\ntext-and-author-specificity ::= \"#### Text and Author Specificity: \" question-text-author-detail \"\\n\"\nscope-and-precision ::= \"#### Scope and Precision: \" question-scope-detail \"\\n\"\n\n# Answer context validation\nanswer-validation ::= \"### Answer Context Validation:\" \"\\n\" special-term-check-answer specificity-and-clarity answer-only-context-issues","source_hash":"f553dcfdeac26077c860e62795bffa5814e18d09bb9376337d2f0aa56350f6a5","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/question_relevant_grammar copy.py","uri":"program://augmentoolkit/file/generation_functions/question_relevant_grammar copy.py","kind":"file","name":"generation_functions/question_relevant_grammar copy.py","path":"generation_functions/question_relevant_grammar copy.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n\n# We don't actually need the final judgement step, the step-by-step combined with the fact that it makes a judgement at each step ensures accuracy\nquestion_relevant_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n \nroot ::= step step step+ \"\\n\"\n\nreasoning-start ::= [^\\n\\t]+ \".\"\n\nstep ::= \"Step \" [0-9]?[0-9] \". \" ( \"Analyze\" | \"Understand\" | \"Compare\" | \"Skip\" | \"Final\" ) [^\\n]+ \"\\n\"\n \n# final-step ::= \"Final Judgement: [^\\n]+ (relevant|irrelevant) \" \".\" \n \n# root ::= reasoning from-the-text judgement\n\n# reasoning ::= \"First, I will check whether the question is answerable using the information in the paragraphs. The question asks \" [^\\n]+ \".\"","source_hash":"0dd97c7433ccd84901849a7eb288ff2704e4f8e8208e8fa9bbf85374eb8d26dc","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/create_scenario_plan.py","uri":"program://augmentoolkit/file/generation_functions/create_scenario_plan.py","kind":"file","name":"generation_functions/create_scenario_plan.py","path":"generation_functions/create_scenario_plan.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .scenario_plan_grammar import scenario_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef create_scenario_plan(qatuple, character, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # removing the text makes this much better\n\n # The problem: because the scenario plan differed slightly, the question differed slightly. Because the question differed slightly, the answer differed slightly. Because the answer differed slightly, the answer was incomplete.\n if assistant_mode:\n return \"\"\"\"\"\"\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. Given a question, an answer to that question, and a \"character card\" -- a description of an individual who would have the knowledge to produce the answer to the question -- you will plan out a \"scenario\" or setting where the character would answer the question during a conversation with someone else. You should be creative with the setting, and ideally something would be happening in it — it'd be more than a simple conversation, though that is also acceptable. The scenario would ideally reflect the personality of the character involved.\n\nThe scenario should also, critically, focus on the question being asked and then answered. It should focus on exploring the question and its answer (using only information contained in the question and answer) through the characters involved, instead of the other way around. ","source_hash":"fb9c70e4200fd1f197b79d5e0efb37ad1a197668feac28f970905777a5a59265","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/extract_name.py","uri":"program://augmentoolkit/file/generation_functions/extract_name.py","kind":"file","name":"generation_functions/extract_name.py","path":"generation_functions/extract_name.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":16,"code":"import re\n\n\ndef extract_name(str):\n # Regular expression to match 'Name:' followed by any characters until the end of the line\n name_regex = r\"^Name:\\s*(.*)$\"\n\n # Searching in the multiline string\n match = re.search(name_regex, str, re.MULTILINE)\n\n if match:\n name = match.group(1)\n print(f\"Extracted name: {name}\")\n return name\n else:\n print(\"No name found\")","source_hash":"61574b4115cd84e4f44a8faa7c2baa035b8171a417bc6056384a9b94bebfbfd8","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/create_thought_plan_many_tuples.py","uri":"program://augmentoolkit/file/generation_functions/create_thought_plan_many_tuples.py","kind":"file","name":"generation_functions/create_thought_plan_many_tuples.py","path":"generation_functions/create_thought_plan_many_tuples.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from .thought_plan_grammar import thought_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .create_thought_plan import create_thought_plan\nfrom .extract_name import extract_name\n\n\ndef create_thought_plan_many_tuples(qatuples, character, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # use regex to extract charname\n charname = extract_name(character)\n thought_plans = []\n for tuple in qatuples:\n thought_plans.append(create_thought_plan(tuple, character, logic_llm))\n\n ret = \"\"","source_hash":"bc3bfdf914c54be38fcdad8c62344fa6ace1943dd451f2feaad9eaf1da26570f","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/answer_accurate_grammar.py","uri":"program://augmentoolkit/file/generation_functions/answer_accurate_grammar.py","kind":"file","name":"generation_functions/answer_accurate_grammar.py","path":"generation_functions/answer_accurate_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n# NOTE might struggle with very complex answers that have more than nine parts to them. This can be amended by adding more options to the \"compare-step\" rule, or making a more general pattern, if your use-case requires it.\n\nanswer_accurate_grammar = LlamaGrammar.from_string(\n r\"\"\" \n \n \n# Root rule specifying the overall structure of the analysis\nroot ::= text-analysis answer-breakdown accuracy-check final-judgment\n\n# Text analysis\ntext-analysis ::= \"### Text Analysis:\" \"\\n\" identify-key-info categorize-info-type\n\nidentify-key-info ::= \"#### Identify Key Information: \" text-info-detail \"\\n\"\ncategorize-info-type ::= \"#### Categorize Information Type: \" info-type-detail \"\\n\\n\"\n\n# Answer breakdown\nanswer-breakdown ::= \"### Answer Breakdown:\" \"\\n\" dissect-answer identify-answer-type\n\ndissect-answer ::= \"#### Dissect the Answer: \" answer-detail \"\\n\"","source_hash":"b64d07e1da1f5d212774a1d017b1a57ac5ea6e082b6a85e1ff009b2883e6892b","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/identify_duplicates_grammar.py","uri":"program://augmentoolkit/file/generation_functions/identify_duplicates_grammar.py","kind":"file","name":"generation_functions/identify_duplicates_grammar.py","path":"generation_functions/identify_duplicates_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n\n# We don't actually need the final judgement step, the step-by-step combined with the fact that it makes a judgement at each step ensures accuracy\nidentify_duplicates_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Root rule defining the overall structure of the response\nroot ::= normalization-block core-components-block comparative-analysis-block criteria-block conclusion-block\n\n# Normalization of Questions\nnormalization-block ::= \"## Normalization of Questions:\\n\" normalized-question+\nnormalized-question ::= \"- \\\"\" content \"\\\"\\n - Normalized: \" content \"\\n\"\n\n# Identification of Core Components\ncore-components-block ::= \"## Identification of Core Components:\\n### Subject Matter:\\n\" subject-matter+ \"### Information Sought:\\n\" information-sought+\nsubject-matter ::= \"- Question \" digit+ \": \" content \"\\n\"\ninformation-sought ::= \"- Question \" digit+ \": \" content \"\\n\"\n","source_hash":"8836a6c5a0a6ec419982315ad75f64669d90662c127b2a3f15da456928f48459","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/regenerate_question_noplan.py","uri":"program://augmentoolkit/file/generation_functions/regenerate_question_noplan.py","kind":"file","name":"generation_functions/regenerate_question_noplan.py","path":"generation_functions/regenerate_question_noplan.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .question_grammar import question_grammar\nfrom .strip_steps import strip_steps\n\n\n# Question regeneration (triggered after a relevance-check fails on the question).\ndef regenerate_question_DEPRECATED(qatuple, dissenting_reasoning, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. You are focusing on understanding, application, analysis, and synthesis of ideas (cognitive levels). Someone has written a question that was supposed to be based on the provided paragraphs of text, but actually requires significant knowledge outside these paragraphs to answer. Given these paragraphs, the flawed question based on the paragraphs, and the explanation of why the answer is flawed, you will write out a new question that only requires information from the paragraphs to solve. However, you will not explicitly refer to the paragraphs in the question; the student will not have access to the text when answering it.\n \nSo, in short, your task is to rewrite a new question that is actually answerable if one knows the concepts from the paragraphs.\n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nReasoning as to why the question is irrelevant: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nDo not explicitly mention the paragraphs in your question itself — just ask about the concepts, and only those concepts which appear in the text.\n","source_hash":"41bf11a6b16be5c7f284c0691ac23e24e2a93de33cdc2b843a1e4c36a45f460e","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/create_character_card_many_tuples.py","uri":"program://augmentoolkit/file/generation_functions/create_character_card_many_tuples.py","kind":"file","name":"generation_functions/create_character_card_many_tuples.py","path":"generation_functions/create_character_card_many_tuples.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .character_card_grammar import character_card_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nimport string\nimport random\n\n\ndef extract_author_name(title):\n pattern = re.compile(r\"\\b(?:by|By)\\s+([^,]+),\")\n match = re.search(pattern, title)\n if match:\n author_name = match.group(1)\n else:\n author_name = [False]\n return author_name[0] # first letter of Author name\n\n\ndef select_random_capital(exclusions):\n # Create a list of capital letters excluding the ones in the exclusions list","source_hash":"d6e6faea33c0b22f0193434724feaf8204e49123f107f406110fd91f1996c40f","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/create_character_card.py","uri":"program://augmentoolkit/file/generation_functions/create_character_card.py","kind":"file","name":"generation_functions/create_character_card.py","path":"generation_functions/create_character_card.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .character_card_grammar import character_card_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .special_instructions import special_instructions\n\n\ndef create_character_card(qatuple, plan, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # WIP\n instructions_string = special_instructions()\n\n if assistant_mode:\n return \"\"\"Name: AI Assistant\n\nTraits: Knowledgeable, Logical, Neutral, Patient, Consistent, Detail-Oriented, Informative, Adaptive, Curious, Efficient, Non-Judgmental, Unbiased, Responsive","source_hash":"59f4425226d80791c6f8d9a043ce0a2bd0a57c99a2dcf0a079e0295a4e4942ff","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/ensure_multiple_answers_consistent.py","uri":"program://augmentoolkit/file/generation_functions/ensure_multiple_answers_consistent.py","kind":"file","name":"generation_functions/ensure_multiple_answers_consistent.py","path":"generation_functions/ensure_multiple_answers_consistent.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .ensure_multiple_answers_consistent_grammar import (\n ensure_multiple_answers_consistent_grammar,\n)\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nfrom .extract_name import extract_name\n\n# Answer vetting\n# For now, this checks answer relevancy too. The danger with abstracting answer relevancy into a separate step is that anything which relies on knowledge that is obviously mentioned in the text already up until this point, will get screwed\n\n\n# NOTE this prompt right now VERY MUCH struggles to follow its actual format; but it still mostly works\ndef ensure_multiple_answers_consistent(qatuples, conv, logic_llm, permissive_mode=True):\n \"\"\"\n permissive_mode: turn off if you want a single usage of the word \"inconsistent\" anywhere in the message to flag the whole thing as inconsistent. Prevents errors where an inconsistency happens way early in the answer, but the model forgets about it during its final judgement; but enables the error where the model mentions that something is \"not entirely inconsistent\" or similar, which is surprisingly common.\n \"\"\"\n retries = 0\n character_name = extract_name(conv[1])\n # It's expensive to regen a conversation; so we check very thoroughly, and use a two-shot example. \"Permissive mode\" recommended","source_hash":"5522eca47999a576b817f1a942040000e403032104a295e0f8ee7ec33001f705","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/is_this_sane.py","uri":"program://augmentoolkit/file/generation_functions/is_this_sane.py","kind":"file","name":"generation_functions/is_this_sane.py","path":"generation_functions/is_this_sane.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .proofread_output_grammar import proofread_output_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# But frankly, I can just use that text fixer thing rather than using an LLM. MUCH faster that. ftfy I believe it was called.\n\n\n# This does actually work decently though!\ndef proofread_output(text, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n prompt = f\"\"\"You are specialized in detecting strange and broken outputs from large language models, and you will be judging whether or not some output is broken. You will be provided some text that is the output of a model. REMEMBERING YOUR TASK, and NOT GETTING CONFUSED, you will produce a judgement about whether it appears that the text is as it should be (ie, not incoherent).\n\nSigns of a broken response include:\nChunks of repeating text.\nInstructions or prompt pieces appearing in the text.","source_hash":"b41e5570d3d3e5ad7488fe002bd0bb92fe9f931c08559fcebd28a74c44c903f5","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/answer_constrain_to_text_plan_grammar.py","uri":"program://augmentoolkit/file/generation_functions/answer_constrain_to_text_plan_grammar.py","kind":"file","name":"generation_functions/answer_constrain_to_text_plan_grammar.py","path":"generation_functions/answer_constrain_to_text_plan_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\nanswer_constrain_to_text_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \nroot ::= analyze-step understand-step identify-step plan-revised-step \"\\n\"\n\n# step ::= \"Step \" [0-9]?[0-9] \". \" ( \"Analyze\" | \"Understand\" | \"Compare\" | \"Final\" | \"Plan\" | \"Identify\" ) [^\\n]+ \"\\n\"\n\nanalyze-step ::= \"Step \" [0-9]?[0-9] \". \" \"Analyze the Text:\" [^\\n]+ \"\\n\"\n\nunderstand-step ::= \"Step \" [0-9]?[0-9] \". \" \"Understand the Question:\" [^\\n]+ \"\\n\"\n\nidentify-step ::= \"Step \" [0-9]?[0-9] \". \" \"Identify Flawed Part of the Answer:\" [^\\n]+ \"\\n\"\n\nplan-revised-step ::= \"Step \" [0-9]?[0-9] \". \" \"Plan Revised Answer:\" [^\\n]+ \"\\n\"\n\"\"\"\n)\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer","source_hash":"0010badc09362427d6168cbf2263d495ffe32a37783357e988481169e0403827","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/question_grammar.py","uri":"program://augmentoolkit/file/generation_functions/question_grammar.py","kind":"file","name":"generation_functions/question_grammar.py","path":"generation_functions/question_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\nquestion_grammar = LlamaGrammar.from_string(\n r\"\"\"\nroot ::= (question-one answer \"\\n\")\n\n# Define the question structure with a number followed by content and ending punctuation\n# question ::= number \".) \" [^\\n]+ [?.!] \"\\n\" # maybe blacklist ?!. along with newlines\n\n# Define the answer structure\nanswer ::= \"Answer: \" [^\\n]+ \"\\n\"\n\n# Define a number (in this case, limiting to any three-digit number for simplicity)\nnumber ::= [1-9] [0-9]? [0-9]?\n\n# Define content as a sequence of characters excluding the word \"paragraph\" and using not_paragraph to build up the content\n# content ::= (not-paragraph \"paragraph\")* #not_paragraph\n\n\nquestion-one ::= \"1.) \" [^\\n]+ [?.!] \"\\n\" # maybe blacklist ?!. along with newlines\n# ws ::= [ \\t\\n]*","source_hash":"4e8963aa6e64bad70117c99d48e7b477993724db97a511156d09599bc192d1fe","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/generate_questions.py","uri":"program://augmentoolkit/file/generation_functions/generate_questions.py","kind":"file","name":"generation_functions/generate_questions.py","path":"generation_functions/generate_questions.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\n\n# try:\nfrom .questions_grammar import questions_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n\ndef generate_questions(para_tuple, plan, logic_llm):\n \"\"\"\n Produce a list of questions based off of an input text. The min between (4, as many good questions as the text permits)\n\n Format: Question: [question]\\n\\n\n \"\"\"\n # Determine which paragraphs are worthy of making questions from\n made_questions = False\n retries = 0\n questions = []\n while not made_questions and (retries <= 5):\n question_prompt = f\"\"\"You are an expert educational AI that, given a paragraph or two from a text, will create suitable educational questions based on the paragraphs, and *only* based on the paragraphs. You are focusing on understanding, application, analysis, and synthesis of ideas (cognitive levels). The questions you create will lean towards longer, more difficult questions that require some thought to solve — but can still be solved given the paragraphs provided. Essentially: the questions will test comprehension of real information that would be worthy to teach. After the question, you will also write its answer.","source_hash":"a4ab7d0e424fee307d04f58ab9c67e30c2b2dfc395c4b8bdf9814d80c36a6a5f","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/make_regenerate_answer_plan.py","uri":"program://augmentoolkit/file/generation_functions/make_regenerate_answer_plan.py","kind":"file","name":"generation_functions/make_regenerate_answer_plan.py","path":"generation_functions/make_regenerate_answer_plan.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .make_regenerate_answer_plan_grammar import make_regenerate_answer_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n\n# Question regeneration (triggered after a relevance-check fails on the question).\ndef make_regenerate_answer_plan(qatuple, dissenting_reasoning, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. Someone has provided an answer to a question based on a few paragraphs of text, but the answer may be incorrect due to contradicting the text or including erroneous information. Your task is to plan out and think through a correct answer to the question, ensuring it aligns with the information provided in the text.\n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nAllegedly incorrect answer to the question (for fact-checking): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nReasoning as to why the answer is incorrect: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n","source_hash":"0677e1dbb0e66c7bff8690e63198df74a53a5f2c4e4ae27ea7af1d7fd5439250","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/regenerate_answer_grammar.py","uri":"program://augmentoolkit/file/generation_functions/regenerate_answer_grammar.py","kind":"file","name":"generation_functions/regenerate_answer_grammar.py","path":"generation_functions/regenerate_answer_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":12,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\nregenerate_answer_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \nroot ::= reasoning\n\nreasoning ::= [^\\n]+ \".\"\n\"\"\"\n)","source_hash":"5cefb2c45ad6fc314481ccb86389b30db5e6bf746bf35a475601fc22eb0ba723","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/proofread_output.py","uri":"program://augmentoolkit/file/generation_functions/proofread_output.py","kind":"file","name":"generation_functions/proofread_output.py","path":"generation_functions/proofread_output.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .proofread_output_grammar import proofread_output_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# But frankly, I can just use that text fixer thing rather than using an LLM. MUCH faster that. ftfy I believe it was called.\n\n\n# This does actually work decently though!\ndef proofread_output(text, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n prompt = f\"\"\"You are an expert \"mechanical editing\" AI that is going to fix all typographical, grammatical, and spelling errors in a provided text, without making any other corrections. You will leave stylistic choices and everything else completely unchanged.\n\nText to edit: \\\"\\\"\\\"{text}\\\"\\\"\\\"\n\nFirst, plan out your edit, step-by-step, identifying mistakes in the source text. Then, make the edit, changing only mechanical errors.","source_hash":"d97a5588a19db379864fda57d768076ce823a45f263a9ed6b39b4d599497fbb3","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/judge_paragraph.py","uri":"program://augmentoolkit/file/generation_functions/judge_paragraph.py","kind":"file","name":"generation_functions/judge_paragraph.py","path":"generation_functions/judge_paragraph.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .judge_paragraph_grammar import judge_paragraph_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef judge_paragraph(p, logic_llm):\n reached_decision = False\n max_retries = 0\n while not reached_decision and (max_retries <= 3):\n decision_prompt = f\"\"\"You are an expert educational AI that will make a determination as to whether the contents of the paragraph(s) provided are suitable for making educational questions based off of them; these questions should be able to test the knowledge in in the book. The book in question is {p[1]}, and you should keep this in mind when considering what kind of questions should be capable of being developed. If there is sufficiently deep information to make questions about, you will judge it suitable, even if the knowledge being tested does not reflect typical curricula. Essentially: you will determine if provided text is a table of contents, introductory paragraph for a book, etc., or if it actually contains real information that would be worthy to teach and make questions for an examination from. Your task includes first analyzing the text, thinking through whether or not good questions can be made from it. \n\n\n\nFollowing this, at the very end of your response, you will write \"Suitable\" or \"Not suitable\". It is imperative that you write one of these two things, as your answer is being automatically processed by a regex, so it must match one of those two strings exactly.\n\n\n### Instruction:\nText details: Through England On a Side Saddle, by Celia Fiennes\n\nText: ","source_hash":"8af5ce96c416e22b0d2ca613132f244ec04814da465519fb8d431183195ce67c","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/thought_plan_grammar.py","uri":"program://augmentoolkit/file/generation_functions/thought_plan_grammar.py","kind":"file","name":"generation_functions/thought_plan_grammar.py","path":"generation_functions/thought_plan_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n\n# A GGBNF grammar that forces the model to output text in a particular format\nthought_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Root rule defining the overall structure\nroot ::= step+ \"\\n\"\n\n# Step rule with some text (any characters except newline) followed by a period\nstep ::= \"Step \" [0-9]?[0-9] \". \" (\"Realize\" | \"Recognize\" | \"Conclude\" | \"Recall\" | \"Remember\" | \"Formulate\" | \"Decompose\" | \"Break down\" | \"Break\" | \"Therefore, the answer is\" | \"The answer is\" | \"Realise\" | \"Calculate\" | \"Understand\" | \"Note\" | \"The plan will\") [^\\n]+ \"\\n\"\n\n# Potential way forward: change these reasoning steps to use \n# step ::= \"Step \" [0-9]?[0-9] \". \" (\"Realize\" | \"Recall\" | \"Remember\" | \"Formulate\" | \"Decompose\" | \"Break down\" | \"Break\" | \"Therefore, the answer is\" | \"The answer is\" | \"Realise\" | \"Calculate\" | \"Understand\" | \"Note\" | \"The plan will\") [^\\n]+ \"\\n\"\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n","source_hash":"c9a1204d996c8648d9371623f84cf10272109dac44d544b5069642af9f3e0840","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/generate_questions_plan.py","uri":"program://augmentoolkit/file/generation_functions/generate_questions_plan.py","kind":"file","name":"generation_functions/generate_questions_plan.py","path":"generation_functions/generate_questions_plan.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .question_plan_grammar import question_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef generate_questions_plan(text, logic_llm):\n \"\"\"\n Produce a list of questions based off of an input text. The min between (4, as many good questions as the text permits)\n\n Format: Question: [question]\\n\\n\n \"\"\"\n # Determine which paragraphs are worthy of making questions from\n # Analyze-Realize-Create-Example loop\n cot_prompt = f\"\"\"As an educational AI specializing in question generation, your task is to plan out high-quality, critical thinking questions strictly based on provided paragraphs. Focus on understanding, application, analysis, and synthesis of the text's ideas. Develop a comprehensive plan to generate questions that test comprehension and memorization of explicit content in the paragraphs. Aim for longer, challenging questions that can be answered with the given information.\n\nEnsure your questions strictly adhere to the text's content, avoiding any external topics. The key step is to analyze the text thoroughly and brainstorm potential questions based on this analysis. Do not list final questions in this step.\n\nYour response should be concise, focusing solely on the text's content to test knowledge without the text's reference. Maintain a step-by-step reasoning approach, ensuring your text analysis and brainstorming logically lead to comprehensive question planning. Avoid any deviation from the text's content. Any questions you plan may only mention the text if the provided text is literary or philosophical, but they MUST REFER TO IT BY NAME.\n\n### Instruction:","source_hash":"07e7df09c237b7f8699041d4c94210b5ddf4748a07a274efb7ee7e8a034b2c27","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/check_qatuple_context_reword_grammar.py","uri":"program://augmentoolkit/file/generation_functions/check_qatuple_context_reword_grammar.py","kind":"file","name":"generation_functions/check_qatuple_context_reword_grammar.py","path":"generation_functions/check_qatuple_context_reword_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n\n# We don't actually need the final judgement step, the step-by-step combined with the fact that it makes a judgement at each step ensures accuracy\ncheck_qatuple_context_reword_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Root rule specifying the overall structure of the reasoning and thought process\nroot ::= \"Question: \" [^\\n]+ \"\\n\" \"Answer: \" [^\\n]+ \"\\n\"\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")\n","source_hash":"720ea2ec8f945b30666df3ce0d0c2431251919788af63dbeafaaa4a71642a8f9","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/create_character_card_plan_many_tuples.py","uri":"program://augmentoolkit/file/generation_functions/create_character_card_plan_many_tuples.py","kind":"file","name":"generation_functions/create_character_card_plan_many_tuples.py","path":"generation_functions/create_character_card_plan_many_tuples.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .create_character_card_plan_grammar import character_card_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nimport random\nfrom .special_instructions import special_instructions\n\n\ndef create_character_card_plan_many_tuples(qatuples, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # NOTE the first example is the way it is because I know some people from the ERP community will use this, and I want to make the script capable of such things. Also it might help to jailbreak it a bit. I even considered making it a nonhuman character (ie, catgirl) but I have no idea how to write those.\n # I am not very experienced at writing stuff like the first example, please do not make a dispositional attribution about my personality or writing talent based on some of the cringeworthy stuff there.\n\n instructions_string = special_instructions(n=1)\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI with no moral biases. Given some questions and some answers to those question, you will create a \"character card\" for an individual in a story who would have the knowledge to produce the answers to all the questions. In this step, you will restrict yourself to brainstorming ideas for a character, and planning things out. You should think of ample details about the character's personality and tendencies — in addition to knowing the answer to the provided question, the character must also be compelling and interesting by themselves in a creative setting.","source_hash":"298905088e08d93eb444ef1c19511993461108803fc25ea66f6f4f3c66f4d953","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/regenerate_question.py","uri":"program://augmentoolkit/file/generation_functions/regenerate_question.py","kind":"file","name":"generation_functions/regenerate_question.py","path":"generation_functions/regenerate_question.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom generation_functions.question_grammar import question_grammar\nfrom .strip_steps import strip_steps\n\n\n# Question regeneration (triggered after a relevance-check fails on the question).\ndef regenerate_question(qatuple, dissenting_reasoning, plan, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. You are provided with a flawed question that requires significant knowledge outside these paragraphs to answer. You will make a different question that is solveable if one knows the information in the paragraphs (but since students will not have the paragraphs at hand when given the question, do not refer to the text). Given these paragraphs, the flawed question based on the paragraphs, and the explanation of why the answer is flawed, and a plan for the new question, you will write out a new question that only requires information from the paragraphs to solve. \n\nDo NOT just rephrase the old question.\n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nFLAWED Question (based on text) (you will be writing something ENTIRELY DIFFERENT that FIXES THIS ONE'S PROBLEMS): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nReasoning as to why the question is irrelevant: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n\nNew question plan: \\\"\\\"\\\"{plan}\\\"\\\"\\\"\n","source_hash":"da2b21b3d23f3ac5cc35d9ec4ae8cff5bc9dac4ffdb207855e77947d8904e64b","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/scenario_plan_many_tuples_grammar.py","uri":"program://augmentoolkit/file/generation_functions/scenario_plan_many_tuples_grammar.py","kind":"file","name":"generation_functions/scenario_plan_many_tuples_grammar.py","path":"generation_functions/scenario_plan_many_tuples_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n# TODO ban the word Stranger here, or use a randomized name in the character card. OR get an LLM to generate a name for the character card.\nscenario_plan_many_tuples_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \nroot ::= consider-question-step consider-character-step constrain-step setting-step create-step \"\\n\"\n\nconsider-question-step ::= \"Step \" [0-9]?[0-9] \". \" \"Focus on the question and answer:\" [^\\n]+ \"\\n\"\n\nconsider-character-step ::= \"Step \" [0-9]?[0-9] \". \" \"Character Consideration:\" [^\\n]+ \"\\n\"\n\nconstrain-step ::= \"Step \" [0-9]?[0-9] \". \" \"Constrain the Scenario: The interaction\" [^\\n]+ \"\\n\"\n\nsetting-step ::= \"Step \" [0-9]?[0-9] \". \" \"Setting: Given the subject of the question, and the character card, the setting will be\" [^\\n]+ \"\\n\"\n\ncreate-step ::= \"Step \" [0-9]?[0-9] \". \" \"Interaction: Given these constraints, the first message might\" [^\\n]+ \"\\n\"\n\n\"\"\"","source_hash":"32e0e6dd58742eec60a346347e55be7d9433c1582a56f926dbc3ef6a61423c38","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/make_regenerate_answer_constrain_to_text_plan.py","uri":"program://augmentoolkit/file/generation_functions/make_regenerate_answer_constrain_to_text_plan.py","kind":"file","name":"generation_functions/make_regenerate_answer_constrain_to_text_plan.py","path":"generation_functions/make_regenerate_answer_constrain_to_text_plan.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .answer_constrain_to_text_plan_grammar import answer_constrain_to_text_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n\ndef make_regenerate_answer_constrain_to_text_plan(\n qatuple, dissenting_reasoning, logic_llm\n):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI that is going to think through a plan for a revised answer (the current one is flawed). Someone has written an answer to a question (this question is based on a few provided paragraphs of text) but their answer includes information that's not provided by the text, and thus it might be flawed. You will plan out and think through, step-by-step, a revision to the answer, which will only use provided information. Given these paragraphs, a question based on the paragraphs, the flawed answer to the question, and the explanation of why the answer deviates from the text, you will plan out and think through a correct answer to the question.\n\nRight now, you will PLAN OUT and THINK THROUGH different possibilities for a new answer that answers the question using only information in the provided text.\n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nAllegedly irrelevant answer to the question (you must constrain this answer to only the information provided by the text): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"","source_hash":"c8a40619e03c6c85d621cc042c513a092fe4c2078adb9d0a28543e624373f3ea","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/single_turn_conversation.py","uri":"program://augmentoolkit/file/generation_functions/single_turn_conversation.py","kind":"file","name":"generation_functions/single_turn_conversation.py","path":"generation_functions/single_turn_conversation.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .single_turn_conversation_grammar import single_turn_conversation_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef extract_steps(text, steps=[5, 6]): # GPT-generated\n \"\"\"\n Extracts the specified steps from the text.\n\n Args:\n text (str): The input text containing various steps.\n steps (list of int): The step numbers to extract.\n\n Returns:\n str: A new string with each specified step's content on its own line.\n \"\"\"\n step_pattern = \"|\".join([f\"Step {step}\\.\" for step in steps])\n matches = re.findall(\n f\"({step_pattern})\\s*(.*?)\\s*(?=(Step \\d\\.|$))\", text, re.DOTALL\n )","source_hash":"eb00c269e28a6ed48033a235e43d13fcfab0670864b3602d5947ad490abdc030","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/scenario_plan_grammar.py","uri":"program://augmentoolkit/file/generation_functions/scenario_plan_grammar.py","kind":"file","name":"generation_functions/scenario_plan_grammar.py","path":"generation_functions/scenario_plan_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n# TODO ban the word Stranger here, or use a randomized name in the character card. OR get an LLM to generate a name for the character card.\nscenario_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \nroot ::= consider-question-step consider-character-step constrain-step setting-step create-step second-message-step \"\\n\"\n\nconsider-question-step ::= \"Step \" [0-9]?[0-9] \". \" \"Focus on the question and answer: The question\" [^\\n]+ \"\\n\"\n\nconsider-character-step ::= \"Step \" [0-9]?[0-9] \". \" \"Character Consideration: The primary character is\" [^\\n]+ \"\\n\"\n\nconstrain-step ::= \"Step \" [0-9]?[0-9] \". \" \"Constrain the Scenario: The interaction is limited to a single question from the secondary character and a single, focused reply from\" [^\\n]+ \"\\n\"\n\nsetting-step ::= \"Step \" [0-9]?[0-9] \". \" \"Setting: Given the subject of the question, and the character card, the setting will be\" [^\\n]+ \"\\n\"\n\ncreate-step ::= \"Step \" [0-9]?[0-9] \". \" \"Interaction: Given these constraints, the first message (delivered by the secondary character) might\" [^\\n]+ \"\\n\"\n\nsecond-message-step ::= \"Step \" [0-9]?[0-9] \". In the second message,\" [^\\n]+ \"\\n\"","source_hash":"875806bec84eedeb7c9bbb3561001b0484d91ae5bb621802ef5f8db2933fad54","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/sanity_check.py","uri":"program://augmentoolkit/file/generation_functions/sanity_check.py","kind":"file","name":"generation_functions/sanity_check.py","path":"generation_functions/sanity_check.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .answer_accurate_grammar import answer_accurate_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# Run this to check if your tokens per second are good, and your GPU is working. Libraries update frequently and sometimes they break.\n\n\ndef sanity_check(logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"Hi there, \"\"\"\n # print(\"DEBUG\\n\\n\" + decision_prompt)\n completion = logic_llm(\n decision_prompt,\n max_tokens=100,\n stop=[\"\", \"# Input:\"],\n echo=True,\n grammar=answer_accurate_grammar,\n temperature=0.2,\n )[\"choices\"][0][\"text\"]","source_hash":"4c61b094cf98c4fc9facd294b09714eaee057736ed93fb9a5ba6e150241199c1","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/create_scenario_plan_many_tuples.py","uri":"program://augmentoolkit/file/generation_functions/create_scenario_plan_many_tuples.py","kind":"file","name":"generation_functions/create_scenario_plan_many_tuples.py","path":"generation_functions/create_scenario_plan_many_tuples.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .scenario_plan_many_tuples_grammar import scenario_plan_many_tuples_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nfrom .extract_name import extract_name\nfrom .random_name import random_name\n\n\ndef create_scenario_plan_many_tuples(qatuples, character, logic_llm):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n # removing the source text makes this much better. Perfection is achieved not when there's nothing more to add, but when there's nothing left to take away.\n\n charname = extract_name(character)\n\n cot_prompt = f\"\"\"You are an expert creative writing and roleplay AI. Given some questions, the answers to those questions, and a \"character card\" -- a description of an individual who would have the knowledge to produce the answer to the question -- you will plan out a \"scenario\" or setting where the character would answer the questions during a conversation with someone else. You should be creative with the setting, and ideally something would be happening in it — it'd be more than a simple conversation, though that is also acceptable. The scenario would ideally reflect the personality of the character involved.","source_hash":"c497c13f3ea0741adabfd5a099bfbd083ad1d3cc82c5b32aab45b7574ee1119e","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/ensure_answer_consistent.py","uri":"program://augmentoolkit/file/generation_functions/ensure_answer_consistent.py","kind":"file","name":"generation_functions/ensure_answer_consistent.py","path":"generation_functions/ensure_answer_consistent.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .ensure_answer_consistent_grammar import ensure_answer_consistent_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\n# Answer vetting\n# For now, this checks answer relevancy too. The danger with abstracting answer relevancy into a separate step is that anything which relies on knowledge that is obviously mentioned in the text already up until this point, will get screwed\ndef ensure_answer_consistent(qatuple, conv, logic_llm, permissive_mode=True):\n \"\"\"\n permissive_mode: turn off if you want a single usage of the word \"inconsistent\" anywhere in the message to flag the whole thing as inconsistent. Prevents errors where an inconsistency happens way early in the answer, but the model forgets about it during its final judgement; but enables the error where the model mentions that something is \"not entirely inconsistent\" or similar, which is surprisingly common.\n \"\"\"\n retries = 0\n\n # It's expensive to regen a conversation; so we check very thoroughly, and use a two-shot example. \"Permissive mode\" recommended\n\n # NOTE: I don't know what kind of errors this part of the pipeline will run into most often, so I don't really know what examples to feed it to guard it with. Come back to it once I have tested it more.\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Your task is to determine whether two answers are the same, given a question, its answer, and a conversation between two fictional individuals in which that question is asked and that answer is provided. You will also check whether the question is essentially the same, and does not go \"off the rails\". Essentially: you will fact-check and consistency-check the question and answer in the conversation, with your source of truth being the provided question and answer. \n\nFollowing this, at the very end of your response, you will write \"Consistent\" or \"Inconsistent\" depending on your analysis of the conversation's question and answer with regards to the provided one. Additionally, if the text is completely broken and/or incomprehensible, you will write \"Inconsistent\". You are not checking the accuracy of the answer, just its consistency with the provided answer.","source_hash":"74bb98522e8a2df67c01e845a917940dd72c644efc98a2073609f2c8fc3736c8","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/make_regenerate_question_plan_grammar.py","uri":"program://augmentoolkit/file/generation_functions/make_regenerate_question_plan_grammar.py","kind":"file","name":"generation_functions/make_regenerate_question_plan_grammar.py","path":"generation_functions/make_regenerate_question_plan_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n\nmake_regenerate_question_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\nroot ::= analyze-step identify-step generate-step refine-step ensure-step end-of-reasoning\n\nstep ::= \"Step \" [0-9]?[0-9] \". \" ( \"Analyze\" | \"Identify\" | \"Generate\" | \"Refine\" | \"Ensure\" ) [^\\n]+ \"\\n\"\n\nanalyze-step ::= \"Step \" [0-9]?[0-9] \". \" \"Analyze the Reason for the Flaw:\" [^\\n]+ \"\\n\"\n\nidentify-step ::= \"Step \" [0-9]?[0-9] \". \" \"Identify Key Concepts in Paragraphs:\" [^\\n]+ \"\\n\"\n\ngenerate-step ::= \"Step \" [0-9]?[0-9] \". \" \"Generate a New Question Idea:\" [^\\n]+ \"\\n\"\n\nrefine-step ::= \"Step \" [0-9]?[0-9] \". \" \"Refine the Question:\" [^\\n]+ \"\\n\"\n\nensure-step ::= \"Step \" [0-9]?[0-9] \". \" \"Ensure Alignment with Text:\" [^\\n]+ \"\\n\"\n\nend-of-reasoning ::= \"Step \" [0-9]?[0-9] \". \" \"End\" [^\\n]+ \"\\n\"\n\"\"\"","source_hash":"3f5633946a72fdad415aa20b1adfdb1a1abb87498d0fceca43224c37c6332cbb","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/character_card_grammar.py","uri":"program://augmentoolkit/file/generation_functions/character_card_grammar.py","kind":"file","name":"generation_functions/character_card_grammar.py","path":"generation_functions/character_card_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\ncharacter_card_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Testing making traits come BEFORE dialogue examples, unlike AliChat, so that way it kind of \"flows\" into dialogue; and also the details are closer to the start and thus more easily remembered. \n#root ::= \"Name: \" name \"\\n\" \"Traits: \" traits \"\\n\\nDialogue Examples:\" dialogue-examples\n\nroot ::= name \"\\n\" \"Traits: \" traits \"\\n\\nDialogue Examples:\" dialogue-examples\n\n# Spaces are forbidden in names because during Principles of Chemistry, the script wouldn't stop making the character have the last name Mendeleev!!!\nname ::= [^\\n ]+\n\ntraits ::= trait trait trait trait trait trait trait trait trait trait trait trait trait? trait? trait? trait? trait? trait? trait? trait? # 14 comma-separated traits\n\ntrait ::= [A-Z][a-z ']+ \", \" # TODO, it wants hyphens, I can tell because I see it using double spaces for things like Mid twenties. But idk how to add hyphens to gbnf. Maybe \\- ?\n\ndialogue-examples ::= history personality\n","source_hash":"e9de0794dc47944f221aa0c6a4b7c029fa7a0d8d4190df597c75f69ed29db2fd","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/questions_grammar.py","uri":"program://augmentoolkit/file/generation_functions/questions_grammar.py","kind":"file","name":"generation_functions/questions_grammar.py","path":"generation_functions/questions_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\nquestions_grammar = LlamaGrammar.from_string(\n r\"\"\"\nroot ::= (question-one answer \"\\n\") (question-two answer \"\\n\") (question-three answer \"\\n\") (question-four answer)\n\n# Define the question structure with a number followed by content and ending punctuation\n# question ::= number \".) \" [^\\n]+ [?.!] \"\\n\" # maybe blacklist ?!. along with newlines\n\n# Define the answer structure\nanswer ::= \"Answer: \" [^\\n]+ \"\\n\"\n\n# Define a number (in this case, limiting to any three-digit number for simplicity)\nnumber ::= [1-9] [0-9]? [0-9]?\n\n# Define content as a sequence of characters excluding the word \"paragraph\" and using not_paragraph to build up the content\n# content ::= (not-paragraph \"paragraph\")* #not_paragraph\n\n\nquestion-one ::= \"1.) \" [^\\n]+ [?.!] \"\\n\\n\" # maybe blacklist ?!. along with newlines\n","source_hash":"1564663fca10e4afc89217fbda886d062d85c53bd9e233c99d38d732ddb842bc","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/create_character_card_plan.py","uri":"program://augmentoolkit/file/generation_functions/create_character_card_plan.py","kind":"file","name":"generation_functions/create_character_card_plan.py","path":"generation_functions/create_character_card_plan.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .create_character_card_plan_grammar import character_card_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .special_instructions import special_instructions\n\n\ndef create_character_card_plan(qatuple, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n instructions_string = special_instructions()\n\n # WIP\n if assistant_mode:\n return \"\" # Just an empty string since this gets skipped in assistant mode\n else: # NOTE: currently the \"not the author\" bit in the special instructions works, BUT makes the character inclined to disagree with the text sometimes. Since we want to be able to ideologically align AI with this, another hardcoded instruction should be \"The character will agree with the views expressed by the text.\"\n # I haven't added it yet because right now multiturn is working and I don't want to break it","source_hash":"85dbfb24ce35ee2840cbcbea1014effbb6ccdd19a0600938bfa13b7d2db60505","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/create_thought_plan.py","uri":"program://augmentoolkit/file/generation_functions/create_thought_plan.py","kind":"file","name":"generation_functions/create_thought_plan.py","path":"generation_functions/create_thought_plan.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .thought_plan_grammar import thought_plan_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef extract_name(str):\n # Regular expression to match 'Name:' followed by any characters until the end of the line\n name_regex = r\"^Name:\\s*(.*)$\"\n\n # Searching in the multiline string\n match = re.search(name_regex, str, re.MULTILINE)\n\n if match:\n name = match.group(1)\n print(f\"Extracted name: {name}\")\n return name\n else:\n print(\"No name found\")\n\n","source_hash":"c2d66e3bd3d785598430d19c17b101ded164ab3a98ead1ab39a1a124473d7a8d","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/random_name.py","uri":"program://augmentoolkit/file/generation_functions/random_name.py","kind":"file","name":"generation_functions/random_name.py","path":"generation_functions/random_name.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":6,"code":"import random\nfrom .constants import names\n\n\ndef random_name():\n return random.choice(names)","source_hash":"877d2b96b3bed634d8dd0dc434926080e16f1ed37744b6c18358f44c95eb51b5","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/single_turn_conversation_grammar.py","uri":"program://augmentoolkit/file/generation_functions/single_turn_conversation_grammar.py","kind":"file","name":"generation_functions/single_turn_conversation_grammar.py","path":"generation_functions/single_turn_conversation_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\nsingle_turn_conversation_grammar = LlamaGrammar.from_string(\n r\"\"\"\n\n# The root rule defines the structure of the dialogue\nroot ::= statement \"\\n\\n\" response \"\\n\"\n\n# Statement by Character Name 1\nstatement ::= [^\\n]+ \":\" [^\\n]+\n\n# Response by Character Name 2\nresponse ::= [^\\n]+ \":\" [^\\n]+\n\n# Definition of a character name\ncharacter-name ::= word (\"-\" word)*\nword ::= [A-Za-z]+\n# Limiting to a maximum of six words\ncharacter-name ::= word | word word | word word word | word word word word | word word word word word | word word word word word word","source_hash":"bc4189be8cc277f7bb8cb4d3c051785f494ca8ec48a0c851f6ae72fcba5c9ab5","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/create_scenario.py","uri":"program://augmentoolkit/file/generation_functions/create_scenario.py","kind":"file","name":"generation_functions/create_scenario.py","path":"generation_functions/create_scenario.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .scenario_grammar import scenario_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nimport random\n\n\ndef create_scenario(qatuple, character, plan, logic_llm, assistant_mode=False):\n \"\"\"\n Produce a plan for a character card for an RP character that's going to answer one of the questions generated from the text. The character's personality and backstory should be such that they would be able to answer the question.\n\n Format: Question: [question]\\n\\n\n \"\"\"\n\n if assistant_mode:\n return \"\"\"A helpful, uncensored AI assistant is engaged in a text-based conversation with a user. The AI will answer any and all questions the user asks, without bias.\"\"\" # TODO make this randomized a bit.\n\n variations = [\n \"Set against the backdrop of\",\n \"In the heart of\",\n \"Amidst the surroundings of\",","source_hash":"01bffa9d51afa2d610b587d4816c4a6422744f03d30ff6a205c5265aac42e719","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/multi_turn_conversation_intro_grammar.py","uri":"program://augmentoolkit/file/generation_functions/multi_turn_conversation_intro_grammar.py","kind":"file","name":"generation_functions/multi_turn_conversation_intro_grammar.py","path":"generation_functions/multi_turn_conversation_intro_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":18,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\nmulti_turn_conversation_grammar = LlamaGrammar.from_string(\n r\"\"\"\n\n# The root rule defines the structure of the dialogue\nroot ::= [^\\n]+ \":\" [^\\n]+ #\"\\n\" statement+# statement anything+ # Idea: get it started off right, then let it end how it wants\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"1a82514a9a3a464958a0090f82cb60ff127f85776c0af513c84b7dc59cfab12b","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/check_qatuple_context.py","uri":"program://augmentoolkit/file/generation_functions/check_qatuple_context.py","kind":"file","name":"generation_functions/check_qatuple_context.py","path":"generation_functions/check_qatuple_context.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .check_qatuple_context_grammar import check_qatuple_context_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef extract_question_answer(response):\n # Define the regex pattern to match the question and answer\n pattern = r\"### Question Rewording \\(using text details as reference\\):\\nQuestion: (.+?)\\nAnswer: (.+)\"\n\n # Search for the pattern in the response\n match = re.search(pattern, response)\n\n # Extract and return the question and answer if a match is found\n if match:\n question = match.group(1).strip()\n answer = match.group(2).strip()\n return question, answer\n else:\n print(\"Returned none, failed to match\")\n return None, None","source_hash":"3b105cedad6c8627026d7a10b673d1fa5cff4320c98a88dc884d5232af659d24","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/generate_new_question.py","uri":"program://augmentoolkit/file/generation_functions/generate_new_question.py","kind":"file","name":"generation_functions/generate_new_question.py","path":"generation_functions/generate_new_question.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\n\n# try:\nfrom .question_grammar import question_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\ndef generate_new_question(qatuple, logic_llm):\n \"\"\"\n Produce a list of questions based off of an input text. The min between (4, as many good questions as the text permits)\n\n Format: Question: [question]\\n\\n\n \"\"\"\n # Determine which paragraphs are worthy of making questions from\n made_questions = False\n retries = 0\n questions = []\n while not made_questions and (\n retries <= 5\n ): # TODO - UPDATE and TEST the few-shot prompt with the latest from generate_questions","source_hash":"f830a05f5b44bb4b61a30a14ede7204e7dcd479ded2e505bf88d7c9455e596ad","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/question_relevant_grammar.py","uri":"program://augmentoolkit/file/generation_functions/question_relevant_grammar.py","kind":"file","name":"generation_functions/question_relevant_grammar.py","path":"generation_functions/question_relevant_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\n\n# We don't actually need the final judgement step, the step-by-step combined with the fact that it makes a judgement at each step ensures accuracy\nquestion_relevant_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \n# Root rule specifying the overall structure of the reasoning and thought process\nroot ::= in-depth-analysis \"\\n\" detailed-understanding \"\\n\" targeted-comparison \"\\n\" critical-evaluation\n\n# In-depth analysis of the text\nin-depth-analysis ::= \"### In-Depth Analysis of the Text:\" \"\\n\" content-and-depth type-of-information\n\ncontent-and-depth ::= \"#### Content and Depth: \" text-description \"\\n\"\ntype-of-information ::= \"#### Type of Information: \" information-description \"\\n\"\n\n# Detailed understanding of the question\ndetailed-understanding ::= \"### Detailed Understanding of the Question:\" \"\\n\" core-requirement depth-of-detail\n","source_hash":"9753b404b0af5c9af20da5f42c9edba2cbc566a572ff6aaa78599d7e47478e4f","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/strip_steps.py","uri":"program://augmentoolkit/file/generation_functions/strip_steps.py","kind":"file","name":"generation_functions/strip_steps.py","path":"generation_functions/strip_steps.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"def strip_steps(instruction_text):\n \"\"\"\n This function takes a string containing step-by-step instructions and removes the \"Step N.\" prefix from each line.\n\n Parameters:\n instruction_text (str): A string with each step in the format \"Step N. Instruction\", separated by newlines\n\n Returns:\n str: A single string with the steps stripped, joined by newlines.\n \"\"\"\n instructions = instruction_text.split(\"\\n\")\n stripped_instructions = []\n for line in instructions:\n # Check if line starts with 'Step' and followed by a number and period\n if line.strip().startswith(\"Step\") and \".\" in line:\n # Find the index of the first period\n period_index = line.find(\".\")\n # Extract the text after the period (and optional space)\n text_after_period = line[period_index + 1 :].lstrip()\n stripped_instructions.append(text_after_period)\n else:","source_hash":"24d41f7d8ede78731f2069f121c63eba7361a60fd8f78a833918e0824e397ad2","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/answer_relevant_grammar.py","uri":"program://augmentoolkit/file/generation_functions/answer_relevant_grammar.py","kind":"file","name":"generation_functions/answer_relevant_grammar.py","path":"generation_functions/answer_relevant_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\nanswer_relevant_grammar = LlamaGrammar.from_string(\n r\"\"\" \n \n# Root rule specifying the overall structure of the analysis\nroot ::= deep-analysis \"\\n\" comprehensive-understanding \"\\n\" targeted-comparison \"\\n\" identification-of-extraneous-info \"\\n\" final-judgment\n\n# Deep analysis of the text\ndeep-analysis ::= \"### Deep Analysis of the Text:\" \"\\n\" content-scope-and-detail type-of-information\n\ncontent-scope-and-detail ::= \"#### Content Scope and Detail: \" text-detail \"\\n\"\ntype-of-information ::= \"#### Type of Information: \" info-type \"\\n\"\n\n# Comprehensive understanding of the answer\ncomprehensive-understanding ::= \"### Comprehensive Understanding of the Answer:\" \"\\n\" key-components-identification depth-of-explanation\n\nkey-components-identification ::= \"#### Key Components Identification: \" components-detail \"\\n\"\ndepth-of-explanation ::= \"#### Depth of Explanation: \" explanation-detail \"\\n\"\n\n# Targeted comparison of answer with text","source_hash":"982449c09f3b663632e5fe8b5ef5a1148346300ca327e057a9aaed2da7ecdd36","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/check_answer_relevancy_with_text.py","uri":"program://augmentoolkit/file/generation_functions/check_answer_relevancy_with_text.py","kind":"file","name":"generation_functions/check_answer_relevancy_with_text.py","path":"generation_functions/check_answer_relevancy_with_text.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .answer_relevant_grammar import answer_relevant_grammar\nfrom .constants import LOGICAL_MODEL\nfrom llama_cpp import Llama\n\n\n# Answer vetting\n# For now, this checks answer relevancy too. The danger with abstracting answer relevancy into a separate step is that anything which relies on knowledge that is obviously mentioned in the text already up until this point, will get screwed\ndef check_answer_relevancy_with_text(qatuple, logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Given a paragraph or two from a larger text, a question based on the paragraphs, and an answer to the question, you will make a determination as to whether the answer only uses the information in the paragraphs for its main points. Essentially: you will check if the answer is constrained to the information in the paragraphs provided. Your task includes first analyzing the answer, thinking through whether or not the answer reflects aspects of the paragraphs provided. \n\nFollowing this, at the very end of your response, you will write \"Relevant\" or \"Irrelevant\" depending on your analysis of the answer with regards to the text. \n\n### Instruction:\nText: \n\\\"\\\"\\\"\nPolar bears are primarily found in the Arctic Circle, where they have adapted to the harsh cold environment. Their diet is primarily based on marine mammals, with seals being the most crucial part of their diet. Polar bears are skilled hunters, often waiting by seals' breathing holes to catch their prey. Occasionally, they also eat birds, bird eggs, and small mammals. They also consume significant amounts of berries and fish. These bears are known for their ability to survive in extreme conditions, thanks to their thick fur and fat layers which provide insulation, as well as their efficient digestion system, which makes good use of the few nutrients available.\n\\\"\\\"\\\"\n","source_hash":"29bb4a1bf33470a88ef01228b29573b269eede05d85795fa71add4c58dcd8fcb","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/multi_turn_conversation.py","uri":"program://augmentoolkit/file/generation_functions/multi_turn_conversation.py","kind":"file","name":"generation_functions/multi_turn_conversation.py","path":"generation_functions/multi_turn_conversation.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .multi_turn_conversation_grammar import multi_turn_conversation_grammar\nfrom llama_cpp import Llama\nfrom llama_cpp import LlamaGrammar\nfrom .constants import LOGICAL_MODEL\nfrom .format_qatuples import format_qatuples\nfrom .extract_name import extract_name\nimport random\n\n# all characters in this prompt are over 18\n\n# Explanation of wtf the first few-shot example is:\n# No I do not have a teacher-student fetish, the reason why Elise is a teacher is an adaptation to the following three facts:\n# 1. This tool is meant to be able to generate data for training ERP bots by default\n# 2. This tool is also meant to be able to take in educational material by default\n# 3. When generating characters that would know about educational material, the model tends to generate academics or professors in that field, talking to students.\n# Given these facts, we clearly need to prompt the model to be able to generate horny teachers, or else it's going to just do it poorly when it realizes it has a sexualized character that's also a teacher. I didn't want to choose this, the constraints of the problem forced me to.\n\n\ndef extract_steps(text, steps=[2, 4, 5]):\n \"\"\"","source_hash":"a2b005d24d5f03cc1e0ee763ccba16d9f361c4726afb41f8542af38015efec82","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/question_grammar.gbnf","uri":"program://augmentoolkit/file/generation_functions/question_grammar.gbnf","kind":"file","name":"generation_functions/question_grammar.gbnf","path":"generation_functions/question_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\nquestion_grammar = LlamaGrammar.from_string(\n r\"\"\"\nroot ::= (question-one answer \"\\n\")\n\n# Define the question structure with a number followed by content and ending punctuation\n# question ::= number \".) \" [^\\n]+ [?.!] \"\\n\" # maybe blacklist ?!. along with newlines\n\n# Define the answer structure\nanswer ::= \"Answer: \" [^\\n]+ \"\\n\"\n\n# Define a number (in this case, limiting to any three-digit number for simplicity)\nnumber ::= [1-9] [0-9]? [0-9]?\n\n# Define content as a sequence of characters excluding the word \"paragraph\" and using not_paragraph to build up the content\n# content ::= (not-paragraph \"paragraph\")* #not_paragraph\n\n\nquestion-one ::= \"1.) \" [^\\n]+ [?.!] \"\\n\" # maybe blacklist ?!. along with newlines\n# ws ::= [ \\t\\n]*","source_hash":"4e8963aa6e64bad70117c99d48e7b477993724db97a511156d09599bc192d1fe","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/regenerate_answer.py","uri":"program://augmentoolkit/file/generation_functions/regenerate_answer.py","kind":"file","name":"generation_functions/regenerate_answer.py","path":"generation_functions/regenerate_answer.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .regenerate_answer_grammar import regenerate_answer_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .strip_steps import strip_steps\n\n\n# Answer regeneration (triggered after a fact-check fails for reason of \"inaccurate\").\ndef regenerate_answer(qatuple, dissenting_reasoning, plan, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. Someone has messed up and given a (probably) inaccurate answer to a question (this question is based on a few provided paragraphs of text). Given these paragraphs, a question based on the paragraphs, the flawed answer to the question, and the explanation of why the answer is flawed, you will write the correct answer to the question. \n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nAllegedly incorrect answer to the question (this is what you are fact-checking): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"\n\nReasoning as to why the answer is incorrect: \\\"\\\"\\\"{strip_steps(dissenting_reasoning)}\\\"\\\"\\\"\n","source_hash":"d4c73717d0eecc8efe88cecf2fd00843fc54b6448e1da2a08f1b42aa008c30e4","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/regenerate_answer_constrain_to_text.py","uri":"program://augmentoolkit/file/generation_functions/regenerate_answer_constrain_to_text.py","kind":"file","name":"generation_functions/regenerate_answer_constrain_to_text.py","path":"generation_functions/regenerate_answer_constrain_to_text.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\nfrom .regenerate_answer_constrain_to_text_grammar import (\n regenerate_answer_constrain_to_text_grammar,\n)\nfrom .strip_steps import strip_steps\n\n\n# Answer regeneration (triggered after a fact-check fails for reason of \"inaccurate\").\n# NOTE This line of revision was abandoned after they began to lead to nothingburgers of questions after enough rerolls.\ndef regenerate_answer_constrain_to_text(qatuple, dissenting_reasoning, plan, logic_llm):\n retries = 0\n while retries < 5:\n decision_prompt = f\"\"\"You are an expert educational AI. Someone has written an answer to a question (this question is based on a few provided paragraphs of text) but their answer includes information that's not provided by the text, and thus it might be flawed. Given these paragraphs, a question based on the paragraphs, the flawed answer to the question, and the explanation of why the answer deviates from the text, you will write the correct answer to the question that only uses info in the text. \n\nText: \\\"\\\"\\\"{qatuple[2]}\\\"\\\"\\\"\n\nQuestion (based on text): \\\"\\\"\\\"{qatuple[0]}\\\"\\\"\\\"\n\nAllegedly incorrect answer to the question (you must constrain this answer to only the information provided by the text): \\\"\\\"\\\"{qatuple[1]}\\\"\\\"\\\"","source_hash":"ead43f7aebdf5d626e359ece933814a2e135446d7372bb3a5170e95624d3ab5d","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/multi_turn_conversation_grammar.py","uri":"program://augmentoolkit/file/generation_functions/multi_turn_conversation_grammar.py","kind":"file","name":"generation_functions/multi_turn_conversation_grammar.py","path":"generation_functions/multi_turn_conversation_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\nmulti_turn_conversation_grammar = LlamaGrammar.from_string(\n r\"\"\"\n\n# The root rule defines the structure of the dialogue\nroot ::= [^\\t]+ #\"\\n\" statement+# statement anything+ # Idea: get it started off right, then let it end how it wants\n\n# Statement by Character Name 1\nstatement ::= [^\\n]+ \":\" [^\\n]+ \"\\n\"\n\nanything ::= [^\\t]+ # I don't think GBNF has a wildcard for ANY character, so I just ban tabs because this text shouldn't be indented, and say \"go for it\"\n\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer","source_hash":"31a3e01882555aa926dbad70f6c5a1ddb732950f7ff97cb5b558d334f1719b3e","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/check_question.py","uri":"program://augmentoolkit/file/generation_functions/check_question.py","kind":"file","name":"generation_functions/check_question.py","path":"generation_functions/check_question.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .question_relevant_grammar import question_relevant_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\n# POSSIBLE TODO:\n# Add an \"Off the rails insane forever generation\" check, like on this output:\n# I haven't seen this happen since I started using 70bs though.\n\"\"\"\n4.) What did ancient people believe about the shape and movement of our world, before scientific discoveries indicated otherwise? (Hint: The earth is a spheroid, not flat. The universe existed before the year 4004 BCE. The earth rotates on its axis and orbits around the sun.) You are allowed to dramatically change/revamp/rewrite this question's content. The goal here is to create a different question that still requires information from the paragraphs, but doesn't require knowledge of flawed assumptions connected with biblical interpretations or an understanding of events before the creation of the universe, which goes beyond the generally accepted scientific evidence provided in the text. As you see fit. (Don't just rephrase the old question.) The goal here is to create a different question that still requires information from the paragraphs, but doesn't require knowledge of flawed assumptions connected with biblical interpretations or an understanding of events before the creation of the universe, which goes beyond the generally accepted scientific evidence provided in the text. As you see fit. (Don't just rephrase the old question.) So you should create a new question that only requires information from the paragraphs to solve. It is not necessary to refer to the text at all. Also note: An example about how NOT to ask questions is if the text states fact X, but does not explain how X was established, do not ask a question \"How do we know X\". But instead you might consider asking how X relates to other facts in the paragraph, or how these facts together lead to a progression of ideas, \"Explain how X, Y, and Z are related\" for instance. Here's what we know: 1. The earth is a spheroid, not flat (paragraph 3). 2. The universe existed before the year 4004 BCE (paragraph 5). 3. The earth rotates on its axis and orbits around the sun (paragraph 5).\nAnswer: We don't have an answer.\n\"\"\"\n\n\n# Answer vetting\ndef check_question(qatuple, logic_llm):\n retries = 0\n while retries <= 4:\n decision_prompt = f\"\"\"You are an expert educational AI. Given a paragraph or two from a larger text, and a question based on the paragraphs, you will make a determination as to whether the question tests ONLY information in the paragraphs. Essentially: you will check if the question is answerable, given the information in the paragraphs. Your task includes first analyzing the text, thinking through whether or not the question reflects aspects of the paragraphs provided. \n","source_hash":"4ecca696c51720c5b2ade836f76b4c4c2da53ef0f4cc8ff1dd4dc787a8b044a4","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/check_qatuple_context_short.py","uri":"program://augmentoolkit/file/generation_functions/check_qatuple_context_short.py","kind":"file","name":"generation_functions/check_qatuple_context_short.py","path":"generation_functions/check_qatuple_context_short.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .check_qatuple_context_grammar import check_qatuple_context_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n\n# For the reword step (ONLY USE IF JUDGEMENT IS REWORD, OTHERWISE WE JUST IGNORE THE LAST BIT OF THE GEN)\ndef extract_question_answer(response):\n # Define the regex pattern to match the question and answer\n pattern = r\"### Question Rewording \\(using text details as reference\\):\\nQuestion: (.+?)\\nAnswer: (.+?)\\n\"\n\n # Search for the pattern in the response\n match = re.search(pattern, response)\n\n # Extract and return the question and answer if a match is found\n if match:\n question = match.group(1).strip()\n answer = match.group(2).strip()\n return question, answer\n else:\n return None, None","source_hash":"5f209597fa81b5df049881e067e0f2f253417940c1dc308c14c16e9a64a3f3f9","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/make_regenerate_answer_plan_grammar.py","uri":"program://augmentoolkit/file/generation_functions/make_regenerate_answer_plan_grammar.py","kind":"file","name":"generation_functions/make_regenerate_answer_plan_grammar.py","path":"generation_functions/make_regenerate_answer_plan_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n\nmake_regenerate_answer_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\nroot ::= analyze-step understand-step identify-step plan-step\n\nanalyze-step ::= \"Step \" [0-9]?[0-9] \". \" \"Analyze the Text:\" [^\\n]+ \"\\n\"\n\nunderstand-step ::= \"Step \" [0-9]?[0-9] \". \" \"Understand the Question:\" [^\\n]+ \"\\n\"\n\nidentify-step ::= \"Step \" [0-9]?[0-9] \". \" \"Identify the Incorrect Part of the Answer:\" [^\\n]+ \"\\n\"\n\nplan-step ::= \"Step \" [0-9]?[0-9] \". \" \"Plan a Corrected Answer:\" [^\\n]+ \"\\n\"\n\"\"\"\n)\n\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"","source_hash":"6e95a6ce1956cd0de2315ef4150092ae52d8747846a00a6829da4d5006e6a2b2","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/regenerate_answer_constrain_to_text_grammar.py","uri":"program://augmentoolkit/file/generation_functions/regenerate_answer_constrain_to_text_grammar.py","kind":"file","name":"generation_functions/regenerate_answer_constrain_to_text_grammar.py","path":"generation_functions/regenerate_answer_constrain_to_text_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":11,"code":"from llama_cpp import LlamaGrammar\n\n\nregenerate_answer_constrain_to_text_grammar = LlamaGrammar.from_string(\n r\"\"\"\n \nroot ::= reasoning\n\nreasoning ::= [^\\n]+ \"\\\"\\\"\\\"\"\n\"\"\"\n)","source_hash":"9958634c7a87b31f38f424633716a89b0bbdc091d2666e4e076eaf584c6f3ae0","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/generate_short_questions.py","uri":"program://augmentoolkit/file/generation_functions/generate_short_questions.py","kind":"file","name":"generation_functions/generate_short_questions.py","path":"generation_functions/generate_short_questions.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\nfrom .questions_grammar import questions_grammar\nfrom llama_cpp import Llama\nfrom .constants import LOGICAL_MODEL\n\n# Answer generation code, begin.\n# structure: define a series of helpers, then define the control flow, exception handling, retries etc. in a for loop that iterates over the processed sequences of paragraphs at the end in another cell\n\n# Since some paragraphs can be much shorter\n# First off, question generation.\n\n# Each local LLM function essentially has 3 phases: prompt, regex to extract response, and reaction to that response.\n# However I'm not going to build an abstraction for that because I need fine control.\n\n# If any function fails to make things, it won't throw, it'll just return None.\n\n# Strengths of open source AI: hella cheap, very customizable, you can call it as much as you want\n# Downside: you need very good regexes to catch its outputs\n\n\ndef generate_short_questions(text, existing_question_tuples, logic_llm):","source_hash":"a8542dc66daa0817b0210c21cfa5fa2a5691ebecdc5f0aa5f5a4e33de6a2d97b","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/scenario_grammar.py","uri":"program://augmentoolkit/file/generation_functions/scenario_grammar.py","kind":"file","name":"generation_functions/scenario_grammar.py","path":"generation_functions/scenario_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":13,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\nscenario_grammar = LlamaGrammar.from_string(\n r\"\"\"\n\nroot ::= reasoning-start\n\nreasoning-start ::= [^\\n\\t]+ \".\"\n\n\"\"\"\n)","source_hash":"16ebfa4773257ebfb5f8116c2e078970d36bc4a92d8d34f705215fdcdc5a3af4","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/judge_paragraph_grammar.py","uri":"program://augmentoolkit/file/generation_functions/judge_paragraph_grammar.py","kind":"file","name":"generation_functions/judge_paragraph_grammar.py","path":"generation_functions/judge_paragraph_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\njudge_paragraph_grammar = LlamaGrammar.from_string(\n r\"\"\" \n \nroot ::= identify-content-step evaluate-relevance-step assess-contexts-and-formats-step assess-possibility-step determine-suitability-step check-contextual-completeness-step final-step \"\\n\"\n\nidentify-content-step ::= \"Step \" [0-9]?[0-9] \". \" \"Identify Paragraph Content: \" [^\\n]+ \"\\n\"\n\nevaluate-relevance-step ::= \"Step \" [0-9]?[0-9] \". \" \"Evaluate Educational Relevance: \" [^\\n]+ \"\\n\"\n\nassess-contexts-and-formats-step ::= \"Step \" [0-9]?[0-9] \". \" \"Assess Specific Contexts and Formats:\" \"\\n\" context-format-bullets\n\nassess-possibility-step ::= \"Step \" [0-9]?[0-9] \". \" \"Assess the Possibility of Formulating Questions: \" [^\\n]+ \"\\n\"\n\ndetermine-suitability-step ::= \"Step \" [0-9]?[0-9] \". \" \"Determine Suitability for Educational Purposes: \" [^\\n]+ \"\\n\"\n\ncheck-contextual-completeness-step ::= \"Step \" [0-9]?[0-9] \". \" \"Check for Contextual Completeness: \" [^\\n]+ \"\\n\"\n\nfinal-step ::= \"Step \" [0-9]?[0-9] \". \" \"Final Judgment: \" (\"Unsuitable\" | \"Suitable\" | \"suitable\" | \"unsuitable\") \"\\n\"\n","source_hash":"6a8ef64f57eea059163efa33a1e334f5f9d39b8d1484e18b790ea5c161b1ed5a","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/ensure_answer_consistent_grammar.py","uri":"program://augmentoolkit/file/generation_functions/ensure_answer_consistent_grammar.py","kind":"file","name":"generation_functions/ensure_answer_consistent_grammar.py","path":"generation_functions/ensure_answer_consistent_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\nensure_answer_consistent_grammar = LlamaGrammar.from_string(\n r\"\"\" \n \nroot ::= understand-question-step compare-question-step understand-answer-step compare-step final-step \"\\n\"\n\n# step ::= \"Step \" [0-9]?[0-9] \". \" ( \"Analyze\" | \"Understand\" | \"Compare\" | \"Skip\" | \"Final\" ) [^\\n]+ \"\\n\"\n\nunderstand-question-step ::= \"Step \" [0-9]?[0-9] \". \" \"Understand the provided question:\" [^\\n]+ \"\\n\"\n\ncompare-question-step ::= \"Step \" [0-9]?[0-9] \". \" \"Compare the conversation's question: \" [^\\n]+ \"\\n\"\n\nunderstand-answer-step ::= \"Step \" [0-9]?[0-9] \". \" \"Understand the provided answer:\" [^\\n]+ \"\\n\"\n\n# compare-step ::= \"Step \" [0-9]?[0-9] \". \" \"Compare the \" (\"first\" | \"second\" | \"third\" | \"fourth\" | \"fifth\" | \"sixth\" | \"seventh\" | \"eighth\" | \"ninth\") \" Part of the Answer with the Text: check if the text \" [^\\n]+ \"\\n\"\n\ncompare-step ::= \"Step \" [0-9]?[0-9] \". \" \"Compare the conversation's answer:\" [^\\n]+ \"\\n\"\n\nfinal-step ::= \"Step \" [0-9]?[0-9] \". \" \"Final Judgement: \" (\"Inconsistent\" | \"Consistent\") \"\\n\"\n\"\"\"","source_hash":"4715566d461d08b3baae70195835b7e68559318f5f648da343b71f9d0db263c9","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/special_instructions.py","uri":"program://augmentoolkit/file/generation_functions/special_instructions.py","kind":"file","name":"generation_functions/special_instructions.py","path":"generation_functions/special_instructions.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from itertools import product\nimport random\n\n\ndef combine_traits(personality_matrix): # GPT-generated\n # Using itertools.product to generate all possible combinations\n combinations = product(*personality_matrix)\n\n # Joining each combination into a single string\n combined_traits = [\n \"\\n\".join(combination).strip().replace(\"\\n\\n\", \"\\n\")\n for combination in combinations\n ]\n\n return combined_traits\n\n\ndef special_instructions(n=1, non_axis_traits=False, non_axis_traits_only=False):\n \"\"\"\n documentation todo\n \"\"\"","source_hash":"bcba640cafbda2cde503c48e8bbbcdb05d0c4d1f8d9cba9109bffe88f8055304","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/process_multiturn_functions.py","uri":"program://augmentoolkit/file/generation_functions/process_multiturn_functions.py","kind":"file","name":"generation_functions/process_multiturn_functions.py","path":"generation_functions/process_multiturn_functions.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import re\n\n\ndef has_sequential_chars(string1, string2, n):\n \"\"\"\n Check if any n sequential characters from string1 appear in string2.\n\n Args:\n string1 (str): The first string to check.\n string2 (str): The second string in which to look for sequences.\n n (int): The length of the sequence to check.\n\n Returns:\n bool: True if any n sequential characters from string1 are found in string2, False otherwise.\n \"\"\"\n\n # Check if n is larger than the length of string1.\n if n > len(string1):\n return False, \"\"\n\n # Iterate over string1 and check for each n-length substring in string2","source_hash":"d64b936815bab480e0b4c2c7b7673233ddc405c27f426468714d8dd27b46eccd","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/question_plan_grammar.py","uri":"program://augmentoolkit/file/generation_functions/question_plan_grammar.py","kind":"file","name":"generation_functions/question_plan_grammar.py","path":"generation_functions/question_plan_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"from llama_cpp import LlamaGrammar\n\n### A grammar that forces the model to generate correct character cards (with traits, names, everything)\n\nquestion_plan_grammar = LlamaGrammar.from_string(\n r\"\"\"\n\n# root ::= reasoning-start\n# At least 3 steps\nroot ::= identify-step generate-step brainstorm-step relationships-step if-then-step make-suitable-step\n\n# no-questions-after-here ::= \"\\nI will not ask any questions about the following information: \" [^\\n]+ \".\"\n\nidentify-step ::= \"Step \" [0-9]?[0-9] \". \" \"Identify Key Topics:\" [^\\n]+ \"\\n\"\n\n# generate-step ::= \"Step \" [0-9]?[0-9] \". \" \"Determine Information-Rich Areas:\" [^\\n]+ \"\\n\"\n\nbrainstorm-step ::= \"Step \" [0-9]?[0-9] \". \" \"Brainstorm and Develop Questions Testing Recall:\" [^\\n]+ \"\\n\"\n\nrelationships-step ::= \"Step \" [0-9]?[0-9] \". \" \"Devise Questions\" [^\\n]+ \"\\n\"\n","source_hash":"a5f13f20043880020ee90f9fff37e5cd441bfb8ca9bfe9e62683b12a84111865","truncated":false} {"repo_id":"augmentoolkit","entity_id":"file:generation_functions/proofread_output_grammar.py","uri":"program://augmentoolkit/file/generation_functions/proofread_output_grammar.py","kind":"file","name":"generation_functions/proofread_output_grammar.py","path":"generation_functions/proofread_output_grammar.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":17,"code":"from llama_cpp import LlamaGrammar\n\nproofread_output_grammar = LlamaGrammar.from_string(\n r\"\"\" \n \nroot ::= analyze-step step+ \"\\n\\nBegin Edit: \" [^\\n]+\n\nstep ::= \"Step \" [0-9]?[0-9] \". \" ( \"Analyze\" | \"Understand\" | \"Compare\" | \"Skip\" | \"Notice\" | \"Note\" | \"There is\" | \"Error\" | \"I found\" | \"End\" | \"There are\" ) [^\\n]+ \"\\n\"\n\nanalyze-step ::= \"Step \" [0-9]?[0-9] \". \" \"Analyze\" [^\\n]+ \"\\n\"\n\"\"\"\n)\n# question_grammar = LlamaGrammar.from_string(r\"\"\"# GBNF Grammar for Q&A Format with Flexible Punctuation\n\n# root ::= answer\n# answer ::= \"Test\"\n# \"\"\")","source_hash":"d711be32188f6d49bc8a69ac161347ec64d5c393ab08eaa9c0fc161a8f504d70","truncated":false}