{ "cells": [ { "cell_type": "markdown", "id": "83f74055-d137-466c-9555-4e2da9759ddb", "metadata": {}, "source": [ "### Search\n", " \n", "We'll use [Tavily Search](https://python.langchain.com/docs/integrations/tools/tavily_search) for web search." ] }, { "cell_type": "code", "execution_count": 36, "id": "28224481-4cb0-4bc6-bf88-2d2b383094df", "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "os.environ[\"TAVILY_API_KEY\"] = \"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\"" ] }, { "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": 37, "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": 38, "id": "2f4db331-c4d0-4c7c-a9a5-0bebc8a89c6c", "metadata": {}, "outputs": [], "source": [ "run_local = \"Yes\"\n", "local_llm = \"llama2-13b\"" ] }, { "cell_type": "code", "execution_count": 39, "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": 40, "id": "d3f4d43f-eb93-4f7d-9cab-1ab3c7de6c6a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "File /home/chenweiw/basic.pdf exists.\n" ] } ], "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", "pdf_path = \"\"\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": 41, "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": 42, "id": "c19560ff-2808-406a-aa70-b8c4d303121e", "metadata": {}, "outputs": [], "source": [ "# !pip install fastembed" ] }, { "cell_type": "code", "execution_count": 43, "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": 44, "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": 46, "id": "15dcb261-2197-4207-bf1d-e9d9ddcc007a", "metadata": {}, "outputs": [], "source": [ "pages_and_texts = basic+surgery" ] }, { "cell_type": "code", "execution_count": 47, "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": 49, "id": "0b37fc4b-ee00-4523-86d6-e9657e2b8c91", "metadata": {}, "outputs": [], "source": [ "# !pip install langchain_openai" ] }, { "cell_type": "code", "execution_count": 1, "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": 51, "id": "d43b5ba7-c2e7-45b1-bcdd-156e53ef9f68", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Document(page_content='CHAPTER 2 Diagnostic tests and their interpretation 54 Automated perimetry: performance and interpretation (2) Interpretation of Humphrey perimetry (cont.) Table 2.4 Global indices (a summary of the results as a single number used to monitor change) Mean deviation (MD) A measure of overall fi eld loss. Pattern standard deviation (PSD) Measure of focal loss or variability within the fi eld, taking into account any generalized depression. An increased PSD is more indicative of glaucomatous fi eld loss than MD. Short-term fl uctuation (SF) An indication of the consistency of responses. It is assessed by measuring threshold twice at 10 preselected points and calculated on the difference between the fi rst and second measurements. Corrected pattern standard deviation (CPSD) A measure of variability within the fi eld after correcting for SF (intratest variability). Table 2.3 Typical graphical results from automated perimetry (Fig. 2.2) Gray scale Decreasing sensitivity is represented by the darker')" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "all_splits[156]" ] }, { "cell_type": "code", "execution_count": 52, "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": 53, "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": 54, "id": "29c4d43b-0ca2-4183-81ef-abf880c4e66d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "VectorStoreRetriever(tags=['Chroma', 'HuggingFaceEmbeddings'], vectorstore=, search_kwargs={'k': 3})" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "retriever" ] }, { "cell_type": "code", "execution_count": 55, "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": 56, "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-3.5-turbo-0125\",\n", " temperature=0,\n", " max_tokens=None,\n", " timeout=None,\n", " max_retries=2,\n", " api_key=\"\", # 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": 57, "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": 58, "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": 59, "id": "0e76ba41-f6ab-4cd8-bf35-d9ebaada3600", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "content='no' response_metadata={'token_usage': {'completion_tokens': 1, 'prompt_tokens': 534, 'total_tokens': 535}, 'model_name': 'gpt-3.5-turbo-0125', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None} id='run-ed0b1a12-eb21-450d-87ef-d8c18b292d0a-0' usage_metadata={'input_tokens': 534, 'output_tokens': 1, 'total_tokens': 535}\n" ] } ], "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": 60, "id": "fdf3f319-9448-4706-b042-c292d0fb3283", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[Document(page_content='corticosteroid use, and diabetes mellitus. Nutritional or vitamin supplementation has not consistently been shown to be useful in preventing cataract formation. Pathogenesis The way in which these factors cause cataracts is unclear, although a com- mon pathway appears to be protein denaturation (e.g., by oxidative stress). Metabolic disturbance (hyperglycemia in diabetes mellitus or hyperuremia in dehydration or renal failure), toxins (e.g., smoking, alcohol), loss of anti-oxidant enzymes (e.g., superoxide dismutase), membrane disruption, reduced metabolism, failure of active transport, and loss of ionic–osmotic balance may all contribute to this process. Clinical presentations Common Change in vision—reduced acuity, contrast sensitivity, or color • appreciation, glare, monocular diplopia, or ghosting. Change in refraction—typically a myopic shift due to nuclear sclerosis. • Change in fundus view—clinicians may have diffi culty “looking in” • long before the patients feel they have diffi'),\n", " Document(page_content='corticosteroid use, and diabetes mellitus. Nutritional or vitamin supplementation has not consistently been shown to be useful in preventing cataract formation. Pathogenesis The way in which these factors cause cataracts is unclear, although a com- mon pathway appears to be protein denaturation (e.g., by oxidative stress). Metabolic disturbance (hyperglycemia in diabetes mellitus or hyperuremia in dehydration or renal failure), toxins (e.g., smoking, alcohol), loss of anti-oxidant enzymes (e.g., superoxide dismutase), membrane disruption, reduced metabolism, failure of active transport, and loss of ionic–osmotic balance may all contribute to this process. Clinical presentations Common Change in vision—reduced acuity, contrast sensitivity, or color • appreciation, glare, monocular diplopia, or ghosting. Change in refraction—typically a myopic shift due to nuclear sclerosis. • Change in fundus view—clinicians may have diffi culty “looking in” • long before the patients feel they have diffi'),\n", " Document(page_content='dysgenesis Peters anomaly Rieger syndrome Metabolic Carbohydrate Hypoglycemia Galactokinase defi ciency Galactosemia, Mannosidosis Lipids Abetalipoproteinemia Amino acid Lowe syndrome Homocysteinuria Sphingolipidoses Niemann–Pick disease Fabry disease Minerals Wilson disease Hypocalcemia Phytanic acid Refsum disease Endocrine Diabetes mellitus Hypoparathyroidism Infective Toxoplasma Rubella Herpes group (CMV, HSV1 & 2, VZV) Syphilis Measles Poliomyelitis Infl uenza Other Trauma Drugs (steroids) Eczema Radiation')]" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "docs" ] }, { "cell_type": "code", "execution_count": 61, "id": "dad03302-bd93-43fc-949e-af51a3298cfa", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Vitamin D is a nutrient that helps the body absorb calcium and phosphorus, which are essential for bone health. It can be obtained through sunlight exposure, certain foods, and supplements. Deficiency in Vitamin D can lead to bone disorders like rickets or osteomalacia.\n" ] } ], "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": 62, "id": "f4b61211-70b5-4471-a714-feb9cc91e860", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'What are the fundamental aspects and significance of love in human relationships and emotional well-being?'" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "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": "5cd97fcd-218c-431b-8447-2a88cface6f6", "metadata": {}, "source": [ "# Translator" ] }, { "cell_type": "code", "execution_count": 63, "id": "63857bdd-5c99-456a-a2cf-8ffb4319e610", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"What is the retina? A eyeball B retina C optic nerve D don't know\"" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# \n", "\n", "translate_prompt = ChatPromptTemplate.from_messages(\n", " [\n", " (\"system\", \"You are a multilingual medical question translator, if the input question is in english, directly return the question. If it is in Portuguese/Spanish/Filipino, directly return the question translated in English.\"),\n", " (\"human\", \"\"\"Here is the initial question: \\n\\n {question} \\n\\n \n", " If not in English, return the question in English ONLY: \"\"\"), \n", " ]\n", ")\n", "\n", "question = \"\"\"\"\n", "什么是视网膜? A 眼球 B 视网膜 C 视神经 D不知道\"\"\"\n", "\n", "\n", "question_translator = translate_prompt | chat_model | StrOutputParser()\n", "question_translator.invoke({\"question\": question})" ] }, { "cell_type": "markdown", "id": "5d7fde29-e62e-4445-80f9-122eee0a3922", "metadata": {}, "source": [ "## Web Search Tool" ] }, { "cell_type": "code", "execution_count": 64, "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=3)" ] }, { "cell_type": "markdown", "id": "8edf5e5b-8633-4cd6-8498-bf39016c7c6c", "metadata": {}, "source": [ "# generateor" ] }, { "cell_type": "code", "execution_count": 65, "id": "7ae7b15d-f255-4a19-93e3-25b462efff7a", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'B 视网膜。视网膜是眼睛内部的一层组织,位于眼球的后部,包含了感光细胞,负责接收光线并将其转化为神经信号,然后通过视神经传送到大脑,使我们能够看到周围的世界。'" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\n", "gen_prompt =ChatPromptTemplate.from_messages([ \"human\", \"{question}\"])\n", "genner = gen_prompt | chat_model | StrOutputParser()\n", "genner.invoke({\"question\": question})" ] }, { "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": 66, "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": 67, "id": "447d1333-082d-479a-a6fa-0ac0df78bb9d", "metadata": {}, "outputs": [], "source": [ "from langchain.schema import Document\n", "\n", "\n", "def translate(state):\n", " \"\"\"\n", " Translate to english\n", " \"\"\"\n", " print(\"---Translate---\")\n", " question = state[\"question\"]\n", "\n", " # Retrieval\n", " question = question_translator.invoke({\"question\": question})\n", " return {\"question\": question}\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": 68, "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(\"translate\", translate)\n", "workflow.add_node(\"generate\", generate) # generatae\n", "\n", "# Build graph\n", "workflow.set_entry_point(\"translate\")\n", "workflow.add_edge(\"translate\",\"generate\")\n", "workflow.add_edge(\"generate\", END)\n", "\n", "# Compile\n", "app = workflow.compile()" ] }, { "cell_type": "code", "execution_count": 71, "id": "39f83ebf-fd20-47f9-8811-0031132315b8", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "from tqdm.notebook import tqdm\n", "import csv\n", "\n", "# Load dataset\n", "QA = pd.read_csv('')\n", "q_eng = QA['english'].copy()\n", "\n", "# Function to generate answers\n", "def generate_answers(questions):\n", " results = []\n", " for q_e in tqdm(questions): \n", " inputs = {\"question\": \"You are an expert medical assistant.\\\n", "You will be provided with medical queries, answer only in a,b,c,d:\" + q_e}\n", " for output in app.stream(inputs):\n", " for key, value in output.items():\n", " pass\n", " results.append(value[\"generation\"])\n", " return results\n", "\n", "# Initial generation\n", "results_eng = generate_answers(q_eng)\n", "\n", "# Open the file in write mode\n", "file_name = 'en3.5t2.csv'\n", "with open(file_name, mode='w', newline='') as file:\n", " writer = csv.writer(file)\n", " for item in results_eng:\n", " writer.writerow([item]) \n", "\n", "# Function to check if answers are valid\n", "def are_valid_answers(answers):\n", " valid_answers = {'a', 'b', 'c', 'd'}\n", " return [answer[0] in valid_answers for answer in answers]\n", "\n", "# Iteratively generate answers until all are valid or patience level is reached\n", "iteration = 0\n", "patience = 10\n", "valid_flags = are_valid_answers(results_eng)\n", "\n", "while not all(valid_flags) and iteration < patience:\n", " iteration += 1\n", " num_valid = sum(valid_flags)\n", " num_invalid = len(valid_flags) - num_valid\n", " print(f\"Iteration {iteration}: {num_valid} valid answers, {num_invalid} invalid answers\")\n", " \n", " # Find indexes of invalid answers\n", " invalid_indexes = [index for index, is_valid in enumerate(valid_flags) if not is_valid]\n", " \n", " # Generate new answers for invalid questions\n", " invalid_questions = [q_eng[index] for index in invalid_indexes]\n", " new_answers = generate_answers(invalid_questions)\n", " \n", " # Update results with new answers\n", " for i, index in enumerate(invalid_indexes):\n", " results_eng[index] = new_answers[i]\n", " \n", " # Re-check validity of all answers\n", " valid_flags = are_valid_answers(results_eng)\n", "\n", "# Final status\n", "if all(valid_flags):\n", " print(\"All answers are now valid.\")\n", "else:\n", " print(\"Reached patience limit. Some answers are still invalid.\")\n", "\n", "# Final comparison with ground truth\n", "res = pd.DataFrame(results_eng, columns=['answer'])\n", "gt = QA.answer.str.lower().tolist()\n", "preds = res['answer'].str[0].tolist() # Take only the first character\n", "first_chars = [s[0] for s in preds if s] # Ensure the string is not empty\n", "\n", "print(first_chars)\n", "print((np.array(first_chars) == np.array(gt)).sum())\n", "\n", "# Save final results to CSV\n", "file_name_final = 'en_3.5t2.csv'\n", "with open(file_name_final, mode='w', newline='') as file:\n", " writer = csv.writer(file)\n", " for item in results_eng:\n", " writer.writerow([item])\n" ] }, { "cell_type": "code", "execution_count": 70, "id": "0fd3b01c-eba8-49ee-9683-8052613c9f5a", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "from tqdm.notebook import tqdm\n", "import csv\n", "\n", "# Open the file in write mode\n", "file_name = 'en3.5t2.csv'\n", "with open(file_name, mode='w', newline='') as file:\n", " writer = csv.writer(file)\n", " for item in results_eng:\n", " writer.writerow([item]) \n", "\n", "# Function to check if answers are valid\n", "def are_valid_answers(answers):\n", " valid_answers = {'a', 'b', 'c', 'd'}\n", " return [answer[0] in valid_answers for answer in answers]\n", "\n", "# Iteratively generate answers until all are valid or patience level is reached\n", "iteration = 0\n", "patience = 10\n", "valid_flags = are_valid_answers(results_eng)\n", "\n", "while not all(valid_flags) and iteration < patience:\n", " iteration += 1\n", " num_valid = sum(valid_flags)\n", " num_invalid = len(valid_flags) - num_valid\n", " print(f\"Iteration {iteration}: {num_valid} valid answers, {num_invalid} invalid answers\")\n", " \n", " # Find indexes of invalid answers\n", " invalid_indexes = [index for index, is_valid in enumerate(valid_flags) if not is_valid]\n", " \n", " # Generate new answers for invalid questions\n", " invalid_questions = [q_eng[index] for index in invalid_indexes]\n", " new_answers = generate_answers(invalid_questions)\n", " \n", " # Update results with new answers\n", " for i, index in enumerate(invalid_indexes):\n", " results_eng[index] = new_answers[i]\n", " \n", " # Re-check validity of all answers\n", " valid_flags = are_valid_answers(results_eng)\n", "\n", "# Final status\n", "if all(valid_flags):\n", " print(\"All answers are now valid.\")\n", "else:\n", " print(\"Reached patience limit. Some answers are still invalid.\")\n", "\n", "# Final comparison with ground truth\n", "res = pd.DataFrame(results_eng, columns=['answer'])\n", "gt = QA.answer.str.lower().tolist()\n", "preds = res['answer'].str[0].tolist() # Take only the first character\n", "first_chars = [s[0] for s in preds if s] # Ensure the string is not empty\n", "\n", "print(first_chars)\n", "print((np.array(first_chars) == np.array(gt)).sum())\n", "\n", "# Save final results to CSV\n", "file_name_final = 'en_3.5t2.csv'\n", "with open(file_name_final, mode='w', newline='') as file:\n", " writer = csv.writer(file)\n", " for item in results_eng:\n", " writer.writerow([item])\n" ] }, { "cell_type": "code", "execution_count": 77, "id": "acb4e714-cd85-4bbd-8624-638d071de3b3", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "from langchain import hub\n", "from langchain.prompts import PromptTemplate\n", "from tqdm.notebook import tqdm\n", "import csv\n", "import json\n", "\n", "# Define the generate_prompt function\n", "def generate_prompt(LANGUAGES, REASONING, Responses=['A', 'B', 'C', 'D']):\n", " delimiter = \"####\"\n", " languages_text = \", \".join(LANGUAGES)\n", " responses_text = \", \".join(Responses)\n", "\n", " system_message = f\"\"\"You are an expert medical assistant.\\\n", " You will be provided with medical queries in these languages: {languages_text}. \\\n", " Answer the question as best as possible.\"\"\"\n", "\n", " template = system_message + \"\\n{format_instructions}\\n{question}\"\n", "\n", " response_schema = {\n", " \"name\": \"response\",\n", " \"description\": f\"This is the option of the correct response. Could be only any of these: {responses_text}\"\n", " }\n", "\n", " if REASONING:\n", " reasoning_schema = {\n", " \"name\": \"reasoning\",\n", " \"description\": \"This is the reasons for the answer\"\n", " }\n", " response_schemas = [response_schema, reasoning_schema]\n", " else:\n", " response_schemas = [response_schema]\n", "\n", " format_instructions = \"Respond with a JSON object containing the following keys:\\n\" + \\\n", " \"\\n\".join([f\"{schema['name']}: {schema['description']}\" for schema in response_schemas])\n", "\n", " prompt = PromptTemplate(\n", " template=template,\n", " input_variables=[\"question\"],\n", " partial_variables={\"format_instructions\": format_instructions}\n", " )\n", " \n", " return prompt\n", "\n", "# Custom parsing function\n", "def parse_response(response_text):\n", " try:\n", " response_json = json.loads(response_text)\n", " return response_json.get(\"response\", \"invalid\")\n", " except json.JSONDecodeError:\n", " return \"invalid\"\n", "\n", "# Load dataset\n", "QA = pd.read_csv('')\n", "q_eng = QA['english'].copy()\n", "\n", "# Generate prompt\n", "LANGUAGES = [\"English\"]\n", "REASONING = False\n", "prompt = generate_prompt(LANGUAGES, REASONING)\n", "\n", "# Post-processing function (from your current generation)\n", "def format_docs(docs):\n", " return \"\\n\\n\".join(doc.page_content for doc in docs)\n", "\n", "# Define the generation function using LangChain\n", "def generate_answers(questions):\n", " results = []\n", " for q_e in tqdm(questions): \n", " formatted_prompt = prompt.format(question=q_e)\n", " inputs = {\"question\": formatted_prompt}\n", " generation = rag_chain.invoke({\"context\": [], \"question\": inputs[\"question\"]})\n", " print(generation) # Print the generation to understand its structure\n", " parsed_response = parse_response(generation)\n", " results.append(parsed_response)\n", " return results\n", "\n", "# Initial generation\n", "results_eng = generate_answers(q_eng)\n", "\n", "# Open the file in write mode\n", "file_name = 'output3.5.csv'\n", "with open(file_name, mode='w', newline='') as file:\n", " writer = csv.writer(file)\n", " for item in results_eng:\n", " writer.writerow([item]) \n", "\n", "# Function to check if answers are valid\n", "def are_valid_answers(answers):\n", " valid_answers = {'a', 'b', 'c', 'd','A','B','C','D'}\n", " return [answer[0] in valid_answers for answer in answers]\n", "\n", "# Iteratively generate answers until all are valid or patience level is reached\n", "iteration = 0\n", "patience = 10\n", "valid_flags = are_valid_answers(results_eng)\n", "\n", "while not all(valid_flags) and iteration < patience:\n", " iteration += 1\n", " num_valid = sum(valid_flags)\n", " num_invalid = len(valid_flags) - num_valid\n", " print(f\"Iteration {iteration}: {num_valid} valid answers, {num_invalid} invalid answers\")\n", " \n", " # Find indexes of invalid answers\n", " invalid_indexes = [index for index, is_valid in enumerate(valid_flags) if not is_valid]\n", " \n", " # Generate new answers for invalid questions\n", " invalid_questions = [q_eng[index] for index in invalid_indexes]\n", " new_answers = generate_answers(invalid_questions)\n", " \n", " # Update results with new answers\n", " for i, index in enumerate(invalid_indexes):\n", " results_eng[index] = new_answers[i]\n", " \n", " # Re-check validity of all answers\n", " valid_flags = are_valid_answers(results_eng)\n", "\n", "# Final status\n", "if all(valid_flags):\n", " print(\"All answers are now valid.\")\n", "else:\n", " print(\"Reached patience limit. Some answers are still invalid.\")\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "9d42f00a-03fa-4bff-8032-f0ecb1021b18", "metadata": {}, "outputs": [], "source": [ "# Final comparison with ground truth\n", "res = pd.DataFrame(results_eng, columns=['answer'])\n", "gt = QA.answer.str.lower().tolist()\n", "preds = res['answer'].str[0].tolist() # Take only the first character\n", "first_chars = [s[0].lower() for s in preds if s] # Ensure the string is not empty\n", "\n", "print(first_chars)\n", "print((np.array(first_chars) == np.array(gt)).sum())\n", "\n", "# Save final results to CSV\n", "file_name_final = 'final_output.csv'\n", "with open(file_name_final, mode='w', newline='') as file:\n", " writer = csv.writer(file)\n", " for item in results_eng:\n", " writer.writerow([item])" ] }, { "cell_type": "code", "execution_count": null, "id": "77de8ce3-d0b2-430a-bb06-770be235dbb0", "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.7" } }, "nbformat": 4, "nbformat_minor": 5 }