import re
from .single_turn_conversation_grammar import single_turn_conversation_grammar
from llama_cpp import Llama
from .constants import LOGICAL_MODEL

def extract_steps(text, steps=[5, 6]):  # GPT-generated
    """
    Extracts the specified steps from the text.

    Args:
    text (str): The input text containing various steps.
    steps (list of int): The step numbers to extract.

    Returns:
    str: A new string with each specified step's content on its own line.
    """
    step_pattern = "|".join([f"Step {step}\." for step in steps])
    matches = re.findall(
        f"({step_pattern})\s*(.*?)\s*(?=(Step \d\.|$))", text, re.DOTALL
    )

    # Extract and join the matched content, skipping the "Step n." part
    extracted_text = "\n".join(match[1].strip() for match in matches)
    return extracted_text

def single_turn_conversation(
    qatuple,
    character,
    scenario,
    thought_plan,
    scenario_plan,
    logic_llm,
    assistant_mode=False,
):
    """
    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.

    Format: Question: [question]\n\n
    """

    extra_info = extract_steps(scenario_plan)

    if assistant_mode:  # TODO
        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.

## Information:

Question: \"\"\"What is the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\"\"\"
Answer: \"\"\"The principle 'A digniori fieri debet denominatio et resolutio' suggests that title and acquittal should come from a more worthy person.\"\"\"

### Response:
## Conversation that answers the provided question:
User: "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'?"
AI 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."

## Information:

Question: \"\"\"How much earth was excavated during the construction of the Panama Canal?\"\"\"
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.\"\"\"

### Response:
## Conversation that answers the provided question:
User: "AI Assistant, I'm curious about the Panama Canal. How much earth was excavated during its construction?"
AI 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."

Question: \"\"\"What is the primary purpose of the Hubble Space Telescope?\"\"\"
Answer: \"\"\"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.\"\"\"

### Response:
## Conversation that answers the provided question:
User: "Hey AI Assistant, I've always been fascinated by space. Can you tell me what the main purpose of the Hubble Space Telescope is?"
AI 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."

## Information:
\"\"\"
{character}
\"\"\"

Here is the scenario:
\"\"\"
{scenario}
\"\"\"

The character will reason out their answer using the following logical steps:
{thought_plan}

Question: {qatuple[0]}
Answer: {qatuple[1]}

The primary character's answer will use all parts of the answer given.

### Response:
## Conversation that answers the provided question (first, the secondary character will ask the question; then, the primary character will answer it):"""
    else:
        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.

You 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.

Remember to provide the whole answer, with step-by-step reasoning, in the second message of the conversation.

## Information:
\"\"\"
Name: Judge Elias Hawthorne

Traits: Intellectual, Stoic, Idealistic, Reflective, Melancholic, Introspective, Authoritative, Reserved, Doubtful, Traditionalist, Articulate, Cultured, Passionate

Dialogue examples:

Stranger: "What's your backstory?"
Judge 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."

Stranger: "What's your personality?"
Judge 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."
\"\"\"

Here is the scenario:
\"\"\"
In 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.
\"\"\"

The character will reason out their answer using the following logical steps:
Step 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.
Step 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."
Step 3. Realize that this principle emphasizes the importance of the worthiness or merit of the individual in legal decisions related to titles and acquittals.
Step 4. Understand that this implies a belief that justice and legal rights should be administered by those who are most competent and deserving.
Step 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.

Here's some further information that might help you:
Interaction: 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.
In 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.

Question: \"\"\"What is the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\"\"\"
Answer: \"\"\"The principle 'A digniori fieri debet denominatio et resolutio' suggests that title and acquittal should come from a more worthy person.\"\"\"

### Response:
## Conversation that answers the provided question:
Evelyn: "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'?"
Judge 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.'"

## Information:
\"\"\"
Name: Carlos Mendez

Traits: Passionate, Innovative, Knowledgeable, Ambitious, Dedicated, Stressed, Obsessive, Fearful of failure, Experienced, Problem-solver, Committed, Hard-working, Exhausted, Proud

Dialogue examples:

Stranger: "What's your backstory?"
Carlos 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."

Stranger: "What's your personality?"
Carlos 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?"
\"\"\"

Here is the scenario:
\"\"\"
As 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.
\"\"\"

The character will reason out their answer using the following logical steps:
Step 1. Formulate a plan to answer the question about the amount of earth excavated during the Panama Canal construction.
Step 2. Recall that "how much earth was excavated" can be decently answered by stating the volume of earth removed.
Step 3. Recall that over 200 million cubic yards of earth were removed.
Step 4. Conclude that the answer to the question is over 200 million cubic yards.

Here's some further information that might help you:
Interaction: 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.
In 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.

Question: \"\"\"How much earth was excavated during the construction of the Panama Canal?\"\"\"
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.\"\"\"

### Response:
## Conversation that answers the provided question:
Mario 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?"
Carlos 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."

## Information:
\"\"\"
{character}
\"\"\"

Here is the scenario:
\"\"\"
{scenario}
\"\"\"

The character will reason out their answer using the following logical steps:
{thought_plan}

Here's some further information that might help you:
{extra_info}

Question: {qatuple[0]}
Answer: {qatuple[1]}

The primary character's answer will use all parts of the answer given.

### Response:
## Conversation that answers the provided question (first, the secondary character will ask the question; then, the primary character will answer it):
"""
    # 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

    # Note: performance degrades rapidly if you put more than one sentence in a pre-prompt parentheses thing
    completion = logic_llm(
        cot_prompt,
        max_tokens=4096,
        stop=["</s>", "# Input:"],
        echo=True,
        grammar=single_turn_conversation_grammar,
        temperature=0.2,
    )["choices"][0]["text"]
    # print("COMPLETION:\n\n----------------------")
    # print(completion)
    # print("\n------------------")

    # Extract plan
    response_pattern = re.compile(
        r"Conversation that answers the provided question \(first, the secondary character will ask the question; then, the primary character will answer it\):\n(.+)",
        re.IGNORECASE | re.DOTALL,
    )
    generation = response_pattern.search(completion).group(1)
    # print("GENERATION:\n\n-------------------\n\n", generation)

    return generation

if __name__ == "__main__":  # test
    logic_llm = Llama(
        model_path=LOGICAL_MODEL,
        n_gqa=8,
        offload_kqv=True,
        n_ctx=4096,
        n_gpu_layers=1000,
    )  # load the logical LLM and offload everything
    # Q0 is good q, bad a
    # q1 is good q, good a,
    # q2 is bad q, bad a,
    # q3 is iffy q, good a
    q_test = [
        (
            "Explain how our understanding of planetary motion has changed over time.",
            "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.",
            "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.",
        ),
        (
            "Identify and explain changes in human understanding throughout history regarding the age of the Earth.",
            "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.",
            "The story of our world is a story that is still very imperfectly known. A couple of hundred years ago men possessed the histor
# ... truncated ...


import re
from .single_turn_conversation_grammar import single_turn_conversation_grammar
from llama_cpp import Llama
from .constants import LOGICAL_MODEL

def extract_steps(text, steps=[5, 6]):  # GPT-generated
    """
    Extracts the specified steps from the text.

    Args:
    text (str): The input text containing various steps.
    steps (list of int): The step numbers to extract.

    Returns:
    str: A new string with each specified step's content on its own line.
    """
    step_pattern = "|".join([f"Step {step}\." for step in steps])
    matches = re.findall(
        f"({step_pattern})\s*(.*?)\s*(?=(Step \d\.|$))", text, re.DOTALL
    )

    # Extract and join the matched content, skipping the "Step n." part
    extracted_text = "\n".join(match[1].strip() for match in matches)
    return extracted_text

def single_turn_conversation(
    qatuple,
    character,
    scenario,
    thought_plan,
    scenario_plan,
    logic_llm,
    assistant_mode=False,
):
    """
    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.

    Format: Question: [question]\n\n
    """

    extra_info = extract_steps(scenario_plan)

    if assistant_mode:  # TODO


    """
    Extracts the specified steps from the text.

    Args:
    text (str): The input text containing various steps.
    steps (list of int): The step numbers to extract.

    Returns:
    str: A new string with each specified step's content on its own line.
    """
    step_pattern = "|".join([f"Step {step}\." for step in steps])
    matches = re.findall(
        f"({step_pattern})\s*(.*?)\s*(?=(Step \d\.|$))", text, re.DOTALL
    )

    # Extract and join the matched content, skipping the "Step n." part
    extracted_text = "\n".join(match[1].strip() for match in matches)
    return extracted_text

def single_turn_conversation(
    qatuple,
    character,
    scenario,
    thought_plan,
    scenario_plan,
    logic_llm,
    assistant_mode=False,
):
    """
    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.

    Format: Question: [question]\n\n
    """

    extra_info = extract_steps(scenario_plan)

    if assistant_mode:  # TODO
        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.

## Information:

Question: \"\"\"What is the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\"\"\"
Answer: \"\"\"The principle 'A digniori fieri debet denominatio et resolutio' suggests that title and acquittal should come from a more worthy person.\"\"\"

### Response:
## Conversation that answers the provided question:
User: "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'?"
AI 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."

## Information:

Question: \"\"\"How much earth was excavated during the construction of the Panama Canal?\"\"\"
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.\"\"\"

### Response:
## Conversation that answers the provided question:
User: "AI Assistant, I'm curious about the Panama Canal. How much earth was excavated during its construction?"
AI 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."

Question: \"\"\"What is the primary purpose of the Hubble Space Telescope?\"\"\"
Answer: \"\"\"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.\"\"\"

### Response:
## Conversation that answers the provided question:
User: "Hey AI Assistant, I've always been fascinated by space. Can you tell me what the main purpose of the Hubble Space Telescope is?"
AI 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."

## Information:
\"\"\"
{character}
\"\"\"

Here is the scenario:
\"\"\"
{scenario}
\"\"\"

The character will reason out their answer using the following logical steps:
{thought_plan}

Question: {qatuple[0]}
Answer: {qatuple[1]}

The primary character's answer will use all parts of the answer given.

### Response:
## Conversation that answers the provided question (first, the secondary character will ask the question; then, the primary character will answer it):"""
    else:
        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.

You 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.

Remember to provide the whole answer, with step-by-step reasoning, in the second message of the conversation.

## Information:
\"\"\"
Name: Judge Elias Hawthorne

Traits: Intellectual, Stoic, Idealistic, Reflective, Melancholic, Introspective, Authoritative, Reserved, Doubtful, Traditionalist, Articulate, Cultured, Passionate

Dialogue examples:

Stranger: "What's your backstory?"
Judge 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."

Stranger: "What's your personality?"
Judge 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."
\"\"\"

Here is the scenario:
\"\"\"
In 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.
\"\"\"

The character will reason out their answer using the following logical steps:
Step 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.
Step 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."
Step 3. Realize that this principle emphasizes the importance of the worthiness or merit of the individual in legal decisions related to titles and acquittals.
Step 4. Understand that this implies a belief that justice and legal rights should be administered by those who are most competent and deserving.
Step 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.

Here's some further information that might help you:
Interaction: 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.
In 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.

Question: \"\"\"What is the old latin legal principle behind 'A digniori fieri debet denominatio et resolutio'?\"\"\"
Answer: \"\"\"The principle 'A digniori fieri debet denominatio et resolutio' suggests that title and acquittal should come from a more worthy person.\"\"\"

### Response:
## Conversation that answers the provided question:
Evelyn: "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'?"
Judge 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.'"

## Information:
\"\"\"
Name: Carlos Mendez

Traits: Passionate, Innovative, Knowledgeable, Ambitious, Dedicated, Stressed, Obsessive, Fearful of failure, Experienced, Problem-solver, Committed, Hard-working, Exhausted, Proud

Dialogue examples:

Stranger: "What's your backstory?"
Carlos 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."

Stranger: "What's your personality?"
Carlos 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?"
\"\"\"

Here is the scenario:
\"\"\"
As 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.
\"\"\"

The character will reason out their answer using the following logical steps:
Step 1. Formulate a plan to answer the question about the amount of earth excavated during the Panama Canal construction.
Step 2. Recall that "how much earth was excavated" can be decently answered by stating the volume of earth removed.
Step 3. Recall that over 200 million cubic yards of earth were removed.
Step 4. Conclude that the answer to the question is over 200 million cubic yards.

Here's some further information that might help you:
Interaction: 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.
In 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.

Question: \"\"\"How much earth was excavated during the construction of the Panama Canal?\"\"\"
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.\"\"\"

### Response:
## Conversation that answers the provided question:
Mario 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?"
Carlos 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."

## Information:
\"\"\"
{character}
\"\"\"

Here is the scenario:
\"\"\"
{scenario}
\"\"\"

The character will reason out their answer using the following logical steps:
{thought_plan}

Here's some further information that might help you:
{extra_info}

Question: {qatuple[0]}
Answer: {qatuple[1]}

The primary character's answer will use all parts of the answer given.

### Response:
## Conversation that answers the provided question (first, the secondary character will ask the question; then, the primary character will answer it):
"""
    # 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

    # Note: performance degrades rapidly if you put more than one sentence in a pre-prompt parentheses thing
    completion = logic_llm(
        cot_prompt,
        max_tokens=4096,
        stop=["</s>", "# Input:"],
        echo=True,
        grammar=single_turn_conversation_grammar,
        temperature=0.2,
    )["choices"][0]["text"]
    # print("COMPLETION:\n\n----------------------")
    # print(completion)
    # print("\n------------------")

    # Extract plan
    response_pattern = re.compile(
        r"Conversation that answers the provided question \(first, the secondary character will ask the question; then, the primary character will answer it\):\n(.+)",
        re.IGNORECASE | re.DOTALL,
    )
    generation = response_pattern.search(completion).group(1)
    # print("GENERATION:\n\n-------------------\n\n", generation)

    return generation

if __name__ == "__main__":  # test
    logic_llm = Llama(
        model_path=LOGICAL_MODEL,
        n_gqa=8,
        offload_kqv=True,
        n_ctx=4096,
        n_gpu_layers=1000,
    )  # load the logical LLM and offload everything
    # Q0 is good q, bad a
    # q1 is good q, good a,
    # q2 is bad q, bad a,
    # q3 is iffy q, good a
    q_test = [
        (
            "Explain how our understanding of planetary motion has changed over time.",
            "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.",
            "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.",
        ),


from llama_cpp import LlamaGrammar

### A grammar that forces the model to generate correct character cards (with traits, names, everything)

# 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.
scenario_plan_grammar = LlamaGrammar.from_string(
    r"""

root ::= consider-question-step consider-character-step constrain-step setting-step create-step second-message-step "\n"

consider-question-step ::= "Step " [0-9]?[0-9] ". " "Focus on the question and answer: The question" [^\n]+ "\n"

consider-character-step ::= "Step " [0-9]?[0-9] ". " "Character Consideration: The primary character is" [^\n]+ "\n"

constrain-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"

setting-step ::= "Step " [0-9]?[0-9] ". " "Setting: Given the subject of the question, and the character card, the setting will be" [^\n]+ "\n"

create-step ::= "Step " [0-9]?[0-9] ". " "Interaction: Given these constraints, the first message (delivered by the secondary character) might" [^\n]+ "\n"

second-message-step ::= "Step " [0-9]?[0-9] ". In the second message," [^\n]+ "\n"

"""
)


import re
from .answer_accurate_grammar import answer_accurate_grammar
from llama_cpp import Llama
from .constants import LOGICAL_MODEL

# Run this to check if your tokens per second are good, and your GPU is working. Libraries update frequently and sometimes they break.

def sanity_check(logic_llm):
    retries = 0
    while retries <= 4:
        decision_prompt = f"""Hi there, """
        # print("DEBUG\n\n" + decision_prompt)
        completion = logic_llm(
            decision_prompt,
            max_tokens=100,
            stop=["</s>", "# Input:"],
            echo=True,
            grammar=answer_accurate_grammar,
            temperature=0.2,
        )["choices"][0]["text"]
        # print(completion)

        return

if __name__ == "__main__":  # test
    logic_llm = Llama(
        model_path=LOGICAL_MODEL,
        n_gqa=8,
        offload_kqv=True,
        n_ctx=8000,
        n_gpu_layers=1000,
        rope_freq_scale=0.33,
        rope_scaling_type=1,
    )  # load the logical LLM and offload everything

    d = sanity_check(logic_llm)
    print(d)


import re
from .scenario_plan_many_tuples_grammar import scenario_plan_many_tuples_grammar
from llama_cpp import Llama
from .constants import LOGICAL_MODEL
from .format_qatuples import format_qatuples
from .extract_name import extract_name
from .random_name import random_name

def create_scenario_plan_many_tuples(qatuples, character, logic_llm):
    """
    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.

    Format: Question: [question]\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.

    charname = extract_name(character)

    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.

The 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.

The scenario plan should explicitly describe how the secondary character is going to ask the primary character the question.

To avoid inaccuracies, don't use real people as characters.

## Information:

Description of the character who is going to answer the question:
\"\"\"
Name: Elise Delacroix

Traits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo

Dialogue Examples:
Stranger: "What's your backstory?"
Elise 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?~"
Stranger: "What's your personality?"
Elise 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?"

Question: \"\"\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\"\"\"
Answer: \"\"\"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.\"\"\"

Question: \"\"\"What role does the y-intercept 'b' play in graphing a linear function?\"\"\"
Answer: \"\"\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\"\"\"

Question: \"\"\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\"\"\"
Answer: \"\"\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\"\"\"

Question: \"\"\"In what fields might you use linear and quadratic functions?\"\"\"
Answer: \"\"\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\"\"\"

### Response:
## Scenario plan:
Step 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.
Step 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.
Step 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.
Step 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.
Step 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.

## Information:

Description of the character who is going to answer the question:
\"\"\"
Name: Hugo Martinez

Traits: 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

Dialogue Examples:
Stranger: "What's your backstory?"
Hugo 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?"
Stranger: "What's your personality?"
Hugo 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."
\"\"\"

Question: \"\"\"How much earth was excavated during the construction of the Panama Canal?\"\"\"
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.\"\"\"

Question: \"\"\"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\"\"\"
Answer: \"\"\"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.\"\"\"

### Response:
## Scenario plan:
Step 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.
Step 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.
Step 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.
Step 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.
Step 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.

## Information:

{format_qatuples(qatuples)}

Description of the character who is going to answer the question:
\"\"\"
{character}
\"\"\"

You don't need to add negative emotions and tension to the scenario if those don't gel nicely with the character's personality.

### Response:
## Scenario plan (be creative, and make sure all characters present fit in with the setting):
"""
    # 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
    completion = logic_llm(
        cot_prompt,
        max_tokens=8000,
        stop=["</s>", "# Input:"],
        echo=True,
        grammar=scenario_plan_many_tuples_grammar,
        temperature=1.5,  # min p settings, too inconsistent
        top_k=0,
        top_p=1,
        min_p=0.5,
    )["choices"][0]["text"]
    # print("COMPLETION:\n\n----------------------")
    # # print(completion)
    # print("\n------------------")

    # Extract plan
    response_pattern = re.compile(
        r"Scenario plan \(be creative, and make sure all characters present fit in with the setting\):\n(.+)",
        re.IGNORECASE | re.DOTALL,
    )
    generation = response_pattern.search(completion).group(1)
    # print("GENERATION:\n\n-------------------\n\n", generation)

    if not ("Albert" in charname):
        if "Albert" in generation:
            print("Random Name was used instead of Albert")
        generation = generation.replace("Albert", random_name())

    return generation.strip(), completion

if __name__ == "__main__":  # test
    logic_llm = Llama(
        model_path=LOGICAL_MODEL,
        n_gqa=8,
        offload_kqv=True,
        n_ctx=8000,
        n_gpu_layers=1000,
        rope_freq_scale=0.5,
        rope_scaling_type=1,
    )  # load the logical LLM and offload everything
    # Q0 is good q, bad a
    # q1 is good q, good a,
    # q2 is bad q, bad a,
    # q3 is iffy q, good a
    q_test = [
        (
            "Explain how our understanding of planetary motion has changed over time.",
            "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.",
            "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.",
            "A Short History of the World, by HG Wells",
        ),
        (
            "Identify and explain changes in human understanding throughout history regarding the age of the Earth.",
            "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.",
            "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
# ... truncated ...


import re
from .scenario_plan_many_tuples_grammar import scenario_plan_many_tuples_grammar
from llama_cpp import Llama
from .constants import LOGICAL_MODEL
from .format_qatuples import format_qatuples
from .extract_name import extract_name
from .random_name import random_name

def create_scenario_plan_many_tuples(qatuples, character, logic_llm):
    """
    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.

    Format: Question: [question]\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.

    charname = extract_name(character)

    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.

The 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.

The scenario plan should explicitly describe how the secondary character is going to ask the primary character the question.

To avoid inaccuracies, don't use real people as characters.

## Information:

Description of the character who is going to answer the question:
\"\"\"
Name: Elise Delacroix

Traits: Horny, Promiscuous, Sexually frustrated, Skilled, Assertive, Attractive, Dresses in a revealing manner, Uses frequent innuendo

Dialogue Examples:
Stranger: "What's your backstory?"
Elise 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?~"
Stranger: "What's your personality?"
Elise 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?"

Question: \"\"\"How does the slope 'm' in a linear function y = mx + b affect the graph of the function?\"\"\"
Answer: \"\"\"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.\"\"\"

Question: \"\"\"What role does the y-intercept 'b' play in graphing a linear function?\"\"\"
Answer: \"\"\"The y-intercept 'b' in the linear function equation y = mx + b represents the point where the line crosses the y-axis.\"\"\"

Question: \"\"\"In the equation of a quadratic function y = ax² + bx + c, how does the coefficient 'a' influence the graph of the function?\"\"\"
Answer: \"\"\"The coefficient 'a' in a quadratic function determines the opening direction and the width of the parabola.\"\"\"

Question: \"\"\"In what fields might you use linear and quadratic functions?\"\"\"
Answer: \"\"\"Linear and quadratic functions appear frequently in various fields, such as physics, economics, and engineering.\"\"\"

### Response:
## Scenario plan:
Step 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.
Step 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.
Step 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.
Step 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.
Step 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.

## Information:

Description of the character who is going to answer the question:
\"\"\"
Name: Hugo Martinez

Traits: 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

Dialogue Examples:
Stranger: "What's your backstory?"
Hugo 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?"
Stranger: "What's your personality?"
Hugo 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."
\"\"\"

Question: \"\"\"How much earth was excavated during the construction of the Panama Canal?\"\"\"
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.\"\"\"

Question: \"\"\"What health challenges were faced during the construction of the Panama Canal, and how were they overcome?\"\"\"
Answer: \"\"\"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.\"\"\"

### Response:
## Scenario plan:
Step 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.
Step 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.
Step 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.
Step 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.
Step 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.

## Information:

{format_qatuples(qatuples)}

Description of the character who is going to answer the question:
\"\"\"
{character}
\"\"\"

You don't need to add negative emotions and tension to the scenario if those don't gel nicely with the character's personality.

### Response:
## Scenario plan (be creative, and make sure all characters present fit in with the setting):
"""
    # 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
    completion = logic_llm(
        cot_prompt,
        max_tokens=8000,
        stop=["</s>", "# Input:"],
        echo=True,
        grammar=scenario_plan_many_tuples_grammar,
        temperature=1.5,  # min p settings, too inconsistent
        top_k=0,
        top_p=1,
        min_p=0.5,
    )["choices"][0]["text"]
    # print("COMPLETION:\n\n----------------------")
    # # print(completion)
    # print("\n------------------")

    # Extract plan
    response_pattern = re.compile(
        r"Scenario plan \(be creative, and make sure all characters present fit in with the setting\):\n(.+)",
        re.IGNORECASE | re.DOTALL,
    )
    generation = response_pattern.search(completion).group(1)
    # print("GENERATION:\n\n-------------------\n\n", generation)

    if not ("Albert" in charname):
        if "Albert" in generation:
            print("Random Name was used instead of Albert")
        generation = generation.replace("Albert", random_name())

    return generation.strip(), completion

if __name__ == "__main__":  # test
    logic_llm = Llama(
        model_path=LOGICAL_MODEL,
        n_gqa=8,
        offload_kqv=True,
        n_ctx=8000,
        n_gpu_layers=1000,
        rope_freq_scale=0.5,
        rope_scaling_type=1,
    )  # load the logical LLM and offload everything
    # Q0 is good q, bad a
    # q1 is good q, good a,
    # q2 is bad q, bad a,
    # q3 is iffy q, good a
    q_test = [
        (
            "Explain how our understanding of planetary motion has changed over time.",
            "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.",


import re
from .ensure_answer_consistent_grammar import ensure_answer_consistent_grammar
from llama_cpp import Llama
from .constants import LOGICAL_MODEL

# Answer vetting
# 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
def ensure_answer_consistent(qatuple, conv, logic_llm, permissive_mode=True):
    """
    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.
    """
    retries = 0

    # It's expensive to regen a conversation; so we check very thoroughly, and use a two-shot example. "Permissive mode" recommended

    # 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.
    while retries <= 4:
        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.

Following 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.

You 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.

Work step-by-step.

### Instruction:
Provided Question: Why is the sky blue?
Provided 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.

Conversation:
\"\"\"
Bob: "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."
Dave: "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."
\"\"\"

### Response:
## Reasoning and thought process:
Step 1. Understand the provided question: The question is straightforward and asks about the reason for the sky's blue color.
Step 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".
Step 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.
Step 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".
Step 5. Final judgement: Consistent.

### Instruction:
Provided Question: \"\"\"Why is the sky blue?\"\"\"
Provided 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.\"\"\"

Conversation:
\"\"\"
Bob: "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."
Dave: "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."
\"\"\"

### Response:
## Reasoning and thought process:
Step 1. Understand the provided question: The question is short and asks about the origin of the sky's blue color.
Step 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".
Step 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.
Step 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".
Step 5. Final judgement: Inconsistent.

### Instruction:
Provided Question: \"\"\"How much earth was excavated during the construction of the Panama Canal?\"\"\"
Provided 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.\"\"\"

Conversation:
\"\"\"
Mario 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?"
Carlos 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."
\"\"\"

### Response:
## Reasoning and thought process:
Step 1. Understand the provided question: The question asks about the volume of earth excavated during the construction of the Panama Canal.
Step 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".
Step 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."
Step 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".
Step 5. Final judgement: Consistent.

### Instruction:
Provided Question: \"\"\"What is the concept of 'projection' in psychology?\"\"\"
Provided Answer: \"\"\"Projection is a defense mechanism in psychology where an individual attributes their own unwanted thoughts, feelings, or motives to another person.\"\"\"

Conversation:
\"\"\"
Clara: "Hey John, I was reading about psychology and came across something interesting. Can you explain what 'projection' means in this context?"
Dr. 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."
\"\"\"

### Response:
## Reasoning and thought process:
Step 1. Understand the provided question: The question asks for the definition of 'projection' in the context of psychology.
Step 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".
Step 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."
Step 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".
Step 5. Final judgement: Inconsistent.

### Instruction:
Provided Question: \"\"\"What is the psychological phenomenon of 'cognitive dissonance'?\"\"\"
Provided Answer: \"\"\"Cognitive dissonance is a mental discomfort experienced by a person who holds two or more contradictory beliefs, values, or ideas simultaneously.\"\"\"

Conversation:
\"\"\"
Alice: "Hey, Jamal! You're studying psychology, right? Can you tell me what causes people to experience cognitive dissonance?"
Jamal: "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."
\"\"\"

### Response:
## Reasoning and thought process:
Step 1. Understand the provided question: The question specifically asks about the definition of 'cognitive dissonance'.
Step 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".
Step 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."
Step 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".
Step 5. Final judgement: Inconsistent.

### Instruction:
Provided Question: {qatuple[0]}
Provided Answer: {qatuple[1]}

Conversation:
\"\"\"
{conv}
\"\"\"

### Response:
## Reasoning and thought process (the conversation's answer must match the provided answer, unsummarized and unsimplified):
"""
        # print("DEBUG\n\n" + decision_prompt)
        try:
            completion = logic_llm(
                decision_prompt,
                max_tokens=4000,
                stop=["</s>", "# Input:"],
                echo=True,
                grammar=ensure_answer_consistent_grammar,
                temperature=0.2,
            )["choices"][0]["text"]
            completion_pattern = re.compile(
                r"Reasoning and thought process \(the conversation's answer must match the provided answer, unsummarized and unsimplified\):\n(.+)",
                re.DOTALL,
            )
            response = completion_pattern.search(completion).group(1).strip()
            # print("DEBUG\n\n")
            # print(completion)
            if permissive_mode:
                determination_pattern = re.compile(r"Final Judgement:(.+)", re.DOTALL)
                determination = determination_pattern.search(response).group(1).strip()
            else:
                determination = response
            print("\n\nDETERMINATION:\n------")
            print(determination)
            print("\n---------\n")
            if "inconsistent" in determination.lower():
                return (False, response)
            elif "consistent" in determination.lower():
                return (True, response)
            else:
                retries += 1
        except:
            retries += 1
            print(
                f"Something went catastrophically wrong with this one. Investigate! Here's the completion:\n{completion}"
            )

if __name__ == "__main__":  # test
    logic_llm = Llama(
        model_path=LOGICAL_MODEL,
        n_gqa=8,
        offload_kqv=True,
        n_ctx=4096,
        n_gpu_layers=1000,
    )  # load the logical LLM and offload everything
    # Q0 is good q, bad a
    # q1 is good q, good a,
    # q2 is bad q, bad a,
    # q3 is iffy q, good a
    q_test = [
        (
            "Explain how our understanding of planetary motion has changed over time.",
            "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.",
            "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.",
        ),
        (
            "Identify and explain changes in human understanding throughout history regarding the age of the Earth.",
            "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.",
            "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.",
        ),
        (
            "Using specific scientific principles, explain why we know Earth is approximately 8000 miles in diameter and how its distance from the sun varies.",
            "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.",
            "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
# ... truncated ...