# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/musique.multihop.ipynb.

# %% auto 0
__all__ = ['make_docs', 'BaselineMultiHop', 'benchmark']

# %% ../../nbs/musique.multihop.ipynb 3
from typing import Callable

import pandas as pd
from tqdm.auto import tqdm

from .eval import calculate_metrics, compare_answers

tqdm.pandas()

# %% ../../nbs/musique.multihop.ipynb 4
def make_docs(example):
    ps = example["paragraphs"]
    for p in ps:
        idx = p["idx"]
        title = p["title"]
        body = p["paragraph_text"]
        is_supporting = p["is_supporting"]
        text = f"# {title}\n{body}"
        yield dict(
            text=text,
            is_supporting=is_supporting,
            parent_id=example["id"],
            idx=idx,
        )

# %% ../../nbs/musique.multihop.ipynb 5
class BaselineMultiHop:
    def __init__(self, qa_func, retrieval_func):
        self.qa_func = qa_func
        self.retrieval_func = retrieval_func

    def _call(self, example) -> dict:
        docs = list(make_docs(example))
        
        # First question
        question1 = example["question_decomposition"][0]["question"]
        query1 = question1
        docs1 = self.retrieval_func(docs, query1)
        context1 = "\n".join(doc['text'] for doc in docs1)
        result1 = self.qa_func(context=context1, question=question1)
        answer1 = result1.get("answer")
        hop1 = {
            "question": question1,
            "query" : query1,
            "context": context1,
            "answer": answer1,
            "llm_output": result1,
        }

        # Second question
        if answer1.strip() == "N/A":
            return {
                "answer": "N/A",
                "hops": [hop1],
            }

        question2 = example["question_decomposition"][1]["question"]
        question2 = question2.replace("#1", answer1)
        query2 = question2
        docs2 = self.retrieval_func(docs, query2)
        context2 = "\n".join(doc['text'] for doc in docs2)
        result2 = self.qa_func(context=context2, question=question2)
        answer2 = result2.get("answer")
        hop2 = {
            "question": question2,
            "query": query2,
            "context": context2,
            "answer": answer2,
            "llm_output": result2,
        }

        return {'answer': answer2, 'hops': [hop1, hop2]}

    def __call__(self, example, ignore_errors: bool = False) -> dict:
        try:
            output = self._call(example)
        except Exception as exc:
            if ignore_errors:
                id = example["id"]
                print(f"Failed to answer the question {id}\n{exc}")
                output = dict(answer="N/A", hops=[{'error': str(exc)}])
            else:
                raise
        return output

# %% ../../nbs/musique.multihop.ipynb 6
def benchmark(
    dataf: pd.DataFrame,
    qa_func: Callable,
    retrieval_func: Callable,
    ignore_errors: bool = False,
) -> tuple[pd.DataFrame, dict]:
    pipeline = BaselineMultiHop(qa_func, retrieval_func)

    def process(example):
        output = pipeline(example, ignore_errors=ignore_errors)
        example["predicted_answer"] = output['answer']
        example["raw_output"] = output
        return example

    dataf = dataf.progress_apply(process, axis=1)
    dataf = compare_answers(dataf)
    scores = calculate_metrics(dataf)
    scores["fuzzy_match"] = dataf["fuzzy_match"].mean()
    return dataf, scores
