{
 "cells": [
  {
   "attachments": {
    "b77a7d3b-b28a-4dcf-9f1a-861f2f2c5f6c.png": {
     "image/png": "[encoded data, 67884 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "92ddc4f4-f7bf-4e0e-b5a5-5abd8a008b21",
   "metadata": {},
   "source": [
    "# Corrective RAG (CRAG) using local LLMs\n",
    "\n",
    "[Corrective-RAG (CRAG)](https://arxiv.org/abs/2401.15884) is a strategy for RAG that incorporates self-reflection / self-grading on retrieved documents. \n",
    "\n",
    "The paper follows this general flow:\n",
    "\n",
    "* If at least one document exceeds the threshold for `relevance`, then it proceeds to generation\n",
    "* If all documents fall below the `relevance` threshold or if the grader is unsure, then it uses web search to supplement retrieval\n",
    "* Before generation, it performs knowledge refinement of the search or retrieved documents\n",
    "* This partitions the document into `knowledge strips`\n",
    "* It grades each strip, and filters out irrelevant ones\n",
    "\n",
    "We will implement some of these ideas from scratch using [LangGraph](https://langchain-ai.github.io/langgraph/):\n",
    "\n",
    "* If *any* documents are irrelevant, we'll supplement retrieval with web search. \n",
    "* We'll skip the knowledge refinement, but this can be added back as a node if desired. \n",
    "* We'll use [Tavily Search](https://python.langchain.com/v0.2/docs/integrations/tools/tavily_search/) for web search.\n",
    "\n",
    "![Screenshot 2024-06-24 at 3.03.16 PM.png](attachment:b77a7d3b-b28a-4dcf-9f1a-861f2f2c5f6c.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ba4302f-09d9-4d2a-a18d-a6fd23704850",
   "metadata": {},
   "source": [
    "### Environment\n",
    "\n",
    "We'll use [Ollama](https://ollama.ai/) to access a local LLM:\n",
    "\n",
    "* Download [Ollama app](https://ollama.ai/).\n",
    "* Pull your model of choice, e.g.: `ollama pull llama3`\n",
    "\n",
    "We'll use [Tavily](https://python.langchain.com/v0.2/docs/integrations/tools/tavily_search/) for web search.\n",
    "\n",
    "We'll use a vectorstore with [Nomic local embeddings](https://blog.nomic.ai/posts/nomic-embed-text-v1) or, optionally, OpenAI embeddings.\n",
    "\n",
    "We'll use [LangSmith](https://docs.smith.langchain.com/) for tracing and evaluation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4a660963-bd3d-4c87-b2e4-b6e432055211",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%capture --no-stderr\n%pip install -U langchain_community tiktoken langchainhub scikit-learn langchain langgraph tavily-python  nomic[local] langchain-nomic langchain_openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68316ba0-854b-41e1-9af5-1f9e965946e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Search\n",
    "import os\n",
    "\n",
    "os.environ[\"TAVILY_API_KEY\"] = \"xxx\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0be68860-dded-481e-9fc7-a5042bf92c04",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Embedding (optional)\nos.environ[\"OPENAI_API_KEY\"] = \"xxx\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7248ab88-2b97-41eb-8dbb-4ea65525ed9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Tracing and testing (optional)\nos.environ[\"LANGCHAIN_API_KEY\"] = \"xxx\"\nos.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\nos.environ[\"LANGCHAIN_ENDPOINT\"] = \"https://api.smith.langchain.com\"\nos.environ[\"LANGCHAIN_PROJECT\"] = \"corrective-rag-agent-testing\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c059c3a3-7f01-4d46-8289-fde4c1b4155f",
   "metadata": {},
   "source": [
    "### LLM\n",
    "\n",
    "You can select from [Ollama LLMs](https://ollama.com/library)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2f4db331-c4d0-4c7c-a9a5-0bebc8a89c6c",
   "metadata": {},
   "outputs": [],
   "source": [
    "local_llm = \"llama3\"\nmodel_tested = \"llama3-8b\"\nmetadata = f\"CRAG, {model_tested}\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e2b6eed-3b3f-44b5-a34a-4ade1e94caf0",
   "metadata": {},
   "source": [
    "### Index\n",
    "\n",
    "Let's index 3 blog posts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "bb8b789b-475b-4e1b-9c66-03504c837830",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "USER_AGENT environment variable not set, consider setting it to identify your requests.\n"
     ]
    }
   ],
   "source": [
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain_community.document_loaders import WebBaseLoader\n",
    "from langchain_community.vectorstores import SKLearnVectorStore\n",
    "from langchain_nomic.embeddings import NomicEmbeddings  # local\n",
    "from langchain_openai import OpenAIEmbeddings  # api\n",
    "\n",
    "# List of URLs to load documents from\n",
    "urls = [\n",
    "    \"https://lilianweng.github.io/posts/2023-06-23-agent/\",\n",
    "    \"https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/\",\n",
    "    \"https://lilianweng.github.io/posts/2023-10-25-adv-attack-llm/\",\n",
    "]\n",
    "\n",
    "# Load documents from the URLs\n",
    "docs = [WebBaseLoader(url).load() for url in urls]\n",
    "docs_list = [item for sublist in docs for item in sublist]\n",
    "\n",
    "# Initialize a text splitter with specified chunk size and overlap\n",
    "text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(\n",
    "    chunk_size=250, chunk_overlap=0\n",
    ")\n",
    "\n",
    "# Split the documents into chunks\n",
    "doc_splits = text_splitter.split_documents(docs_list)\n",
    "\n",
    "# Embedding\n",
    "\"\"\"\n",
    "embedding=NomicEmbeddings(\n",
    "    model=\"nomic-embed-text-v1.5\",\n",
    "    inference_mode=\"local\",\n",
    ")\n",
    "\"\"\"\n",
    "embedding = OpenAIEmbeddings()\n",
    "\n",
    "# Add the document chunks to the \"vector store\"\n",
    "vectorstore = SKLearnVectorStore.from_documents(\n",
    "    documents=doc_splits,\n",
    "    embedding=embedding,\n",
    ")\n",
    "retriever = vectorstore.as_retriever(k=4)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "fe7fd10a-f64a-48de-a116-6d5890def1af",
   "metadata": {},
   "source": [
    "### Tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "0e75c029-6c10-47c7-871c-1f4932b25309",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'score': '1'}\n"
     ]
    }
   ],
   "source": [
    "### Retrieval Grader\n\nfrom langchain.prompts import PromptTemplate\nfrom langchain_community.chat_models import ChatOllama\nfrom langchain_core.output_parsers import JsonOutputParser\nfrom langchain_mistralai.chat_models import ChatMistralAI\n\n# LLM\nllm = ChatOllama(model=local_llm, format=\"json\", temperature=0)\n\n# Prompt\nprompt = PromptTemplate(\n    template=\"\"\"You are a teacher grading a quiz. You will be given: \n    1/ a QUESTION\n    2/ A FACT provided by the student\n    \n    You are grading RELEVANCE RECALL:\n    A score of 1 means that ANY of the statements in the FACT are relevant to the QUESTION. \n    A score of 0 means that NONE of the statements in the FACT are relevant to the QUESTION. \n    1 is the highest (best) score. 0 is the lowest score you can give. \n    \n    Explain your reasoning in a step-by-step manner. Ensure your reasoning and conclusion are correct. \n    \n    Avoid simply stating the correct answer at the outset.\n    \n    Question: {question} \\n\n    Fact: \\n\\n {documents} \\n\\n\n    \n    Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question. \\n\n    Provide the binary score as a JSON with a single key 'score' and no premable or explanation.\n    \"\"\",\n    input_variables=[\"question\", \"documents\"],\n)\n\nretrieval_grader = prompt | llm | JsonOutputParser()\nquestion = \"agent memory\"\ndocs = retriever.invoke(question)\ndoc_txt = docs[1].page_content\nprint(retrieval_grader.invoke({\"question\": question, \"documents\": doc_txt}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "dad03302-bd93-43fc-949e-af51a3298cfa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The document mentions \"memory stream\" which is a long-term memory module that records a comprehensive list of agents' experience in natural language. It also discusses short-term memory and long-term memory, with the latter providing the agent with the capability to retain and recall information over extended periods. Additionally, it mentions planning and reflection mechanisms that enable agents to behave conditioned on past experience.\n"
     ]
    }
   ],
   "source": [
    "### Generate\n\nfrom langchain_core.output_parsers import StrOutputParser\n\n# Prompt\nprompt = PromptTemplate(\n    template=\"\"\"You are an assistant for question-answering tasks. \n    \n    Use the following documents to answer the question. \n    \n    If you don't know the answer, just say that you don't know. \n    \n    Use three sentences maximum and keep the answer concise:\n    Question: {question} \n    Documents: {documents} \n    Answer: \n    \"\"\",\n    input_variables=[\"question\", \"documents\"],\n)\n\n# LLM\nllm = ChatOllama(model=local_llm, temperature=0)\n\n# Chain\nrag_chain = prompt | llm | StrOutputParser()\n\n# Run\ngeneration = rag_chain.invoke({\"documents\": docs, \"question\": question})\nprint(generation)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b36a2f36-bc5f-408d-a5e8-3fa203c233f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "### Search\n\nfrom langchain_community.tools.tavily_search import TavilySearchResults\n\nweb_search_tool = TavilySearchResults(k=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3421cf0-9067-43fe-8681-0d3189d15dd3",
   "metadata": {},
   "source": [
    "### Graph \n",
    "\n",
    "Here we'll explicitly define the majority of the control flow, only using an LLM to define a single branch point following grading."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "10028794-2fbc-43f9-aa4c-7fe3abd69c1e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 20092 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from typing import List\nfrom typing_extensions import TypedDict\nfrom IPython.display import Image, display\nfrom langchain.schema import Document\nfrom langgraph.graph import START, END, StateGraph\n\n\nclass GraphState(TypedDict):\n    \"\"\"\n    Represents the state of our graph.\n\n    Attributes:\n        question: question\n        generation: LLM generation\n        search: whether to add search\n        documents: list of documents\n    \"\"\"\n\n    question: str\n    generation: str\n    search: str\n    documents: List[str]\n    steps: List[str]\n\n\ndef retrieve(state):\n    \"\"\"\n    Retrieve documents\n\n    Args:\n        state (dict): The current graph state\n\n    Returns:\n        state (dict): New key added to state, documents, that contains retrieved documents\n    \"\"\"\n    question = state[\"question\"]\n    documents = retriever.invoke(question)\n    steps = state[\"steps\"]\n    steps.append(\"retrieve_documents\")\n    return {\"documents\": documents, \"question\": question, \"steps\": steps}\n\n\ndef generate(state):\n    \"\"\"\n    Generate answer\n\n    Args:\n        state (dict): The current graph state\n\n    Returns:\n        state (dict): New key added to state, generation, that contains LLM generation\n    \"\"\"\n\n    question = state[\"question\"]\n    documents = state[\"documents\"]\n    generation = rag_chain.invoke({\"documents\": documents, \"question\": question})\n    steps = state[\"steps\"]\n    steps.append(\"generate_answer\")\n    return {\n        \"documents\": documents,\n        \"question\": question,\n        \"generation\": generation,\n        \"steps\": steps,\n    }\n\n\ndef grade_documents(state):\n    \"\"\"\n    Determines whether the retrieved documents are relevant to the question.\n\n    Args:\n        state (dict): The current graph state\n\n    Returns:\n        state (dict): Updates documents key with only filtered relevant documents\n    \"\"\"\n\n    question = state[\"question\"]\n    documents = state[\"documents\"]\n    steps = state[\"steps\"]\n    steps.append(\"grade_document_retrieval\")\n    filtered_docs = []\n    search = \"No\"\n    for d in documents:\n        score = retrieval_grader.invoke(\n            {\"question\": question, \"documents\": d.page_content}\n        )\n        grade = score[\"score\"]\n        if grade == \"yes\":\n            filtered_docs.append(d)\n        else:\n            search = \"Yes\"\n            continue\n    return {\n        \"documents\": filtered_docs,\n        \"question\": question,\n        \"search\": search,\n        \"steps\": steps,\n    }\n\n\ndef web_search(state):\n    \"\"\"\n    Web search based on the re-phrased question.\n\n    Args:\n        state (dict): The current graph state\n\n    Returns:\n        state (dict): Updates documents key with appended web results\n    \"\"\"\n\n    question = state[\"question\"]\n    documents = state.get(\"documents\", [])\n    steps = state[\"steps\"]\n    steps.append(\"web_search\")\n    web_results = web_search_tool.invoke({\"query\": question})\n    documents.extend(\n        [\n            Document(page_content=d[\"content\"], metadata={\"url\": d[\"url\"]})\n            for d in web_results\n        ]\n    )\n    return {\"documents\": documents, \"question\": question, \"steps\": steps}\n\n\ndef decide_to_generate(state):\n    \"\"\"\n    Determines whether to generate an answer, or re-generate a question.\n\n    Args:\n        state (dict): The current graph state\n\n    Returns:\n        str: Binary decision for next node to call\n    \"\"\"\n    search = state[\"search\"]\n    if search == \"Yes\":\n        return \"search\"\n    else:\n        return \"generate\"\n\n\n# Graph\nworkflow = StateGraph(GraphState)\n\n# Define the nodes\nworkflow.add_node(\"retrieve\", retrieve)  # retrieve\nworkflow.add_node(\"grade_documents\", grade_documents)  # grade documents\nworkflow.add_node(\"generate\", generate)  # generatae\nworkflow.add_node(\"web_search\", web_search)  # web search\n\n# Build graph\nworkflow.add_edge(START, \"retrieve\")\nworkflow.add_edge(\"retrieve\", \"grade_documents\")\nworkflow.add_conditional_edges(\n    \"grade_documents\",\n    decide_to_generate,\n    {\n        \"search\": \"web_search\",\n        \"generate\": \"generate\",\n    },\n)\nworkflow.add_edge(\"web_search\", \"generate\")\nworkflow.add_edge(\"generate\", END)\n\ncustom_graph = workflow.compile()\n\ndisplay(Image(custom_graph.get_graph(xray=True).draw_mermaid_png()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "447d1333-082d-479a-a6fa-0ac0df78bb9d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'response': 'According to the documents, there are two types of agent memory:\\n\\n* Short-term memory (STM): This is a data structure that holds information temporarily and allows the agent to process it when needed.\\n* Long-term memory (LTM): This provides the agent with the capability to retain and recall information over extended periods.\\n\\nThese types of memories allow the agent to learn, reason, and make decisions.',\n",
       " 'steps': ['retrieve_documents',\n",
       "  'grade_document_retrieval',\n",
       "  'web_search',\n",
       "  'generate_answer']}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import uuid\n",
    "\n",
    "\n",
    "def predict_custom_agent_local_answer(example: dict):\n",
    "    config = {\"configurable\": {\"thread_id\": str(uuid.uuid4())}}\n",
    "    state_dict = custom_graph.invoke(\n",
    "        {\"question\": example[\"input\"], \"steps\": []}, config\n",
    "    )\n",
    "    return {\"response\": state_dict[\"generation\"], \"steps\": state_dict[\"steps\"]}\n",
    "\n",
    "\n",
    "example = {\"input\": \"What are the types of agent memory?\"}\n",
    "response = predict_custom_agent_local_answer(example)\n",
    "response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "91325c88-ec77-4c79-8a77-cb2e2842bcd4",
   "metadata": {},
   "source": [
    "Trace: \n",
    "\n",
    "https://smith.langchain.com/public/88e7579e-2571-4cf6-98d2-1f9ce3359967/r"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b80d5da-f698-40d2-a2fb-4eac89e35350",
   "metadata": {},
   "source": [
    "## Evaluation\n",
    "\n",
    "Now we've defined two different agent architectures that do roughly the same thing!\n",
    "\n",
    "We can evaluate them. See our [conceptual guide](https://docs.smith.langchain.com/concepts/evaluation#agents) for context on agent evaluation.\n",
    "\n",
    "### Response\n",
    "\n",
    "First, we can assess how well [our agent performs on a set of question-answer pairs](https://docs.smith.langchain.com/tutorials/Developers/agents#response-evaluation).\n",
    "\n",
    "We'll create a dataset and save it in LangSmith."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b83706ac-724b-46b1-9f08-66e6c4fac742",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langsmith import Client\n\nclient = Client()\n\n# Create a dataset\nexamples = [\n    (\n        \"How does the ReAct agent use self-reflection? \",\n        \"ReAct integrates reasoning and acting, performing actions - such tools like Wikipedia search API - and then observing / reasoning about the tool outputs.\",\n    ),\n    (\n        \"What are the types of biases that can arise with few-shot prompting?\",\n        \"The biases that can arise with few-shot prompting include (1) Majority label bias, (2) Recency bias, and (3) Common token bias.\",\n    ),\n    (\n        \"What are five types of adversarial attacks?\",\n        \"Five types of adversarial attacks are (1) Token manipulation, (2) Gradient based attack, (3) Jailbreak prompting, (4) Human red-teaming, (5) Model red-teaming.\",\n    ),\n    (\n        \"Who did the Chicago Bears draft first in the 2024 NFL draft”?\",\n        \"The Chicago Bears drafted Caleb Williams first in the 2024 NFL draft.\",\n    ),\n    (\"Who won the 2024 NBA finals?\", \"The Boston Celtics on the 2024 NBA finals\"),\n]\n\n# Save it\ndataset_name = \"Corrective RAG Agent Testing\"\nif not client.has_dataset(dataset_name=dataset_name):\n    dataset = client.create_dataset(dataset_name=dataset_name)\n    inputs, outputs = zip(\n        *[({\"input\": text}, {\"output\": label}) for text, label in examples]\n    )\n    client.create_examples(inputs=inputs, outputs=outputs, dataset_id=dataset.id)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a23f6bc0-2d03-488c-8f4b-747c93876788",
   "metadata": {},
   "source": [
    "Now, we'll use an `LLM as a grader` to compare both agent responses to our ground truth reference answer.\n",
    "\n",
    "[Here](https://smith.langchain.com/hub/rlm/rag-answer-vs-reference) is the default prompt that we can use.\n",
    "\n",
    "We'll use `gpt-4o` as our LLM grader.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "0a63776c-f9cd-46ce-b8cf-95c066dc5b06",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# Grade prompt\n",
    "grade_prompt_answer_accuracy = hub.pull(\"langchain-ai/rag-answer-vs-reference\")\n",
    "\n",
    "\n",
    "def answer_evaluator(run, example) -> dict:\n",
    "    \"\"\"\n",
    "    A simple evaluator for RAG answer accuracy\n",
    "    \"\"\"\n",
    "\n",
    "    # Get the question, the ground truth reference answer, RAG chain answer prediction\n",
    "    input_question = example.inputs[\"input\"]\n",
    "    reference = example.outputs[\"output\"]\n",
    "    prediction = run.outputs[\"response\"]\n",
    "\n",
    "    # Define an LLM grader\n",
    "    llm = ChatOpenAI(model=\"gpt-4o\", temperature=0)\n",
    "    answer_grader = grade_prompt_answer_accuracy | llm\n",
    "\n",
    "    # Run evaluator\n",
    "    score = answer_grader.invoke(\n",
    "        {\n",
    "            \"question\": input_question,\n",
    "            \"correct_answer\": reference,\n",
    "            \"student_answer\": prediction,\n",
    "        }\n",
    "    )\n",
    "    score = score[\"Score\"]\n",
    "    return {\"key\": \"answer_v_reference_score\", \"score\": score}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "960f1a01-7f8c-429f-83d0-052cea47b32b",
   "metadata": {},
   "source": [
    "### Trajectory\n",
    "\n",
    "Second, [we can assess the list of tool calls](https://docs.smith.langchain.com/tutorials/Developers/agents#trajectory) that each agent makes relative to expected trajectories.\n",
    "\n",
    "This evaluates the specific reasoning traces taken by our agents!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "deb28175-27a1-4afc-9747-2983e87fc881",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langsmith.schemas import Example, Run\n",
    "\n",
    "# Reasoning traces that we expect the agents to take\n",
    "expected_trajectory_1 = [\n",
    "    \"retrieve_documents\",\n",
    "    \"grade_document_retrieval\",\n",
    "    \"web_search\",\n",
    "    \"generate_answer\",\n",
    "]\n",
    "expected_trajectory_2 = [\n",
    "    \"retrieve_documents\",\n",
    "    \"grade_document_retrieval\",\n",
    "    \"generate_answer\",\n",
    "]\n",
    "\n",
    "\n",
    "def check_trajectory_react(root_run: Run, example: Example) -> dict:\n",
    "    \"\"\"\n",
    "    Check if all expected tools are called in exact order and without any additional tool calls.\n",
    "    \"\"\"\n",
    "    messages = root_run.outputs[\"messages\"]\n",
    "    tool_calls = find_tool_calls_react(messages)\n",
    "    print(f\"Tool calls ReAct agent: {tool_calls}\")\n",
    "    if tool_calls == expected_trajectory_1 or tool_calls == expected_trajectory_2:\n",
    "        score = 1\n",
    "    else:\n",
    "        score = 0\n",
    "\n",
    "    return {\"score\": int(score), \"key\": \"tool_calls_in_exact_order\"}\n",
    "\n",
    "\n",
    "def check_trajectory_custom(root_run: Run, example: Example) -> dict:\n",
    "    \"\"\"\n",
    "    Check if all expected tools are called in exact order and without any additional tool calls.\n",
    "    \"\"\"\n",
    "    tool_calls = root_run.outputs[\"steps\"]\n",
    "    print(f\"Tool calls custom agent: {tool_calls}\")\n",
    "    if tool_calls == expected_trajectory_1 or tool_calls == expected_trajectory_2:\n",
    "        score = 1\n",
    "    else:\n",
    "        score = 0\n",
    "\n",
    "    return {\"score\": int(score), \"key\": \"tool_calls_in_exact_order\"}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "909b097d-cda1-45ff-8210-afeb2d18b8ae",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "View the evaluation results for experiment: 'custom-agent-llama3-8b-answer-and-tool-use-d6006159' at:\n",
      "https://smith.langchain.com/o/1fa8b1f4-fcb9-4072-9aa9-983e35ad61b8/datasets/a8b9273b-ca33-4e2f-9f69-9bbc37f6f51b/compare?selectedSessions=83c60822-ef22-43e8-ac85-4488af279c6f\n",
      "\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "529952314cd34ac1bb115840536921c3",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "0it [00:00, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n",
      "Tool calls custom agent: ['retrieve_documents', 'grade_document_retrieval', 'web_search', 'generate_answer']\n"
     ]
    }
   ],
   "source": [
    "from langsmith.evaluation import evaluate\n",
    "\n",
    "experiment_prefix = f\"custom-agent-{model_tested}\"\n",
    "experiment_results = evaluate(\n",
    "    predict_custom_agent_local_answer,\n",
    "    data=dataset_name,\n",
    "    evaluators=[answer_evaluator, check_trajectory_custom],\n",
    "    experiment_prefix=experiment_prefix + \"-answer-and-tool-use\",\n",
    "    num_repetitions=3,\n",
    "    max_concurrency=1,  # Use when running locally\n",
    "    metadata={\"version\": metadata},\n",
    ")"
   ]
  },
  {
   "attachments": {
    "80e86604-7734-4aeb-a200-d1413870c3cb.png": {
     "image/png": "[encoded data, 91956 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "47c38cd3-2c31-48c4-8281-bd9e1f7b2830",
   "metadata": {},
   "source": [
    "We can see the results benchmarked against `GPT-4o` and `Llama-3-70b` using `Custom` agent (as shown here) and ReAct.\n",
    "\n",
    "![Screenshot 2024-06-24 at 4.14.04 PM.png](attachment:80e86604-7734-4aeb-a200-d1413870c3cb.png)\n",
    "\n",
    "The `local custom agent` performs well in terms of tool calling reliability: it follows the expected reasoning traces.\n",
    "\n",
    "However, the answer accuracy performance lags the larger models with `custom agent` implementations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79295798-0181-417e-abad-11dddb6ff05e",
   "metadata": {},
   "outputs": [],
   "source": [
    ""
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
