diff --git a/bootcamp/tutorials/integration/graph_rag_with_milvus.ipynb b/bootcamp/tutorials/integration/graph_rag_with_milvus.ipynb new file mode 100644 index 000000000..53b03373a --- /dev/null +++ b/bootcamp/tutorials/integration/graph_rag_with_milvus.ipynb @@ -0,0 +1,912 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + } + }, + "source": [ + "\"Open" + ] + }, + { + "cell_type": "markdown", + "source": [ + "# Graph RAG with Milvus\n", + "\n", + "The widespread application of large language models highlights the importance of improving the accuracy and relevance of their responses. Retrieval-Augmented Generation (RAG) enhances models with external knowledge bases, providing more contextual information and mitigating issues like hallucination and insufficient knowledge. However, relying solely on simple RAG paradigms has its limitations, especially when dealing with complex entity relationships and multi-hop questions, where the model often struggles to provide accurate answers.\n", + "\n", + "Introducing knowledge graphs (KGs) into the RAG system offers a new solution. KGs present entities and their relationships in a structured way, providing more precise retrieval information and helping RAG to better handle complex question-answering tasks. KG-RAG is still in its early stages, and there is no consensus on how to effectively retrieve entities and relationships from KGs or how to integrate vector similarity search with graph structures.\n", + "\n", + "In this notebook, we introduce a simple yet powerful approach to greatly improve the performance of this scenario. It is a simple RAG paradigm with multi-way retrieval and then reranking, but it implements Graph RAG logically, and achieves state-of-the-art performance in handling multi-hop questions. Let's see how it is implemented." + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "markdown", + "source": [ + "![](../../../images/graph_rag_with_milvus_1.png)" + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + } + }, + "source": [ + "## Prerequisites\n", + "\n", + "Before running this notebook, make sure you have the following dependencies installed:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + }, + "pycharm": { + "name": "#%%\n" + } + }, + "outputs": [], + "source": [ + "! pip install --upgrade --quiet pymilvus numpy scipy langchain langchain-core langchain-openai tqdm" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + } + }, + "source": [ + "> If you are using Google Colab, to enable dependencies just installed, you may need to **restart the runtime** (click on the \"Runtime\" menu at the top of the screen, and select \"Restart session\" from the dropdown menu).\n" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + } + }, + "source": [ + "We will use the models from OpenAI. You should prepare the [api key](https://platform.openai.com/docs/quickstart) `OPENAI_API_KEY` as an environment variable." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + }, + "pycharm": { + "name": "#%%\n" + } + }, + "outputs": [], + "source": [ + "import os\n", + "\n", + "os.environ[\"OPENAI_API_KEY\"] = \"sk-***********\"" + ] + }, + { + "cell_type": "markdown", + "source": [ + "Import the necessary libraries and dependencies." + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "\n", + "from collections import defaultdict\n", + "from scipy.sparse import csr_matrix\n", + "from pymilvus import MilvusClient\n", + "from langchain_core.messages import AIMessage, HumanMessage\n", + "from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate\n", + "from langchain_core.output_parsers import StrOutputParser, JsonOutputParser\n", + "from langchain_openai import ChatOpenAI, OpenAIEmbeddings\n", + "from tqdm import tqdm" + ] + }, + { + "cell_type": "markdown", + "source": [ + "Initialize the instance of Milvus client, the LLM, and the embedding model." + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + }, + "pycharm": { + "name": "#%%\n" + } + }, + "outputs": [], + "source": [ + "milvus_client = MilvusClient(uri=\"milvus_demo.db\")\n", + "\n", + "llm = ChatOpenAI(\n", + " model=\"gpt-4o\",\n", + " temperature=0,\n", + ")\n", + "embedding_model = OpenAIEmbeddings(model=\"text-embedding-3-small\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + } + }, + "source": [ + "> For the args in MilvusClient:\n", + "> - Setting the `uri` as a local file, e.g.`./milvus.db`, is the most convenient method, as it automatically utilizes [Milvus Lite](https://milvus.io/docs/milvus_lite.md) to store all data in this file.\n", + "> - If you have large scale of data, you can set up a more performant Milvus server on [docker or kubernetes](https://milvus.io/docs/quickstart.md). In this setup, please use the server uri, e.g.`http://localhost:19530`, as your `uri`.\n", + "> - If you want to use [Zilliz Cloud](https://zilliz.com/cloud), the fully managed cloud service for Milvus, adjust the `uri` and `token`, which correspond to the [Public Endpoint and Api key](https://docs.zilliz.com/docs/on-zilliz-cloud-console#free-cluster-details) in Zilliz Cloud." + ] + }, + { + "cell_type": "markdown", + "source": [ + "## Offline Data Loading\n", + "### Data Preparation\n", + "\n", + "We will use a nano dataset which introduce the relationship between Bernoulli family and Euler to demonstrate as an example. The nano dataset contains 4 passages and a set of corresponding triplets, where each triplet contains a subject, a predicate, and an object.\n", + "In practice, you can use any approach to extract the triplets from your own custom corpus." + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + }, + "pycharm": { + "name": "#%%\n" + } + }, + "outputs": [], + "source": [ + "nano_dataset = [\n", + " {\n", + " \"passage\": \"Jakob Bernoulli (1654–1705): Jakob was one of the earliest members of the Bernoulli family to gain prominence in mathematics. He made significant contributions to calculus, particularly in the development of the theory of probability. He is known for the Bernoulli numbers and the Bernoulli theorem, a precursor to the law of large numbers. He was the older brother of Johann Bernoulli, another influential mathematician, and the two had a complex relationship that involved both collaboration and rivalry.\",\n", + " \"triplets\": [\n", + " [\"Jakob Bernoulli\", \"made significant contributions to\", \"calculus\"],\n", + " [\n", + " \"Jakob Bernoulli\",\n", + " \"made significant contributions to\",\n", + " \"the theory of probability\",\n", + " ],\n", + " [\"Jakob Bernoulli\", \"is known for\", \"the Bernoulli numbers\"],\n", + " [\"Jakob Bernoulli\", \"is known for\", \"the Bernoulli theorem\"],\n", + " [\"The Bernoulli theorem\", \"is a precursor to\", \"the law of large numbers\"],\n", + " [\"Jakob Bernoulli\", \"was the older brother of\", \"Johann Bernoulli\"],\n", + " ],\n", + " },\n", + " {\n", + " \"passage\": \"Johann Bernoulli (1667–1748): Johann, Jakob’s younger brother, was also a major figure in the development of calculus. He worked on infinitesimal calculus and was instrumental in spreading the ideas of Leibniz across Europe. Johann also contributed to the calculus of variations and was known for his work on the brachistochrone problem, which is the curve of fastest descent between two points.\",\n", + " \"triplets\": [\n", + " [\n", + " \"Johann Bernoulli\",\n", + " \"was a major figure of\",\n", + " \"the development of calculus\",\n", + " ],\n", + " [\"Johann Bernoulli\", \"was\", \"Jakob's younger brother\"],\n", + " [\"Johann Bernoulli\", \"worked on\", \"infinitesimal calculus\"],\n", + " [\"Johann Bernoulli\", \"was instrumental in spreading\", \"Leibniz's ideas\"],\n", + " [\"Johann Bernoulli\", \"contributed to\", \"the calculus of variations\"],\n", + " [\"Johann Bernoulli\", \"was known for\", \"the brachistochrone problem\"],\n", + " ],\n", + " },\n", + " {\n", + " \"passage\": \"Daniel Bernoulli (1700–1782): The son of Johann Bernoulli, Daniel made major contributions to fluid dynamics, probability, and statistics. He is most famous for Bernoulli’s principle, which describes the behavior of fluid flow and is fundamental to the understanding of aerodynamics.\",\n", + " \"triplets\": [\n", + " [\"Daniel Bernoulli\", \"was the son of\", \"Johann Bernoulli\"],\n", + " [\"Daniel Bernoulli\", \"made major contributions to\", \"fluid dynamics\"],\n", + " [\"Daniel Bernoulli\", \"made major contributions to\", \"probability\"],\n", + " [\"Daniel Bernoulli\", \"made major contributions to\", \"statistics\"],\n", + " [\"Daniel Bernoulli\", \"is most famous for\", \"Bernoulli’s principle\"],\n", + " [\n", + " \"Bernoulli’s principle\",\n", + " \"is fundamental to\",\n", + " \"the understanding of aerodynamics\",\n", + " ],\n", + " ],\n", + " },\n", + " {\n", + " \"passage\": \"Leonhard Euler (1707–1783) was one of the greatest mathematicians of all time, and his relationship with the Bernoulli family was significant. Euler was born in Basel and was a student of Johann Bernoulli, who recognized his exceptional talent and mentored him in mathematics. Johann Bernoulli’s influence on Euler was profound, and Euler later expanded upon many of the ideas and methods he learned from the Bernoullis.\",\n", + " \"triplets\": [\n", + " [\n", + " \"Leonhard Euler\",\n", + " \"had a significant relationship with\",\n", + " \"the Bernoulli family\",\n", + " ],\n", + " [\"leonhard Euler\", \"was born in\", \"Basel\"],\n", + " [\"Leonhard Euler\", \"was a student of\", \"Johann Bernoulli\"],\n", + " [\"Johann Bernoulli's influence\", \"was profound on\", \"Euler\"],\n", + " ],\n", + " },\n", + "]" + ] + }, + { + "cell_type": "markdown", + "source": [ + "Based on the dataset, we can construct some dicts to store the mapping between entities, relations, and passages, which are useful for later data inserting and graph structure construction.\n", + "\n", + "We construct the entites and relations as follows:\n", + "- The entity is the subject or object in the triplet, so we directly extract them from the triplets.\n", + "- Here we construct the concept of relationship by directly concatenating the subject, predicate, and object with a space in between.\n" + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + }, + "pycharm": { + "name": "#%%\n" + } + }, + "outputs": [], + "source": [ + "entityid_2_relationids = defaultdict(list)\n", + "relationid_2_entityids = defaultdict(list)\n", + "relationid_2_passageids = defaultdict(list)\n", + "entityid_2_passageids = defaultdict(list)\n", + "\n", + "entities = []\n", + "relations = []\n", + "passages = []\n", + "for passage_id, dataset_info in enumerate(nano_dataset):\n", + " passage, triplets = dataset_info[\"passage\"], dataset_info[\"triplets\"]\n", + " passages.append(passage)\n", + " for triplet in triplets:\n", + " if triplet[0] not in entities:\n", + " entities.append(triplet[0])\n", + " entityid_2_passageids[entities.index(triplet[0])].append(passage_id)\n", + " if triplet[2] not in entities:\n", + " entities.append(triplet[2])\n", + " entityid_2_passageids[entities.index(triplet[2])].append(passage_id)\n", + " relation = \" \".join(triplet)\n", + " if relation not in relations:\n", + " relations.append(relation)\n", + " relationid_2_entityids[len(relations) - 1] = [\n", + " entities.index(triplet[0]),\n", + " entities.index(triplet[2]),\n", + " ]\n", + " entityid_2_relationids[entities.index(triplet[0])].append(\n", + " len(relations) - 1\n", + " )\n", + " entityid_2_relationids[entities.index(triplet[2])].append(\n", + " len(relations) - 1\n", + " )\n", + " relationid_2_passageids[relations.index(relation)].append(passage_id)" + ] + }, + { + "cell_type": "markdown", + "source": [ + "### Data Insertion\n", + "\n", + "Create Milvus collections for entity, relation, and passage. The entity collection and relation collection are used as the major collections for graph construction in our method, while the passage collection is used as the naive RAG retrieval comparison or auxiliary purpose." + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + }, + "pycharm": { + "name": "#%%\n" + } + }, + "outputs": [], + "source": [ + "embedding_dim = len(embedding_model.embed_query(\"foo\"))\n", + "\n", + "\n", + "def create_milvus_collection(collection_name: str):\n", + " if milvus_client.has_collection(collection_name=collection_name):\n", + " milvus_client.drop_collection(collection_name=collection_name)\n", + " milvus_client.create_collection(\n", + " collection_name=collection_name,\n", + " dimension=embedding_dim,\n", + " consistency_level=\"Strong\",\n", + " )\n", + "\n", + "\n", + "entity_col_name = \"entity_collection\"\n", + "relation_col_name = \"relation_collection\"\n", + "passage_col_name = \"passage_collection\"\n", + "create_milvus_collection(entity_col_name)\n", + "create_milvus_collection(relation_col_name)\n", + "create_milvus_collection(passage_col_name)" + ] + }, + { + "cell_type": "markdown", + "source": [ + "Insert the data with their metadata information into Milvus collections, including entity, relation, and passage collections. The metadata information includes the passage id and the adjacency entity or relation id." + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + }, + "pycharm": { + "name": "#%%\n" + } + }, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Inserting: 100%|███████████████████████████████████| 1/1 [00:00<00:00, 1.02it/s]\n", + "Inserting: 100%|███████████████████████████████████| 1/1 [00:00<00:00, 1.39it/s]\n", + "Inserting: 100%|███████████████████████████████████| 1/1 [00:00<00:00, 2.28it/s]\n" + ] + } + ], + "source": [ + "def milvus_insert(\n", + " collection_name: str,\n", + " text_list: list[str],\n", + " metadatas: list[dict] = None,\n", + "):\n", + " batch_size = 512\n", + " if metadatas:\n", + " assert len(text_list) == len(metadatas)\n", + " for row_id in tqdm(range(0, len(text_list), batch_size), desc=\"Inserting\"):\n", + " batch_texts = text_list[row_id : row_id + batch_size]\n", + " batch_embeddings = embedding_model.embed_documents(batch_texts)\n", + "\n", + " batch_ids = [row_id + j for j in range(len(batch_texts))]\n", + " batch_data = [\n", + " {\n", + " \"id\": id_,\n", + " \"text\": text,\n", + " \"vector\": vector,\n", + " }\n", + " for id_, text, vector in zip(batch_ids, batch_texts, batch_embeddings)\n", + " ]\n", + " if metadatas:\n", + " batch_metadatas = metadatas[row_id : row_id + batch_size]\n", + " for data, metadata in zip(batch_data, batch_metadatas):\n", + " data.update(metadata)\n", + "\n", + " milvus_client.insert(\n", + " collection_name=collection_name,\n", + " data=batch_data,\n", + " )\n", + "\n", + "\n", + "milvus_insert(\n", + " collection_name=relation_col_name,\n", + " text_list=relations,\n", + " metadatas=[\n", + " {\n", + " \"passage_id\": relationid_2_passageids[relation_id],\n", + " \"entity_ids\": relationid_2_entityids[relation_id],\n", + " }\n", + " for relation_id, relation in enumerate(relations)\n", + " ],\n", + ")\n", + "\n", + "milvus_insert(\n", + " collection_name=entity_col_name,\n", + " text_list=entities,\n", + " metadatas=[\n", + " {\n", + " \"passage_id\": entityid_2_passageids[entity_id],\n", + " \"relation_id\": entityid_2_relationids[entity_id],\n", + " }\n", + " for entity_id, entity in enumerate(entities)\n", + " ],\n", + ")\n", + "\n", + "milvus_insert(\n", + " collection_name=passage_col_name,\n", + " text_list=passages,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "source": [ + "## Online Querying\n", + "### Similarity Retrieval\n", + "We retrieve the topK similar entities and relations based on the input query from Milvus.\n", + "\n", + "When performing the entity retrieving, we should first extract the query entities from the query text using some specific method like NER (Named-entity recognition). For simplicity, we prepare the NER results here. If you want to change the query as your custom question, you have to change the corresponding query NER list.\n", + "In practice, you can use any other model or approach to extract the entities from the query." + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + }, + "pycharm": { + "name": "#%%\n" + } + }, + "outputs": [], + "source": [ + "query = \"What contribution did the son of Euler's teacher make?\"\n", + "\n", + "query_ner_list = [\"Euler\"]\n", + "# query_ner_list = ner(query) # In practice, replace it with your custom NER approach\n", + "\n", + "query_ner_embeddings = [\n", + " embedding_model.embed_query(query_ner) for query_ner in query_ner_list\n", + "]\n", + "\n", + "top_k = 3\n", + "\n", + "entity_search_res = milvus_client.search(\n", + " collection_name=entity_col_name,\n", + " data=query_ner_embeddings,\n", + " limit=top_k,\n", + " output_fields=[\"id\"],\n", + ")\n", + "\n", + "query_embedding = embedding_model.embed_query(query)\n", + "\n", + "relation_search_res = milvus_client.search(\n", + " collection_name=relation_col_name,\n", + " data=[query_embedding],\n", + " limit=top_k,\n", + " output_fields=[\"id\"],\n", + ")[0]" + ] + }, + { + "cell_type": "markdown", + "source": [ + "### Expand Subgraph\n", + "\n", + "We use the retrieved entities and relations to expand the subgraph and obtain the candidate relationships, and then merge them from the two ways. Here is a flow chart of the subgraph expansion process:\n", + "![](../../../images/graph_rag_with_milvus_2.png)" + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "markdown", + "source": [ + "Here we construct an adjacency matrix and use matrix multiplication to calculate the adjacency mapping information within a few degrees. In this way, we can quickly obtain information of any degree of expansion." + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + }, + "pycharm": { + "name": "#%%\n" + } + }, + "outputs": [], + "source": [ + "# Construct the adjacency matrix of entities and relations where the value of the adjacency matrix is 1 if an entity is related to a relation, otherwise 0.\n", + "entity_relation_adj = np.zeros((len(entities), len(relations)))\n", + "for entity_id, entity in enumerate(entities):\n", + " entity_relation_adj[entity_id, entityid_2_relationids[entity_id]] = 1\n", + "\n", + "# Convert the adjacency matrix to a sparse matrix for efficient computation.\n", + "entity_relation_adj = csr_matrix(entity_relation_adj)\n", + "\n", + "# Use the entity-relation adjacency matrix to construct 1 degree entity-entity and relation-relation adjacency matrices.\n", + "entity_adj_1_degree = entity_relation_adj @ entity_relation_adj.T\n", + "relation_adj_1_degree = entity_relation_adj.T @ entity_relation_adj\n", + "\n", + "# Specify the target degree of the subgraph to be expanded.\n", + "# 1 or 2 is enough for most cases.\n", + "target_degree = 1\n", + "\n", + "# Compute the target degree adjacency matrices using matrix multiplication.\n", + "entity_adj_target_degree = entity_adj_1_degree\n", + "for _ in range(target_degree - 1):\n", + " entity_adj_target_degree = entity_adj_target_degree * entity_adj_1_degree\n", + "relation_adj_target_degree = relation_adj_1_degree\n", + "for _ in range(target_degree - 1):\n", + " relation_adj_target_degree = relation_adj_target_degree * relation_adj_1_degree\n", + "\n", + "entity_relation_adj_target_degree = entity_adj_target_degree @ entity_relation_adj" + ] + }, + { + "cell_type": "markdown", + "source": [ + "By taking the value from the target degree expansion matrix, we can easily expand the corresponding degree from the retrieved entity and relations to obtain all relations of the subgraph." + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "code", + "execution_count": null, + "outputs": [], + "source": [ + "expanded_relations_from_relation = set()\n", + "expanded_relations_from_entity = set()\n", + "# You can set the similarity threshold here to guarantee the quality of the retrieved ones.\n", + "# entity_sim_filter_thresh = ...\n", + "# relation_sim_filter_thresh = ...\n", + "\n", + "filtered_hit_relation_ids = [\n", + " relation_res[\"entity\"][\"id\"]\n", + " for relation_res in relation_search_res\n", + " # if relation_res['distance'] > relation_sim_filter_thresh\n", + "]\n", + "for hit_relation_id in filtered_hit_relation_ids:\n", + " expanded_relations_from_relation.update(\n", + " relation_adj_target_degree[hit_relation_id].nonzero()[1].tolist()\n", + " )\n", + "\n", + "filtered_hit_entity_ids = [\n", + " one_entity_res[\"entity\"][\"id\"]\n", + " for one_entity_search_res in entity_search_res\n", + " for one_entity_res in one_entity_search_res\n", + " # if one_entity_res['distance'] > entity_sim_filter_thresh\n", + "]\n", + "\n", + "for filtered_hit_entity_id in filtered_hit_entity_ids:\n", + " expanded_relations_from_entity.update(\n", + " entity_relation_adj_target_degree[filtered_hit_entity_id].nonzero()[1].tolist()\n", + " )\n", + "\n", + "# Merge the expanded relations from the relation and entity retrieval ways.\n", + "relation_candidate_ids = list(\n", + " expanded_relations_from_relation | expanded_relations_from_entity\n", + ")\n", + "\n", + "relation_candidate_texts = [\n", + " relations[relation_id] for relation_id in relation_candidate_ids\n", + "]" + ], + "metadata": { + "collapsed": false, + "pycharm": { + "name": "#%%\n" + } + } + }, + { + "cell_type": "markdown", + "source": [ + "We have get the candidate relationships by expanding the subgraph, which will be reranked by LLM in the next step." + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "markdown", + "source": [ + "### LLM reranking\n", + "\n", + "In this stage, we deploy the powerful self-attention mechanism of LLM to further filter and refine the candidate set of relationships. We employ a one-shot prompt, incorporating the query and the candidate set of relationships into the prompt, and instruct LLM to select potential relationships that could assist in answering the query. Given that some queries may be complex, we adopt the Chain-of-Thought approach, allowing LLM to articulate its thought process in its response. We stipulate that LLM's response is in json format for convenient parsing." + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + }, + "pycharm": { + "name": "#%%\n" + } + }, + "outputs": [], + "source": [ + "query_prompt_one_shot_input = \"\"\"I will provide you with a list of relationship descriptions. Your task is to select 3 relationships that may be useful to answer the given question. Please return a JSON object containing your thought process and a list of the selected relationships in order of their relevance.\n", + "\n", + "Question:\n", + "When was the mother of the leader of the Third Crusade born?\n", + "\n", + "Relationship descriptions:\n", + "[1] Eleanor was born in 1122.\n", + "[2] Eleanor married King Louis VII of France.\n", + "[3] Eleanor was the Duchess of Aquitaine.\n", + "[4] Eleanor participated in the Second Crusade.\n", + "[5] Eleanor had eight children.\n", + "[6] Eleanor was married to Henry II of England.\n", + "[7] Eleanor was the mother of Richard the Lionheart.\n", + "[8] Richard the Lionheart was the King of England.\n", + "[9] Henry II was the father of Richard the Lionheart.\n", + "[10] Henry II was the King of England.\n", + "[11] Richard the Lionheart led the Third Crusade.\n", + "\n", + "\"\"\"\n", + "query_prompt_one_shot_output = \"\"\"{\"thought_process\": \"To answer the question about the birth of the mother of the leader of the Third Crusade, I first need to identify who led the Third Crusade and then determine who his mother was. After identifying his mother, I can look for the relationship that mentions her birth.\", \"useful_relationships\": [\"[11] Richard the Lionheart led the Third Crusade\", \"[7] Eleanor was the mother of Richard the Lionheart\", \"[1] Eleanor was born in 1122\"]}\"\"\"\n", + "\n", + "query_prompt_template = \"\"\"Question:\n", + "{question}\n", + "\n", + "Relationship descriptions:\n", + "{relation_des_str}\n", + "\n", + "\"\"\"\n", + "\n", + "\n", + "def rerank_relations(\n", + " query: str, relation_candidate_texts: list[str], relation_candidate_ids: list[str]\n", + ") -> list[int]:\n", + " relation_des_str = \"\\n\".join(\n", + " map(\n", + " lambda item: f\"[{item[0]}] {item[1]}\",\n", + " zip(relation_candidate_ids, relation_candidate_texts),\n", + " )\n", + " ).strip()\n", + " rerank_prompts = ChatPromptTemplate.from_messages(\n", + " [\n", + " HumanMessage(query_prompt_one_shot_input),\n", + " AIMessage(query_prompt_one_shot_output),\n", + " HumanMessagePromptTemplate.from_template(query_prompt_template),\n", + " ]\n", + " )\n", + " rerank_chain = (\n", + " rerank_prompts\n", + " | llm.bind(response_format={\"type\": \"json_object\"})\n", + " | JsonOutputParser()\n", + " )\n", + " rerank_res = rerank_chain.invoke(\n", + " {\"question\": query, \"relation_des_str\": relation_des_str}\n", + " )\n", + " rerank_relation_ids = []\n", + " rerank_relation_lines = rerank_res[\"useful_relationships\"]\n", + " id_2_lines = {}\n", + " for line in rerank_relation_lines:\n", + " id_ = int(line[line.find(\"[\") + 1 : line.find(\"]\")])\n", + " id_2_lines[id_] = line.strip()\n", + " rerank_relation_ids.append(id_)\n", + " return rerank_relation_ids\n", + "\n", + "\n", + "rerank_relation_ids = rerank_relations(\n", + " query,\n", + " relation_candidate_texts=relation_candidate_texts,\n", + " relation_candidate_ids=relation_candidate_ids,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "source": [ + "### Get Final Results\n", + "\n", + "We can get final retrieved passages from the reranked relationships." + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + }, + "pycharm": { + "name": "#%%\n" + } + }, + "outputs": [], + "source": [ + "final_top_k = 2\n", + "\n", + "final_passages = []\n", + "final_passage_ids = []\n", + "for relation_id in rerank_relation_ids:\n", + " for passage_id in relationid_2_passageids[relation_id]:\n", + " if passage_id not in final_passage_ids:\n", + " final_passage_ids.append(passage_id)\n", + " final_passages.append(passages[passage_id])\n", + "passages_from_our_method = final_passages[:final_top_k]" + ] + }, + { + "cell_type": "markdown", + "source": [ + "\n", + "We can compare the results with the naive RAG method, which retrieves the topK passages based on the query embedding directly from the passage collection." + ], + "metadata": { + "collapsed": false + } + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + }, + "pycharm": { + "name": "#%%\n" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Passages retrieved from naive RAG: \n", + "['Leonhard Euler (1707–1783) was one of the greatest mathematicians of all time, and his relationship with the Bernoulli family was significant. Euler was born in Basel and was a student of Johann Bernoulli, who recognized his exceptional talent and mentored him in mathematics. Johann Bernoulli’s influence on Euler was profound, and Euler later expanded upon many of the ideas and methods he learned from the Bernoullis.', 'Johann Bernoulli (1667–1748): Johann, Jakob’s younger brother, was also a major figure in the development of calculus. He worked on infinitesimal calculus and was instrumental in spreading the ideas of Leibniz across Europe. Johann also contributed to the calculus of variations and was known for his work on the brachistochrone problem, which is the curve of fastest descent between two points.']\n", + "\n", + "Passages retrieved from our method: \n", + "['Leonhard Euler (1707–1783) was one of the greatest mathematicians of all time, and his relationship with the Bernoulli family was significant. Euler was born in Basel and was a student of Johann Bernoulli, who recognized his exceptional talent and mentored him in mathematics. Johann Bernoulli’s influence on Euler was profound, and Euler later expanded upon many of the ideas and methods he learned from the Bernoullis.', 'Daniel Bernoulli (1700–1782): The son of Johann Bernoulli, Daniel made major contributions to fluid dynamics, probability, and statistics. He is most famous for Bernoulli’s principle, which describes the behavior of fluid flow and is fundamental to the understanding of aerodynamics.']\n", + "\n", + "\n", + "Answer from naive RAG: I don't know. The retrieved context does not provide information about the contributions made by the son of Euler's teacher.\n", + "\n", + "Answer from our method: The son of Euler's teacher, Daniel Bernoulli, made major contributions to fluid dynamics, probability, and statistics. He is most famous for Bernoulli’s principle, which describes the behavior of fluid flow and is fundamental to the understanding of aerodynamics.\n" + ] + } + ], + "source": [ + "naive_passage_res = milvus_client.search(\n", + " collection_name=passage_col_name,\n", + " data=[query_embedding],\n", + " limit=final_top_k,\n", + " output_fields=[\"text\"],\n", + ")[0]\n", + "passages_from_naive_rag = [res[\"entity\"][\"text\"] for res in naive_passage_res]\n", + "\n", + "print(\n", + " f\"Passages retrieved from naive RAG: \\n{passages_from_naive_rag}\\n\\n\"\n", + " f\"Passages retrieved from our method: \\n{passages_from_our_method}\\n\\n\"\n", + ")\n", + "\n", + "\n", + "prompt = ChatPromptTemplate.from_messages(\n", + " [\n", + " (\n", + " \"human\",\n", + " \"\"\"Use the following pieces of retrieved context to answer the question. If there is not enough information in the retrieved context to answer the question, just say that you don't know.\n", + "Question: {question}\n", + "Context: {context}\n", + "Answer:\"\"\",\n", + " )\n", + " ]\n", + ")\n", + "\n", + "rag_chain = prompt | llm | StrOutputParser()\n", + "\n", + "answer_from_naive_rag = rag_chain.invoke(\n", + " {\"question\": query, \"context\": \"\\n\".join(passages_from_naive_rag)}\n", + ")\n", + "answer_from_our_method = rag_chain.invoke(\n", + " {\"question\": query, \"context\": \"\\n\".join(passages_from_our_method)}\n", + ")\n", + "\n", + "print(\n", + " f\"Answer from naive RAG: {answer_from_naive_rag}\\n\\nAnswer from our method: {answer_from_our_method}\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "source": [ + "As we can see, the retrieved passages from the naive RAG missed a ground-truth passage, which led to a wrong answer.\n", + "The retrieved passages from our method are correct, and it helps to get an accurate answer to the question." + ], + "metadata": { + "collapsed": false, + "pycharm": { + "name": "#%% md\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.10.13" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/images/graph_rag_with_milvus_1.png b/images/graph_rag_with_milvus_1.png new file mode 100644 index 000000000..3eda994b7 Binary files /dev/null and b/images/graph_rag_with_milvus_1.png differ diff --git a/images/graph_rag_with_milvus_2.png b/images/graph_rag_with_milvus_2.png new file mode 100644 index 000000000..95827ff81 Binary files /dev/null and b/images/graph_rag_with_milvus_2.png differ