|
| 1 | +from langchain.text_splitter import RecursiveCharacterTextSplitter |
| 2 | +from langchain_community.document_loaders import PyPDFLoader |
| 3 | +from litellm import embedding |
| 4 | +from pymilvus import MilvusClient |
| 5 | +from pymilvus.exceptions import MilvusException |
| 6 | + |
| 7 | + |
| 8 | +def parse(filename: str, chunk_size: int, chunk_overlap: int) -> list[str]: |
| 9 | + loader = PyPDFLoader(filename) |
| 10 | + |
| 11 | + docs = loader.load() |
| 12 | + # 'docs' will be a list[langchain_core.documents.base.Document], |
| 13 | + # one entry per page. We don't want to return this, because PDL only |
| 14 | + # wants types that work in JSON schemas. |
| 15 | + |
| 16 | + text_splitter = RecursiveCharacterTextSplitter( |
| 17 | + chunk_size=chunk_size, |
| 18 | + chunk_overlap=chunk_overlap, |
| 19 | + length_function=len, |
| 20 | + is_separator_regex=False, |
| 21 | + ) |
| 22 | + |
| 23 | + split_docs = text_splitter.split_documents(docs) |
| 24 | + |
| 25 | + # Note that this throws away the metadata. |
| 26 | + return [doc.page_content for doc in split_docs] |
| 27 | + |
| 28 | + |
| 29 | +def rag_index( |
| 30 | + inp: list[str], |
| 31 | + encoder_model: str, |
| 32 | + embed_dimension: int, |
| 33 | + database_name: str, |
| 34 | + collection_name: str, |
| 35 | +): |
| 36 | + |
| 37 | + # Have LiteLLM embed the passages |
| 38 | + response = embedding( |
| 39 | + model=encoder_model, |
| 40 | + input=inp, |
| 41 | + ) |
| 42 | + |
| 43 | + client = MilvusClient( |
| 44 | + database_name |
| 45 | + ) # Use URL if talking to remote Milvus (non-Lite) |
| 46 | + |
| 47 | + if client.has_collection(collection_name=collection_name): |
| 48 | + client.drop_collection(collection_name=collection_name) |
| 49 | + client.create_collection( |
| 50 | + collection_name=collection_name, dimension=embed_dimension, overwrite=True |
| 51 | + ) |
| 52 | + |
| 53 | + mid = 0 # There is also an auto-id feature in Milvus, which we are not using |
| 54 | + for text in inp: |
| 55 | + vector = response.data[id]["embedding"] # type: ignore |
| 56 | + client.insert( |
| 57 | + collection_name=collection_name, |
| 58 | + data=[ |
| 59 | + { |
| 60 | + "id": mid, |
| 61 | + "text": text, |
| 62 | + "vector": vector, |
| 63 | + # We SHOULD set "source" and "url" based on the metadata we threw away in parse() |
| 64 | + } |
| 65 | + ], |
| 66 | + ) |
| 67 | + mid = mid + 1 |
| 68 | + |
| 69 | + return True |
| 70 | + |
| 71 | + |
| 72 | +# Global cache of database clients. |
| 73 | +# (We do this so the PDL programmer doesn't need to explicitly maintain the client connection) |
| 74 | +DATABASE_CLIENTS: dict[str, MilvusClient] = {} |
| 75 | + |
| 76 | + |
| 77 | +def get_or_create_client(database_name: str): |
| 78 | + if database_name in DATABASE_CLIENTS: |
| 79 | + return DATABASE_CLIENTS[database_name] |
| 80 | + |
| 81 | + client = MilvusClient( |
| 82 | + database_name |
| 83 | + ) # Use URL if talking to remote Milvus (non-Lite) |
| 84 | + DATABASE_CLIENTS[database_name] = client |
| 85 | + return client |
| 86 | + |
| 87 | + |
| 88 | +# Search vector database collection for input. |
| 89 | +# The output is 'limit' vectors, as strings, concatenated together |
| 90 | +def rag_retrieve( |
| 91 | + inp: str, encoder_model: str, limit: int, database_name: str, collection_name: str |
| 92 | +) -> str: |
| 93 | + # Embed the question as a vector |
| 94 | + try: |
| 95 | + response = embedding( |
| 96 | + model=encoder_model, |
| 97 | + input=[inp], |
| 98 | + ) |
| 99 | + except MilvusException: # This is usually a APIConnectionError |
| 100 | + # Retry because of https://github.com/BerriAI/litellm/issues/7667 |
| 101 | + response = embedding( |
| 102 | + model=encoder_model, |
| 103 | + input=[inp], |
| 104 | + ) |
| 105 | + |
| 106 | + data = response.data[0]["embedding"] |
| 107 | + |
| 108 | + milvus_client = get_or_create_client(database_name) |
| 109 | + search_res = milvus_client.search( |
| 110 | + collection_name=collection_name, |
| 111 | + data=[data], |
| 112 | + limit=limit, # Return top n results |
| 113 | + search_params={"metric_type": "COSINE", "params": {}}, |
| 114 | + output_fields=["text"], # Return the text field |
| 115 | + ) |
| 116 | + |
| 117 | + # Note that this throws away document metadata (if any) |
| 118 | + return "\n".join([res["entity"]["text"] for res in search_res[0]]) |
0 commit comments