{ "cells": [ { "cell_type": "markdown", "id": "55ec4c0c-65cc-4816-86df-c40b55f9c2d5", "metadata": {}, "source": [ "### Tracing\n", "\n", "Optionally, use [LangSmith](https://docs.smith.langchain.com/) for tracing (shown at bottom)" ] }, { "cell_type": "code", "execution_count": 1, "id": "68fed362-871a-46df-8ba0-579797ff2e9c", "metadata": {}, "outputs": [], "source": [ "# os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n", "# os.environ[\"LANGCHAIN_ENDPOINT\"] = \"https://api.smith.langchain.com\"\n", "# os.environ[\"LANGCHAIN_API_KEY\"] = \"\"" ] }, { "cell_type": "markdown", "id": "c059c3a3-7f01-4d46-8289-fde4c1b4155f", "metadata": {}, "source": [ "## Configuration\n", "\n", "Decide to run locally and select LLM to use with Ollama." ] }, { "cell_type": "code", "execution_count": 2, "id": "2f4db331-c4d0-4c7c-a9a5-0bebc8a89c6c", "metadata": {}, "outputs": [], "source": [ "run_local = \"Yes\"\n", "local_llm = \"llama2-13b\"" ] }, { "cell_type": "code", "execution_count": 3, "id": "632ae5bb-8b63-43a8-bfb8-da05d1c1bde4", "metadata": {}, "outputs": [], "source": [ "# !pip install langchain_nomic" ] }, { "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": 5, "id": "d3f4d43f-eb93-4f7d-9cab-1ab3c7de6c6a", "metadata": {}, "outputs": [], "source": [ "# Download PDF file\n", "import os\n", "import requests\n", "import fitz # (pymupdf, found this is better than pypdf for our use case, note: licence is AGPL-3.0, keep that in mind if you want to use any code commercially)\n", "from tqdm.auto import tqdm\n", "# Get PDF document\n", "\n", "# Download PDF if it doesn't already exist\n", "if not os.path.exists(pdf_path):\n", " print(\"File doesn't exist, downloading...\")\n", "\n", " # The URL of the PDF you want to download\n", " url = \"https://pressbooks.oer.hawaii.edu/humannutrition2/open/download?type=pdf\"\n", "\n", " # The local filename to save the downloaded file\n", " filename = pdf_path\n", "\n", " # Send a GET request to the URL\n", " response = requests.get(url)\n", "\n", " # Check if the request was successful\n", " if response.status_code == 200:\n", " # Open a file in binary write mode and save the content to it\n", " with open(filename, \"wb\") as file:\n", " file.write(response.content)\n", " print(f\"The file has been downloaded and saved as {filename}\")\n", " else:\n", " print(f\"Failed to download the file. Status code: {response.status_code}\")\n", "else:\n", " print(f\"File {pdf_path} exists.\")" ] }, { "cell_type": "code", "execution_count": null, "id": "a5debec4-983b-462e-b871-81b8cf3dd33b", "metadata": {}, "outputs": [], "source": [ "# # Requires !pip install PyMuPDF, see: https://github.com/pymupdf/pymupdf\n", "# import fitz # (pymupdf, found this is better than pypdf for our use case, note: licence is AGPL-3.0, keep that in mind if you want to use any code commercially)\n", "# from tqdm.auto import tqdm # for progress bars, requires !pip install tqdm \n", "\n", "# def text_formatter(text: str) -> str:\n", "# \"\"\"Performs minor formatting on text.\"\"\"\n", "# cleaned_text = text.replace(\"\\n\", \" \").strip() # note: this might be different for each doc (best to experiment)\n", "\n", "# # Other potential text formatting functions can go here\n", "# return cleaned_text\n", "\n", "# # Open PDF and get lines/pages\n", "# # Note: this only focuses on text, rather than images/figures etc\n", "# def open_and_read_pdf(pdf_path: str) -> list[dict]:\n", "# \"\"\"\n", "# Opens a PDF file, reads its text content page by page, and collects statistics.\n", "\n", "# Parameters:\n", "# pdf_path (str): The file path to the PDF document to be opened and read.\n", "\n", "# Returns:\n", "# list[dict]: A list of dictionaries, each containing the page number\n", "# (adjusted), character count, word count, sentence count, token count, and the extracted text\n", "# for each page.\n", "# \"\"\"\n", "# doc = fitz.open(pdf_path) # open a document\n", "# pages_and_texts = \"\"\n", "# for page_number, page in tqdm(enumerate(doc)): # iterate the document pages\n", "# text = page.get_text() # get plain text encoded as UTF-8\n", "# text = text_formatter(text)\n", "# pages_and_texts+=text\n", "# # pages_and_texts.append({\"page_number\": page_number - 41, # adjust page numbers since our PDF starts on page 42\n", "# # \"page_char_count\": len(text),\n", "# # \"page_word_count\": len(text.split(\" \")),\n", "# # \"page_sentence_count_raw\": len(text.split(\". \")),\n", "# # \"page_token_count\": len(text) / 4, # 1 token = ~4 chars, see: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them\n", "# # \"text\": text})\n", "# return pages_and_texts\n", "\n", "# pages_and_texts = open_and_read_pdf(pdf_path=pdf_path)\n", "# pages_and_texts[:100]" ] }, { "cell_type": "code", "execution_count": null, "id": "c19560ff-2808-406a-aa70-b8c4d303121e", "metadata": {}, "outputs": [], "source": [ "# !pip install fastembed" ] }, { "cell_type": "code", "execution_count": null, "id": "bb8b789b-475b-4e1b-9c66-03504c837830", "metadata": {}, "outputs": [], "source": [ "# from langchain.text_splitter import RecursiveCharacterTextSplitter,CharacterTextSplitter\n", "# from langchain_community.document_loaders import WebBaseLoader\n", "# from langchain_community.vectorstores import Chroma\n", "# from langchain_mistralai import MistralAIEmbeddings\n", "# # from langchain_nomic.embeddings import NomicEmbeddings\n", "# from langchain_community.embeddings import OllamaEmbeddings\n", "# # ollama_emb = \n", "# # Load\n", "# from langchain_community.embeddings.fastembed import FastEmbedEmbeddings\n", "\n", "# # # Split\n", "# # text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(\n", "# # chunk_size=500, chunk_overlap=100\n", "# # )\n", "\n", "# text_splitter = CharacterTextSplitter(\n", "# chunk_size=1000,\n", "# chunk_overlap=200,\n", "# separator=\"\\n\"\n", "# )\n", "\n", "\n", "# all_splits = text_splitter.create_documents(pages_and_texts)\n", "\n", "# # Embed and index\n", "# if run_local == \"Yes\":\n", "# embedding = FastEmbedEmbeddings(model_name=\"BAAI/bge-base-en-v1.5\",device=\"cuda\")\n", "\n", "# else:\n", "# embedding = MistralAIEmbeddings(mistral_api_key=mistral_api_key)\n", "\n", "# # Index\n", "# vectorstore = Chroma.from_documents(\n", "# documents=all_splits,\n", "# collection_name=\"rag-chroma\",\n", "# embedding=embedding,\n", "# )\n", "# retriever = vectorstore.as_retriever()" ] }, { "cell_type": "code", "execution_count": null, "id": "bc1efd13-576f-4bae-996b-81dd8f8863df", "metadata": {}, "outputs": [], "source": [ "import fitz # PyMuPDF\n", "def text_formatter(text: str) -> str:\n", " \"\"\"Performs minor formatting on text.\"\"\"\n", " cleaned_text = text.replace(\"\\n\", \" \").strip() # note: this might be different for each doc (best to experiment)\n", "\n", " # Other potential text formatting functions can go here\n", " return cleaned_text\n", "def extract_text_from_pdf(pdf_path):\n", " document = fitz.open(pdf_path)\n", " pages_and_texts = []\n", " for page_num in range(len(document)):\n", " page = document.load_page(page_num)\n", " text = page.get_text(\"text\")\n", " text = text_formatter(text)\n", " pages_and_texts.append(text)\n", " return pages_and_texts\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "15dcb261-2197-4207-bf1d-e9d9ddcc007a", "metadata": {}, "outputs": [], "source": [ "pages_and_texts = basic+surgery" ] }, { "cell_type": "code", "execution_count": null, "id": "4e57c3b2-060c-4f0d-aae4-d052a202ea5e", "metadata": {}, "outputs": [], "source": [ "from langchain.text_splitter import RecursiveCharacterTextSplitter, CharacterTextSplitter\n", "from langchain_community.document_loaders import WebBaseLoader\n", "from langchain_community.vectorstores import Chroma\n", "from sentence_transformers import SentenceTransformer\n", "import torch\n", "\n", "# Define your text splitter\n", "text_splitter = CharacterTextSplitter(\n", " chunk_size=1000,\n", " chunk_overlap=200,\n", " separator=\" \"\n", ")\n", "\n", "# Assuming 'pages_and_texts' is your list of documents' text\n", "all_splits = text_splitter.create_documents(pages_and_texts)\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "dcf9e2f5-009b-4320-ad0f-23b0fd231072", "metadata": {}, "outputs": [], "source": [ "len(all_splits)" ] }, { "cell_type": "code", "execution_count": null, "id": "0b37fc4b-ee00-4523-86d6-e9657e2b8c91", "metadata": {}, "outputs": [], "source": [ "# !pip install langchain_openai" ] }, { "cell_type": "code", "execution_count": null, "id": "cdc20558-395f-4330-83f8-13070e377526", "metadata": {}, "outputs": [], "source": [ "from langchain_community.embeddings.sentence_transformer import (\n", " SentenceTransformerEmbeddings,\n", ")\n", "\n", "if run_local == \"Yes\":\n", " embedding = SentenceTransformerEmbeddings(model_name=\"BAAI/bge-base-en-v1.5\")\n", "# from langchain_openai import OpenAIEmbeddings\n", "\n", "# embedding = OpenAIEmbeddings(api_key=\"sk-proj-KQ4DlWOH3c1mSlTGHXbqT3BlbkFJ3TxJ8nsKKJyk98rFXx1x\")\n", "else:\n", " # Handle the case when not running locally\n", " embedding = MistralAIEmbeddings(mistral_api_key=mistral_api_key)\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "d43b5ba7-c2e7-45b1-bcdd-156e53ef9f68", "metadata": {}, "outputs": [], "source": [ "all_splits[156]" ] }, { "cell_type": "code", "execution_count": null, "id": "9bb98da2-e40d-46e7-be5b-0f85a801b9db", "metadata": {}, "outputs": [], "source": [ "from tqdm.notebook import tqdm\n", "\n", "# Embed the documents with progress tracking\n", "embedded_docs = []\n", "# for doc in tqdm(all_splits, desc=\"Embedding Documents\"):\n", "# embedded_docs.append(embedding.embed_documents([doc.page_content])[0])\n", "\n", " # # Embed and index\n", "# if run_local == \"Yes\":\n", "# embedding = FastEmbedEmbeddings(model_name=\"BAAI/bge-base-en-v1.5\",device=\"cuda\")\n", "\n", "# else:\n", "# embedding = MistralAIEmbeddings(mistral_api_key=mistral_api_key)\n", "\n", "# # Index\n", "# vectorstore = Chroma.from_documents(\n", "# documents=all_splits,\n", "# collection_name=\"rag-chroma\",\n", "# embedding=embedding,\n", "# )\n", "# retriever = vectorstore.as_retriever()\n", " \n", " \n", "# Store in Chroma vector store\n", "vectorstore = Chroma.from_documents(\n", " embedding=embedding,\n", " documents=all_splits,\n", " collection_name=\"rag-chroma\"\n", ")\n", "\n", "# Use the vector store as a retriever\n" ] }, { "cell_type": "code", "execution_count": null, "id": "f008f94e-5f17-4596-a9e3-64cc6a153249", "metadata": {}, "outputs": [], "source": [ "# # Embed the documents\n", "# embedded_docs = embedding.embed_documents([doc.page_content for doc in all_splits])\n", "\n", "# # Store in Chroma vector store\n", "# vectorstore = Chroma.from_embeddings(\n", "# embeddings=embedded_docs,\n", "# documents=all_splits,\n", "# collection_name=\"rag-chroma\"\n", "# )\n", "\n", "# # Use the vector store as a retriever\n", "# retriever = vectorstore.as_retriever()\n", "\n", "retriever = vectorstore.as_retriever(search_kwargs={\"k\": 3})" ] }, { "cell_type": "code", "execution_count": null, "id": "29c4d43b-0ca2-4183-81ef-abf880c4e66d", "metadata": {}, "outputs": [], "source": [ "retriever" ] }, { "cell_type": "code", "execution_count": null, "id": "ec422828-696d-455c-9f6a-34a6dd0e6ac8", "metadata": {}, "outputs": [], "source": [ "# !pip install langchain_huggingface" ] }, { "cell_type": "markdown", "id": "fe7fd10a-f64a-48de-a116-6d5890def1af", "metadata": {}, "source": [ "## LLMs" ] }, { "cell_type": "code", "execution_count": null, "id": "0e75c029-6c10-47c7-871c-1f4932b25309", "metadata": {}, "outputs": [], "source": [ "### Retrieval Grader\n", "\n", "from langchain.prompts import PromptTemplate\n", "from langchain_community.chat_models import ChatOllama\n", "from langchain_core.output_parsers import JsonOutputParser\n", "from langchain_mistralai.chat_models import ChatMistralAI\n", "from langchain_core.messages import (\n", " HumanMessage,\n", " SystemMessage,\n", ")\n", "from langchain_huggingface import ChatHuggingFace\n", "# LLM\n", "\n", "from langchain_openai import ChatOpenAI\n", "\n", "\n", "if run_local == \"Yes\":\n", "\n", "# from langchain_huggingface.llms import HuggingFacePipeline\n", "\n", "# hf = HuggingFacePipeline.from_model_id(\n", "# model_id=\"meta-llama/Llama-2-13b-chat-hf\",\n", "# task=\"text-generation\",\n", "# pipeline_kwargs={\"max_new_tokens\": 256,'temperature' :1e-10},\n", "# device = 0,\n", "# )\n", " llm = ChatOpenAI(\n", " model=\"gpt-4o\",\n", " temperature=0,\n", " max_tokens=None,\n", " timeout=None,\n", " max_retries=2,\n", " api_key=\"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\", # if you prefer to pass api key in directly instaed of using env vars\n", " # base_url=\"...\",\n", " # organization=\"...\",\n", " # other params...\n", " )\n", " # chat_model = ChatHuggingFace(llm=llm)\n", " chat_model = llm\n", "else:\n", " llm = ChatMistralAI(\n", " model=\"mistral-medium\", temperature=0, mistral_api_key=mistral_api_key\n", " )\n", " print(\"yesmistral\")\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "7c719323-f184-4747-9479-7414deeffd01", "metadata": {}, "outputs": [], "source": [ "from langchain_core.prompts import (\n", " ChatPromptTemplate,\n", " FewShotChatMessagePromptTemplate,\n", ")\n", "examples = [\n", " {\"input\": \"\"\"Here is the retrieved document: \n", "\n", " are packaged into the lipid-containing chylomicrons inside small intestine mucosal cells and then transported to the liver. In the liver, carotenoids are repackaged into lipoproteins, which transport them to cells. The retinoids are aptly named as their most notable function is in the retina of the eye where they aid in vision, particularly in seeing under low-light conditions. This is why night blindness is the most definitive sign of vitamin A deficiency.Vitamin A has several important functions in the body, including maintaining vision and a healthy immune system. Many of vitamin A’s functions in the body are similar to the functions of hormones (for example, vitamin A can interact with DNA, causing a change in protein function). Vitamin A assists in maintaining healthy skin and the linings and coverings of tissues; it also regulates growth and development. As an antioxidant, vitamin A protects cellular membranes, helps in maintaining glutathione levels, and influences the amount \n", "\n", " \n", " Here is the user question: What is Vitamin A? Is this retrieved document relevant to user question? Yes or no.\"\"\", \"output\": \"yes\"},\n", "\n", "]" ] }, { "cell_type": "code", "execution_count": null, "id": "cfa8ab09-61cc-413b-b9c5-754792f2d1a9", "metadata": {}, "outputs": [], "source": [ "example_prompt = ChatPromptTemplate.from_messages(\n", " [\n", " (\"human\", \"{input}\"),\n", " (\"ai\", \"{output}\"),\n", " ]\n", ")\n", "few_shot_prompt = FewShotChatMessagePromptTemplate(\n", " example_prompt=example_prompt,\n", " examples=examples,\n", ")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "0e76ba41-f6ab-4cd8-bf35-d9ebaada3600", "metadata": {}, "outputs": [], "source": [ "\n", "from langchain_core.output_parsers import StrOutputParser\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 {document} \\n\\n \n", "# Here is the user question: {question} \\n \n", "# Is this retrieved document relevant to user question? Yes or no. \"\"\",\n", "# input_variables=[\"question\", \"document\"],\n", "# )\n", "\n", "# messages = [\n", "# SystemMessage(content=\"You are a grader assessing relevance of a retrieved document to a user question. Your answer should only be 'yes' or 'no'\"),\n", "# HumanMessage(\n", "# content=\"What happens when an unstoppable force meets an immovable object?\"\n", "# ),\n", "# ]\n", "prompt = ChatPromptTemplate.from_messages(\n", " [\n", " (\"system\", \"You are a grader assessing relevance of a retrieved document to a user question. Your answer should only be 'yes' or 'no'\"),\n", " few_shot_prompt,\n", " (\"human\", \"\"\"Here is the retrieved document: \\n\\n {document} \\n\\n \n", " Here is the user question: {question} \\n \n", " Is this retrieved document relevant to user question? Yes or no. \"\"\"),\n", " ]\n", ")\n", "\n", "retrieval_grader = prompt | chat_model \n", "question = \"what is Vitamin D?\"\n", "docs = retriever.get_relevant_documents(question)\n", "doc_txt = docs[1].page_content\n", "print(retrieval_grader.invoke({\"question\": question, \"document\": doc_txt}))" ] }, { "cell_type": "code", "execution_count": null, "id": "fdf3f319-9448-4706-b042-c292d0fb3283", "metadata": {}, "outputs": [], "source": [ "docs" ] }, { "cell_type": "code", "execution_count": null, "id": "dad03302-bd93-43fc-949e-af51a3298cfa", "metadata": {}, "outputs": [], "source": [ "### Generate\n", "\n", "from langchain import hub\n", "\n", "# Prompt\n", "prompt = hub.pull(\"rlm/rag-prompt\")\n", "\n", "\n", "# Post-processing\n", "def format_docs(docs):\n", " return \"\\n\\n\".join(doc.page_content for doc in docs)\n", "\n", "\n", "# Chain\n", "rag_chain = prompt | chat_model | StrOutputParser()\n", "\n", "# Run\n", "generation = rag_chain.invoke({\"context\": docs, \"question\": question})\n", "print(generation)" ] }, { "cell_type": "code", "execution_count": null, "id": "f4b61211-70b5-4471-a714-feb9cc91e860", "metadata": {}, "outputs": [], "source": [ "examples2 = [\n", " {\"input\": \"\"\"Here is the initial question: \\n what is Vitamin D? \\n Write me an improved question only with no explanation: \"\"\", \"output\": \"What are the key properties and benefits of vitamin D, and how does it contribute to maintaining overall health and wellness?\"},\n", "\n", "]\n", "\n", "example_prompt2 = ChatPromptTemplate.from_messages(\n", " [\n", " (\"human\", \"{input}\"),\n", " (\"ai\", \"{output}\"),\n", " ]\n", ")\n", "few_shot_prompt2 = FewShotChatMessagePromptTemplate(\n", " example_prompt=example_prompt2,\n", " examples=examples2,\n", ")\n", "\n", "re_write_prompt = ChatPromptTemplate.from_messages(\n", " [\n", " (\"system\", \"You a question re-writer that converts an input question to a better version that is optimized for vectorstore retrieval. Look at the initial and formulate an improved question.\"),\n", " few_shot_prompt2,\n", " (\"human\", \"\"\"Here is the initial question: \\n\\n {question} \\n\\n \n", " Write me an improved question only with no explanation: \"\"\"),\n", " \n", " ]\n", ")\n", "\n", "question = \"what is love?\"\n", "# re_write_prompt = PromptTemplate(\n", "# template=\"\"\"You a question re-writer that converts an input question to a better version that is optimized \\n \n", "# for vectorstore retrieval. Look at the initial and formulate an improved question. \\n\n", "# Here is the initial question: \\n\\n {question}. Improved question with no explanation: \\n \"\"\",\n", "# input_variables=[\"generation\", \"question\"],\n", "# )\n", "\n", "question_rewriter = re_write_prompt | chat_model | StrOutputParser()\n", "question_rewriter.invoke({\"question\": question})" ] }, { "cell_type": "markdown", "id": "5d7fde29-e62e-4445-80f9-122eee0a3922", "metadata": {}, "source": [ "## Web Search Tool" ] }, { "cell_type": "code", "execution_count": null, "id": "b36a2f36-bc5f-408d-a5e8-3fa203c233f6", "metadata": {}, "outputs": [], "source": [ "### Search\n", "\n", "from langchain_community.tools.tavily_search import TavilySearchResults\n", "\n", "web_search_tool = TavilySearchResults(k=1)" ] }, { "cell_type": "markdown", "id": "a3421cf0-9067-43fe-8681-0d3189d15dd3", "metadata": {}, "source": [ "# Graph \n", "\n", "Capture the flow in as a graph.\n", "\n", "## Graph state" ] }, { "cell_type": "code", "execution_count": null, "id": "10028794-2fbc-43f9-aa4c-7fe3abd69c1e", "metadata": {}, "outputs": [], "source": [ "from typing import List\n", "\n", "from typing_extensions import TypedDict\n", "\n", "\n", "class GraphState(TypedDict):\n", " \"\"\"\n", " Represents the state of our graph.\n", "\n", " Attributes:\n", " question: question\n", " generation: LLM generation\n", " web_search: whether to add search\n", " documents: list of documents\n", " \"\"\"\n", "\n", " question: str\n", " generation: str\n", " web_search: str\n", " documents: List[str]" ] }, { "cell_type": "code", "execution_count": null, "id": "447d1333-082d-479a-a6fa-0ac0df78bb9d", "metadata": {}, "outputs": [], "source": [ "from langchain.schema import Document\n", "\n", "\n", "def 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", " print(\"---RETRIEVE---\")\n", " question = state[\"question\"]\n", "\n", " # Retrieval\n", " documents = retriever.get_relevant_documents(question)\n", " return {\"documents\": documents, \"question\": question}\n", "\n", "\n", "def 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", " print(\"---GENERATE---\")\n", " question = state[\"question\"]\n", " documents = state[\"documents\"]\n", "\n", " # RAG generation\n", " generation = rag_chain.invoke({\"context\": documents, \"question\": question})\n", " return {\"documents\": documents, \"question\": question, \"generation\": generation}\n", "\n", "\n", "def 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", " print(\"---CHECK DOCUMENT RELEVANCE TO QUESTION---\")\n", " question = state[\"question\"]\n", " documents = state[\"documents\"]\n", "\n", " # Score each doc\n", " filtered_docs = []\n", " web_search = \"No\"\n", " for d in documents:\n", " score = retrieval_grader.invoke(\n", " {\"question\": question, \"document\": d.page_content}\n", " )\n", " print(\"SC\", score)\n", " grade = score.content\n", " if grade == \"yes\":\n", " print(\"---GRADE: DOCUMENT RELEVANT---\")\n", " filtered_docs.append(d)\n", " else:\n", " print(\"---GRADE: DOCUMENT NOT RELEVANT---\")\n", " web_search = \"Yes\"\n", " continue\n", " return {\"documents\": filtered_docs, \"question\": question, \"web_search\": web_search}\n", "\n", "\n", "def transform_query(state):\n", " \"\"\"\n", " Transform the query to produce a better question.\n", "\n", " Args:\n", " state (dict): The current graph state\n", "\n", " Returns:\n", " state (dict): Updates question key with a re-phrased question\n", " \"\"\"\n", "\n", " print(\"---TRANSFORM QUERY---\")\n", " question = state[\"question\"]\n", " documents = state[\"documents\"]\n", "\n", " # Re-write question\n", " # better_question = question_rewriter.invoke({\"question\": question})\n", " return {\"documents\": documents, \"question\": question}\n", "\n", "\n", "def 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", " print(\"---WEB SEARCH---\")\n", " question = state[\"question\"]\n", " documents = state[\"documents\"]\n", " print(\"WEB SEARCH\", question)\n", " # Web search\n", " docs = web_search_tool.invoke({\"query\": question[:100]})\n", "\n", " web_results = \"\\n\".join([d[\"content\"] for d in docs])\n", "\n", " web_results = Document(page_content=web_results)\n", " documents.append(web_results)\n", "\n", " return {\"documents\": documents, \"question\": question}\n", "\n", "\n", "### Edges\n", "\n", "\n", "def 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", "\n", " print(\"---ASSESS GRADED DOCUMENTS---\")\n", " state[\"question\"]\n", " web_search = state[\"web_search\"]\n", " state[\"documents\"]\n", "\n", " if web_search == \"Yes\":\n", " # All documents have been filtered check_relevance\n", " # We will re-generate a new query\n", " print(\n", " \"---DECISION: ALL DOCUMENTS ARE NOT RELEVANT TO QUESTION, TRANSFORM QUERY---\"\n", " )\n", " return \"transform_query\"\n", " else:\n", " # We have relevant documents, so generate answer\n", " print(\"---DECISION: GENERATE---\")\n", " return \"generate\"" ] }, { "cell_type": "markdown", "id": "6096626d-dfa5-48e0-8a24-3747b298bc67", "metadata": {}, "source": [ "## Build Graph\n", "\n", "This just follows the flow we outlined in the figure above." ] }, { "cell_type": "code", "execution_count": null, "id": "0a63776c-f9cd-46ce-b8cf-95c066dc5b06", "metadata": {}, "outputs": [], "source": [ "from langgraph.graph import END, StateGraph\n", "\n", "workflow = StateGraph(GraphState)\n", "\n", "# Define the nodes\n", "workflow.add_node(\"retrieve\", retrieve) # retrieve\n", "workflow.add_node(\"grade_documents\", grade_documents) # grade documents\n", "workflow.add_node(\"generate\", generate) # generatae\n", "workflow.add_node(\"transform_query\", transform_query) # transform_query\n", "workflow.add_node(\"web_search_node\", web_search) # web search\n", "\n", "# Build graph\n", "workflow.set_entry_point(\"retrieve\")\n", "workflow.add_edge(\"retrieve\", \"grade_documents\")\n", "workflow.add_conditional_edges(\n", " \"grade_documents\",\n", " decide_to_generate,\n", " {\n", " \"transform_query\": \"transform_query\",\n", " \"generate\": \"generate\",\n", " },\n", ")\n", "workflow.add_edge(\"transform_query\", \"web_search_node\")\n", "workflow.add_edge(\"web_search_node\", \"generate\")\n", "workflow.add_edge(\"generate\", END)\n", "\n", "# Compile\n", "app = workflow.compile()" ] }, { "cell_type": "code", "execution_count": null, "id": "3b32741c-dbca-4075-ba80-c45e3728059e", "metadata": {}, "outputs": [], "source": [ "q_eng =QA['french'].copy()" ] }, { "cell_type": "code", "execution_count": null, "id": "3ab1d8df-a74e-4b48-a30b-e39bbfd5925a", "metadata": {}, "outputs": [], "source": [ "from pprint import pprint\n", "results_eng = []\n", "from tqdm.notebook import tqdm\n", "for q_e in tqdm(q_eng): \n", " inputs = {\"question\": \"Only answer in a,b,c,d.\" +q_e }\n", " for output in app.stream(inputs):\n", " for key, value in output.items():\n", " # Node\n", " pprint(f\"Node '{key}':\")\n", " # Optional: print full state at each node\n", " # pprint.pprint(value[\"keys\"], indent=2, width=80, depth=None)\n", " pprint(\"\\n---\\n\")\n", "\n", " # Final generation\n", " pprint(value[\"generation\"])\n", " results_eng.append(value[\"generation\"])" ] }, { "cell_type": "code", "execution_count": null, "id": "4837cd9d-a86b-4611-b7b8-f85d2df6edae", "metadata": {}, "outputs": [], "source": [ "results_eng" ] }, { "cell_type": "code", "execution_count": null, "id": "71777932-7710-47d8-93dc-2a1657c48909", "metadata": {}, "outputs": [], "source": [ "import csv\n", "file_name = 'output_french.csv'\n", "\n", "# Open the file in write mode\n", "with open(file_name, mode='w', newline='') as file:\n", " writer = csv.writer(file)\n", "\n", " # Write each item in the list as a new row in the CSV file\n", " for item in results_eng:\n", " writer.writerow([item]) " ] }, { "cell_type": "code", "execution_count": null, "id": "71b2cd11-9435-4a47-9027-3c2718dd5284", "metadata": {}, "outputs": [], "source": [ "\n", "\n", "# Find all indexes of strings that start with \"I don\"\n", "indexes = [index for index, item in enumerate(results_eng) if item.startswith(\"I don\")]\n", "\n", "print(indexes)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "614970c7-02bf-4ee4-9e78-cd025b2e43bf", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "res = pd.read_csv(\"output_french.csv\",header=None)" ] }, { "cell_type": "code", "execution_count": null, "id": "ab9393e4-8b9b-4bf0-970a-8ebb54b83246", "metadata": {}, "outputs": [], "source": [ "res" ] }, { "cell_type": "code", "execution_count": null, "id": "50a5d9c6-dd60-4033-9e20-673d2cdd50cc", "metadata": {}, "outputs": [], "source": [ "gt = QA.answer.str.lower().tolist()" ] }, { "cell_type": "code", "execution_count": null, "id": "c86b57dd-7d6f-4b1e-9566-d9ebc8b10b5d", "metadata": {}, "outputs": [], "source": [ "preds = res[0]" ] }, { "cell_type": "code", "execution_count": null, "id": "fa6fc4a4-cd10-44a7-926f-6bdbc68345bc", "metadata": {}, "outputs": [], "source": [ "first_chars = [s[0] for s in preds if s] # the 'if s' ensures the string is not empty\n", "\n", "print(first_chars)" ] }, { "cell_type": "code", "execution_count": null, "id": "c41a9c42-f128-417e-9957-fdf94a02a5f6", "metadata": {}, "outputs": [], "source": [ "def sum_not_in_abcd(lst):\n", " # Initialize sum\n", " total_sum = 0\n", "\n", " # Iterate through the list\n", " for item in lst:\n", " # Check if the first character is not in the specified list\n", " if item[0].lower() not in ['a', 'b', 'c', 'd',\"A\",\"B\",\"C\",'D']:\n", " # Convert to integer and add to the sum\n", " total_sum += 1\n", " \n", " return total_sum\n", "\n", "# Example usage\n", "lst = first_chars\n", "sum_not_in_abcd(lst)" ] }, { "cell_type": "code", "execution_count": null, "id": "935cb5e2-d9e2-4c08-9989-44d4cc6cac8e", "metadata": {}, "outputs": [], "source": [ "(np.array(first_chars) == np.array(gt)).sum()" ] }, { "cell_type": "code", "execution_count": null, "id": "6d927ae5-9179-400e-85f2-23a8afa01dc1", "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.9.13" } }, "nbformat": 4, "nbformat_minor": 5 }