{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "47e3b43b",
   "metadata": {},
   "source": [
    "This directory is retained purely for archival purposes and is no longer updated. Please see the newly [consolidated LangChain documentation](https://docs.langchain.com/oss/python/langgraph/overview) for the most current information and resources."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "425fb020-e864-40ce-a31f-8da40c73d14b",
   "metadata": {},
   "source": [
    "# Agentic RAG\n",
    "\n",
    "[Retrieval Agents](https://python.langchain.com/v0.2/docs/tutorials/qa_chat_history/#agents) are useful when we want to make decisions about whether to retrieve from an index.\n",
    "\n",
    "To implement a retrieval agent, we simple need to give an LLM access to a retriever tool.\n",
    "\n",
    "We can incorporate this into [LangGraph](https://langchain-ai.github.io/langgraph/).\n",
    "\n",
    "## Setup\n",
    "\n",
    "First, let's download the required packages and set our API keys:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "969fb438",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%capture --no-stderr\n",
    "%pip install -U --quiet langchain-community tiktoken langchain-openai langchainhub chromadb langchain langgraph langchain-text-splitters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e4958a8c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import getpass\n",
    "import os\n",
    "\n",
    "\n",
    "def _set_env(key: str):\n",
    "    if key not in os.environ:\n",
    "        os.environ[key] = getpass.getpass(f\"{key}:\")\n",
    "\n",
    "\n",
    "_set_env(\"OPENAI_API_KEY\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d07e8d4",
   "metadata": {},
   "source": [
    "<div class=\"admonition tip\">\n",
    "    <p class=\"admonition-title\">Set up <a href=\"https://smith.langchain.com\">LangSmith</a> for LangGraph development</p>\n",
    "    <p style=\"padding-top: 5px;\">\n",
    "        Sign up for LangSmith to quickly spot issues and improve the performance of your LangGraph projects. LangSmith lets you use trace data to debug, test, and monitor your LLM apps built with LangGraph — read more about how to get started <a href=\"https://docs.smith.langchain.com\">here</a>. \n",
    "    </p>\n",
    "</div>    "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c74e4532",
   "metadata": {},
   "source": [
    "## Retriever\n",
    "\n",
    "First, we index 3 blog posts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e50c9efe-4abe-42fa-b35a-05eeeede9ec6",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.document_loaders import WebBaseLoader\n",
    "from langchain_community.vectorstores import Chroma\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
    "\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",
    "docs = [WebBaseLoader(url).load() for url in urls]\n",
    "docs_list = [item for sublist in docs for item in sublist]\n",
    "\n",
    "text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(\n",
    "    chunk_size=100, chunk_overlap=50\n",
    ")\n",
    "doc_splits = text_splitter.split_documents(docs_list)\n",
    "\n",
    "# Add to vectorDB\n",
    "vectorstore = Chroma.from_documents(\n",
    "    documents=doc_splits,\n",
    "    collection_name=\"rag-chroma\",\n",
    "    embedding=OpenAIEmbeddings(),\n",
    ")\n",
    "retriever = vectorstore.as_retriever()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "225d2277-45b2-4ae8-a7d6-62b07fb4a002",
   "metadata": {},
   "source": [
    "Then we create a retriever tool."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "0b97bdd8-d7e3-444d-ac96-5ef4725f9048",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.tools.retriever import create_retriever_tool\n",
    "\n",
    "retriever_tool = create_retriever_tool(\n",
    "    retriever,\n",
    "    \"retrieve_blog_posts\",\n",
    "    \"Search and return information about Lilian Weng blog posts on LLM agents, prompt engineering, and adversarial attacks on LLMs.\",\n",
    ")\n",
    "\n",
    "tools = [retriever_tool]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe6e8f78-1ef7-42ad-b2bf-835ed5850553",
   "metadata": {},
   "source": [
    "## Agent State\n",
    " \n",
    "We will define a graph.\n",
    "\n",
    "A `state` object that it passes around to each node.\n",
    "\n",
    "Our state will be a list of `messages`.\n",
    "\n",
    "Each node in our graph will append to it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "0e378706-47d5-425a-8ba0-57b9acffbd0c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Annotated, Sequence, TypedDict\n",
    "\n",
    "from langchain_core.messages import BaseMessage\n",
    "\n",
    "from langgraph.graph.message import add_messages\n",
    "\n",
    "\n",
    "class AgentState(TypedDict):\n",
    "    # The add_messages function defines how an update should be processed\n",
    "    # Default is to replace. add_messages says \"append\"\n",
    "    messages: Annotated[Sequence[BaseMessage], add_messages]"
   ]
  },
  {
   "attachments": {
    "7ad1a116-28d7-473f-8cff-5f2efd0bf118.png": {
     "image/png": "[encoded data, 139508 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "dc949d42-8a34-4231-bff0-b8198975e2ce",
   "metadata": {},
   "source": [
    "## Nodes and Edges\n",
    "\n",
    "We can lay out an agentic RAG graph like this:\n",
    "\n",
    "* The state is a set of messages\n",
    "* Each node will update (append to) state\n",
    "* Conditional edges decide which node to visit next\n",
    "\n",
    "![Screenshot 2024-02-14 at 3.43.58 PM.png](attachment:7ad1a116-28d7-473f-8cff-5f2efd0bf118.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "278d1d83-dda6-4de4-bf8b-be9965c227fa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "********************Prompt[rlm/rag-prompt]********************\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.\n",
      "Question: \u001b[33;1m\u001b[1;3m{question}\u001b[0m \n",
      "Context: \u001b[33;1m\u001b[1;3m{context}\u001b[0m \n",
      "Answer:\n"
     ]
    }
   ],
   "source": [
    "from typing import Annotated, Literal, Sequence, TypedDict\n",
    "\n",
    "from langchain import hub\n",
    "from langchain_core.messages import BaseMessage, HumanMessage\n",
    "from langchain_core.output_parsers import StrOutputParser\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain_core.pydantic_v1 import BaseModel, Field\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "from langgraph.prebuilt import tools_condition\n",
    "\n",
    "### Edges\n",
    "\n",
    "\n",
    "def grade_documents(state) -> Literal[\"generate\", \"rewrite\"]:\n",
    "    \"\"\"\n",
    "    Determines whether the retrieved documents are relevant to the question.\n",
    "\n",
    "    Args:\n",
    "        state (messages): The current state\n",
    "\n",
    "    Returns:\n",
    "        str: A decision for whether the documents are relevant or not\n",
    "    \"\"\"\n",
    "\n",
    "    print(\"---CHECK RELEVANCE---\")\n",
    "\n",
    "    # Data model\n",
    "    class grade(BaseModel):\n",
    "        \"\"\"Binary score for relevance check.\"\"\"\n",
    "\n",
    "        binary_score: str = Field(description=\"Relevance score 'yes' or 'no'\")\n",
    "\n",
    "    # LLM\n",
    "    model = ChatOpenAI(temperature=0, model=\"gpt-4o\", streaming=True)\n",
    "\n",
    "    # LLM with tool and validation\n",
    "    llm_with_tool = model.with_structured_output(grade)\n",
    "\n",
    "    # Prompt\n",
    "    prompt = PromptTemplate(\n",
    "        template=\"\"\"You are a grader assessing relevance of a retrieved document to a user question. \\n \n",
    "        Here is the retrieved document: \\n\\n {context} \\n\\n\n",
    "        Here is the user question: {question} \\n\n",
    "        If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant. \\n\n",
    "        Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.\"\"\",\n",
    "        input_variables=[\"context\", \"question\"],\n",
    "    )\n",
    "\n",
    "    # Chain\n",
    "    chain = prompt | llm_with_tool\n",
    "\n",
    "    messages = state[\"messages\"]\n",
    "    last_message = messages[-1]\n",
    "\n",
    "    question = messages[0].content\n",
    "    docs = last_message.content\n",
    "\n",
    "    scored_result = chain.invoke({\"question\": question, \"context\": docs})\n",
    "\n",
    "    score = scored_result.binary_score\n",
    "\n",
    "    if score == \"yes\":\n",
    "        print(\"---DECISION: DOCS RELEVANT---\")\n",
    "        return \"generate\"\n",
    "\n",
    "    else:\n",
    "        print(\"---DECISION: DOCS NOT RELEVANT---\")\n",
    "        print(score)\n",
    "        return \"rewrite\"\n",
    "\n",
    "\n",
    "### Nodes\n",
    "\n",
    "\n",
    "def agent(state):\n",
    "    \"\"\"\n",
    "    Invokes the agent model to generate a response based on the current state. Given\n",
    "    the question, it will decide to retrieve using the retriever tool, or simply end.\n",
    "\n",
    "    Args:\n",
    "        state (messages): The current state\n",
    "\n",
    "    Returns:\n",
    "        dict: The updated state with the agent response appended to messages\n",
    "    \"\"\"\n",
    "    print(\"---CALL AGENT---\")\n",
    "    messages = state[\"messages\"]\n",
    "    model = ChatOpenAI(temperature=0, streaming=True, model=\"gpt-4-turbo\")\n",
    "    model = model.bind_tools(tools)\n",
    "    response = model.invoke(messages)\n",
    "    # We return a list, because this will get added to the existing list\n",
    "    return {\"messages\": [response]}\n",
    "\n",
    "\n",
    "def rewrite(state):\n",
    "    \"\"\"\n",
    "    Transform the query to produce a better question.\n",
    "\n",
    "    Args:\n",
    "        state (messages): The current state\n",
    "\n",
    "    Returns:\n",
    "        dict: The updated state with re-phrased question\n",
    "    \"\"\"\n",
    "\n",
    "    print(\"---TRANSFORM QUERY---\")\n",
    "    messages = state[\"messages\"]\n",
    "    question = messages[0].content\n",
    "\n",
    "    msg = [\n",
    "        HumanMessage(\n",
    "            content=f\"\"\" \\n \n",
    "    Look at the input and try to reason about the underlying semantic intent / meaning. \\n \n",
    "    Here is the initial question:\n",
    "    \\n ------- \\n\n",
    "    {question} \n",
    "    \\n ------- \\n\n",
    "    Formulate an improved question: \"\"\",\n",
    "        )\n",
    "    ]\n",
    "\n",
    "    # Grader\n",
    "    model = ChatOpenAI(temperature=0, model=\"gpt-4-0125-preview\", streaming=True)\n",
    "    response = model.invoke(msg)\n",
    "    return {\"messages\": [response]}\n",
    "\n",
    "\n",
    "def generate(state):\n",
    "    \"\"\"\n",
    "    Generate answer\n",
    "\n",
    "    Args:\n",
    "        state (messages): The current state\n",
    "\n",
    "    Returns:\n",
    "         dict: The updated state with re-phrased question\n",
    "    \"\"\"\n",
    "    print(\"---GENERATE---\")\n",
    "    messages = state[\"messages\"]\n",
    "    question = messages[0].content\n",
    "    last_message = messages[-1]\n",
    "\n",
    "    docs = last_message.content\n",
    "\n",
    "    # Prompt\n",
    "    prompt = hub.pull(\"rlm/rag-prompt\")\n",
    "\n",
    "    # LLM\n",
    "    llm = ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0, streaming=True)\n",
    "\n",
    "    # Post-processing\n",
    "    def format_docs(docs):\n",
    "        return \"\\n\\n\".join(doc.page_content for doc in docs)\n",
    "\n",
    "    # Chain\n",
    "    rag_chain = prompt | llm | StrOutputParser()\n",
    "\n",
    "    # Run\n",
    "    response = rag_chain.invoke({\"context\": docs, \"question\": question})\n",
    "    return {\"messages\": [response]}\n",
    "\n",
    "\n",
    "print(\"*\" * 20 + \"Prompt[rlm/rag-prompt]\" + \"*\" * 20)\n",
    "prompt = hub.pull(\"rlm/rag-prompt\").pretty_print()  # Show what the prompt looks like"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "955882ef-7467-48db-ae51-de441f2fc3a7",
   "metadata": {},
   "source": [
    "## Graph\n",
    "\n",
    "* Start with an agent, `call_model`\n",
    "* Agent make a decision to call a function\n",
    "* If so, then `action` to call tool (retriever)\n",
    "* Then call agent with the tool output added to messages (`state`)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "8718a37f-83c2-4f16-9850-e61e0f49c3d4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langgraph.graph import END, StateGraph, START\n",
    "from langgraph.prebuilt import ToolNode\n",
    "\n",
    "# Define a new graph\n",
    "workflow = StateGraph(AgentState)\n",
    "\n",
    "# Define the nodes we will cycle between\n",
    "workflow.add_node(\"agent\", agent)  # agent\n",
    "retrieve = ToolNode([retriever_tool])\n",
    "workflow.add_node(\"retrieve\", retrieve)  # retrieval\n",
    "workflow.add_node(\"rewrite\", rewrite)  # Re-writing the question\n",
    "workflow.add_node(\n",
    "    \"generate\", generate\n",
    ")  # Generating a response after we know the documents are relevant\n",
    "# Call agent node to decide to retrieve or not\n",
    "workflow.add_edge(START, \"agent\")\n",
    "\n",
    "# Decide whether to retrieve\n",
    "workflow.add_conditional_edges(\n",
    "    \"agent\",\n",
    "    # Assess agent decision\n",
    "    tools_condition,\n",
    "    {\n",
    "        # Translate the condition outputs to nodes in our graph\n",
    "        \"tools\": \"retrieve\",\n",
    "        END: END,\n",
    "    },\n",
    ")\n",
    "\n",
    "# Edges taken after the `action` node is called.\n",
    "workflow.add_conditional_edges(\n",
    "    \"retrieve\",\n",
    "    # Assess agent decision\n",
    "    grade_documents,\n",
    ")\n",
    "workflow.add_edge(\"generate\", END)\n",
    "workflow.add_edge(\"rewrite\", \"agent\")\n",
    "\n",
    "# Compile\n",
    "graph = workflow.compile()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "7b5a1d35",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/jpeg": "[encoded data, 22660 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "\n",
    "try:\n",
    "    display(Image(graph.get_graph(xray=True).draw_mermaid_png()))\n",
    "except Exception:\n",
    "    # This requires some extra dependencies and is optional\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "7649f05a-cb67-490d-b24a-74d41895139a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---CALL AGENT---\n",
      "\"Output from node 'agent':\"\n",
      "'---'\n",
      "{ 'messages': [ AIMessage(content='', additional_kwargs={'tool_calls': [{'index': 0, 'id': 'call_z36oPZN8l1UC6raxrebqc1bH', 'function': {'arguments': '{\"query\":\"types of agent memory\"}', 'name': 'retrieve_blog_posts'}, 'type': 'function'}]}, response_metadata={'finish_reason': 'tool_calls'}, id='run-2bad2518-8187-4d8f-8e23-2b9501becb6f-0', tool_calls=[{'name': 'retrieve_blog_posts', 'args': {'query': 'types of agent memory'}, 'id': 'call_z36oPZN8l1UC6raxrebqc1bH'}])]}\n",
      "'\\n---\\n'\n",
      "---CHECK RELEVANCE---\n",
      "---DECISION: DOCS RELEVANT---\n",
      "\"Output from node 'retrieve':\"\n",
      "'---'\n",
      "{ 'messages': [ ToolMessage(content='Table of Contents\\n\\n\\n\\nAgent System Overview\\n\\nComponent One: Planning\\n\\nTask Decomposition\\n\\nSelf-Reflection\\n\\n\\nComponent Two: Memory\\n\\nTypes of Memory\\n\\nMaximum Inner Product Search (MIPS)\\n\\n\\nComponent Three: Tool Use\\n\\nCase Studies\\n\\nScientific Discovery Agent\\n\\nGenerative Agents Simulation\\n\\nProof-of-Concept Examples\\n\\n\\nChallenges\\n\\nCitation\\n\\nReferences\\n\\nPlanning\\n\\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\\n\\n\\nMemory\\n\\nMemory\\n\\nShort-term memory: I would consider all the in-context learning (See Prompt Engineering) as utilizing short-term memory of the model to learn.\\nLong-term memory: This provides the agent with the capability to retain and recall (infinite) information over extended periods, often by leveraging an external vector store and fast retrieval.\\n\\n\\nTool use\\n\\nThe design of generative agents combines LLM with memory, planning and reflection mechanisms to enable agents to behave conditioned on past experience, as well as to interact with other agents.', name='retrieve_blog_posts', id='d815f283-868c-4660-a1c6-5f6e5373ca06', tool_call_id='call_z36oPZN8l1UC6raxrebqc1bH')]}\n",
      "'\\n---\\n'\n",
      "---GENERATE---\n",
      "\"Output from node 'generate':\"\n",
      "'---'\n",
      "{ 'messages': [ 'Lilian Weng discusses short-term and long-term memory in '\n",
      "                'agent systems. Short-term memory is used for in-context '\n",
      "                'learning, while long-term memory allows agents to retain and '\n",
      "                'recall information over extended periods.']}\n",
      "'\\n---\\n'\n"
     ]
    }
   ],
   "source": [
    "import pprint\n",
    "\n",
    "inputs = {\n",
    "    \"messages\": [\n",
    "        (\"user\", \"What does Lilian Weng say about the types of agent memory?\"),\n",
    "    ]\n",
    "}\n",
    "for output in graph.stream(inputs):\n",
    "    for key, value in output.items():\n",
    "        pprint.pprint(f\"Output from node '{key}':\")\n",
    "        pprint.pprint(\"---\")\n",
    "        pprint.pprint(value, indent=2, width=80, depth=None)\n",
    "    pprint.pprint(\"\\n---\\n\")"
   ]
  }
 ],
 "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.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
