meidkad commited on
Commit
c7db908
·
verified ·
1 Parent(s): 94a02d3

Upload 5 files

Browse files
Files changed (5) hide show
  1. .env +1 -0
  2. compare_embeddings.py +29 -0
  3. create_database.py +72 -0
  4. query_data.py +52 -0
  5. requirements.txt +13 -0
.env ADDED
@@ -0,0 +1 @@
 
 
1
+ OPENAI_API_KEY=sk-proj-dlXAL6ZUsd5avTHM4XWhT3BlbkFJ5HMLFh3HxqwhlBm9Yza1
compare_embeddings.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_openai import OpenAIEmbeddings
2
+ from langchain.evaluation import load_evaluator
3
+ from dotenv import load_dotenv
4
+ import openai
5
+ import os
6
+
7
+ # Load environment variables. Assumes that project contains .env file with API keys
8
+ load_dotenv()
9
+ #---- Set OpenAI API key
10
+ # Change environment variable name from "OPENAI_API_KEY" to the name given in
11
+ # your .env file.
12
+ openai.api_key = os.environ['OPENAI_API_KEY']
13
+
14
+ def main():
15
+ # Get embedding for a word.
16
+ embedding_function = OpenAIEmbeddings()
17
+ vector = embedding_function.embed_query("apple")
18
+ print(f"Vector for 'apple': {vector}")
19
+ print(f"Vector length: {len(vector)}")
20
+
21
+ # Compare vector of two words
22
+ evaluator = load_evaluator("pairwise_embedding_distance")
23
+ words = ("apple", "iphone")
24
+ x = evaluator.evaluate_string_pairs(prediction=words[0], prediction_b=words[1])
25
+ print(f"Comparing ({words[0]}, {words[1]}): {x}")
26
+
27
+
28
+ if __name__ == "__main__":
29
+ main()
create_database.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # from langchain.document_loaders import DirectoryLoader
3
+ from langchain_community.document_loaders import DirectoryLoader
4
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
5
+ from langchain.schema import Document
6
+ # from langchain.embeddings import OpenAIEmbeddings
7
+ from langchain_openai import OpenAIEmbeddings
8
+ from langchain_community.vectorstores import Chroma
9
+ import openai
10
+ from dotenv import load_dotenv
11
+ import os
12
+ import shutil
13
+
14
+ # Load environment variables. Assumes that project contains .env file with API keys
15
+ load_dotenv()
16
+ #---- Set OpenAI API key
17
+ # Change environment variable name from "OPENAI_API_KEY" to the name given in
18
+ # your .env file.
19
+ openai.api_key = os.environ['OPENAI_API_KEY']
20
+
21
+ CHROMA_PATH = "chroma"
22
+ DATA_PATH = "data/books"
23
+
24
+
25
+ def main():
26
+ generate_data_store()
27
+
28
+
29
+ def generate_data_store():
30
+ documents = load_documents()
31
+ chunks = split_text(documents)
32
+ save_to_chroma(chunks)
33
+
34
+
35
+ def load_documents():
36
+ loader = DirectoryLoader(DATA_PATH, glob="*.md")
37
+ documents = loader.load()
38
+ return documents
39
+
40
+
41
+ def split_text(documents: list[Document]):
42
+ text_splitter = RecursiveCharacterTextSplitter(
43
+ chunk_size=300,
44
+ chunk_overlap=100,
45
+ length_function=len,
46
+ add_start_index=True,
47
+ )
48
+ chunks = text_splitter.split_documents(documents)
49
+ print(f"Split {len(documents)} documents into {len(chunks)} chunks.")
50
+
51
+ document = chunks[10]
52
+ print(document.page_content)
53
+ print(document.metadata)
54
+
55
+ return chunks
56
+
57
+
58
+ def save_to_chroma(chunks: list[Document]):
59
+ # Clear out the database first.
60
+ if os.path.exists(CHROMA_PATH):
61
+ shutil.rmtree(CHROMA_PATH)
62
+
63
+ # Create a new DB from the documents.
64
+ db = Chroma.from_documents(
65
+ chunks, OpenAIEmbeddings(), persist_directory=CHROMA_PATH
66
+ )
67
+ db.persist()
68
+ print(f"Saved {len(chunks)} chunks to {CHROMA_PATH}.")
69
+
70
+
71
+ if __name__ == "__main__":
72
+ main()
query_data.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ # from dataclasses import dataclass
3
+ from langchain_community.vectorstores import Chroma
4
+ from langchain_openai import OpenAIEmbeddings
5
+ from langchain_openai import ChatOpenAI
6
+ from langchain.prompts import ChatPromptTemplate
7
+
8
+ CHROMA_PATH = "chroma"
9
+
10
+ PROMPT_TEMPLATE = """
11
+ Answer the question based only on the following context:
12
+
13
+ {context}
14
+
15
+ ---
16
+
17
+ Answer the question based on the above context: {question}
18
+ """
19
+
20
+
21
+ def main():
22
+ # Create CLI.
23
+ parser = argparse.ArgumentParser()
24
+ parser.add_argument("query_text", type=str, help="The query text.")
25
+ args = parser.parse_args()
26
+ query_text = args.query_text
27
+
28
+ # Prepare the DB.
29
+ embedding_function = OpenAIEmbeddings()
30
+ db = Chroma(persist_directory=CHROMA_PATH, embedding_function=embedding_function)
31
+
32
+ # Search the DB.
33
+ results = db.similarity_search_with_relevance_scores(query_text, k=3)
34
+ if len(results) == 0 or results[0][1] < 0.7:
35
+ print(f"Unable to find matching results.")
36
+ return
37
+
38
+ context_text = "\n\n---\n\n".join([doc.page_content for doc, _score in results])
39
+ prompt_template = ChatPromptTemplate.from_template(PROMPT_TEMPLATE)
40
+ prompt = prompt_template.format(context=context_text, question=query_text)
41
+ print(prompt)
42
+
43
+ model = ChatOpenAI()
44
+ response_text = model.predict(prompt)
45
+
46
+ sources = [doc.metadata.get("source", None) for doc, _score in results]
47
+ formatted_response = f"Response: {response_text}\nSources: {sources}"
48
+ print(formatted_response)
49
+
50
+
51
+ if __name__ == "__main__":
52
+ main()
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python-dotenv==1.0.1 # For reading environment variables stored in .env file
2
+ langchain==0.2.2
3
+ langchain-community==0.2.3
4
+ langchain-openai==0.1.8 # For embeddings
5
+ unstructured==0.14.4 # Document loading
6
+ # onnxruntime==1.17.1 # chromadb dependency: on Mac use `conda install onnxruntime -c conda-forge`
7
+ # For Windows users, install Microsoft Visual C++ Build Tools first
8
+ # install onnxruntime before installing `chromadb`
9
+ chromadb==0.5.0 # Vector storage
10
+ openai==1.31.1 # For embeddings
11
+ tiktoken==0.7.0 # For embeddings
12
+
13
+ # install markdown depenendies with: `pip install "unstructured[md]"` after install the requirements file. Leave this line commented out.