Spaces:
Sleeping
Sleeping
File size: 5,716 Bytes
b8918cc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
import os
import subprocess
import sys
from langchain_community.embeddings import OpenAIEmbeddings
from dotenv import load_dotenv
def install_packages():
# List of packages to install in separate batches
packages_batches = [
["langchain", "langchain-openai", "langchain_core", "langchain-community", "langchainhub", "openai", "langchain-qdrant"],
["qdrant-client", "pymupdf", "pandas"],
["llama-index", "--no-cache-dir"],
["llama-parse", "PyPDF2", "tiktoken"],
["langchain-text-splitters"],
["PyPDF2"],
["scikit-learn"]
]
# Install each batch of packages
for package_list in packages_batches:
try:
print(f"Installing: {' '.join(package_list)}")
subprocess.check_call([sys.executable, "-m", "pip", "install"] + package_list)
print(f"Successfully installed: {' '.join(package_list)}\n")
except subprocess.CalledProcessError as e:
print(f"Failed to install {package_list}: {e}\n")
# Call the function to install the packages
if __name__ == "__main__":
install_packages()
# Load environment variables from .env file
load_dotenv()
# Get the OpenAI API key from the environment variables
api_key = os.getenv("OPENAI_API_KEY")
# Check if the API key is loaded
if not api_key:
print("OpenAI API key not found. Please ensure it is set in the .env file.")
else:
print("OpenAI API key loaded successfully.")
import nest_asyncio
nest_asyncio.apply()
# Function to extract text from PDF URLs
import re
import requests
from PyPDF2 import PdfReader
from io import BytesIO
# URLs for the two PDFs
pdf_urls = [
"https://www.whitehouse.gov/wp-content/uploads/2022/10/Blueprint-for-an-AI-Bill-of-Rights.pdf",
"https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.600-1.pdf"
]
def extract_text_from_pdf(url):
response = requests.get(url)
pdf_file = BytesIO(response.content)
reader = PdfReader(pdf_file)
pdf_text = ""
for page in reader.pages:
pdf_text += page.extract_text()
cleaned_text = pdf_text.replace("\n", " ").replace("\r", " ").strip()
cleaned_text = " ".join(cleaned_text.split())
sentences = re.split(r'(?<=[.!?]) +', cleaned_text)
return sentences
# Extract text from both PDFs
sentences_list = []
for url in pdf_urls:
sentences = extract_text_from_pdf(url)
sentences_list.append(sentences)
print(f"Extracted {len(sentences)} sentences from {url}")
# Semantic chunking
from langchain.embeddings.openai import OpenAIEmbeddings
from sklearn.metrics.pairwise import cosine_similarity
import tiktoken
import numpy as np
embedding_model = OpenAIEmbeddings()
flat_sentences = [sentence for sublist in sentences_list for sentence in sublist]
embeddings = embedding_model.embed_documents(flat_sentences)
def greedy_chunk_sentences(sentences, sentence_embeddings, max_chunk_size=1000, similarity_threshold=0.75):
chunks = []
current_chunk = []
current_chunk_tokens = 0
encoder = tiktoken.get_encoding("cl100k_base")
for i, sentence in enumerate(sentences):
sentence_tokens = len(encoder.encode(sentence))
if current_chunk:
similarity = cosine_similarity([sentence_embeddings[i]], [sentence_embeddings[i - 1]])[0][0]
if similarity < similarity_threshold or current_chunk_tokens + sentence_tokens > max_chunk_size:
chunks.append(" ".join(current_chunk))
current_chunk = []
current_chunk_tokens = 0
current_chunk.append(sentence)
current_chunk_tokens += sentence_tokens
if current_chunk:
chunks.append(" ".join(current_chunk))
return chunks
# Perform greedy chunking
semantic_chunks = greedy_chunk_sentences(sentences_list[0], embeddings)
# Qdrant setup for storing chunks
from qdrant_client import QdrantClient
from qdrant_client.http.models import Distance, VectorParams
from langchain_qdrant import QdrantVectorStore
from langchain.schema import Document
import uuid
LOCATION = ":memory:"
COLLECTION_NAME = "Semantic_Chunking"
qdrant_client = QdrantClient(LOCATION)
qdrant_client.create_collection(
collection_name=COLLECTION_NAME,
vectors_config=VectorParams(size=1536, distance=Distance.COSINE)
)
qdrant_vector_store = QdrantVectorStore(
client=qdrant_client,
collection_name=COLLECTION_NAME,
embedding=embedding_model,
)
documents = [Document(page_content=chunk, metadata={"source": "generated"}, id=str(uuid.uuid4())) for chunk in semantic_chunks]
qdrant_vector_store.add_documents(documents)
# Retrieve data from Qdrant
retriever = qdrant_vector_store.as_retriever()
# Define prompt and execute RAG chain
from langchain.prompts import ChatPromptTemplate
from operator import itemgetter
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
template = """
### You are a helpful assistant. Use the available context to answer the question. If you can't answer the question, say you don't know.
Question:
{question}
Context:
{context}
"""
prompt = ChatPromptTemplate.from_template(template)
primary_qa_llm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0)
retrieval_augmented_qa_chain = (
{"context": itemgetter("question") | retriever, "question": itemgetter("question")}
| RunnablePassthrough.assign(context=itemgetter("context"))
| {"response": prompt | primary_qa_llm, "context": itemgetter("context")}
)
# Query the RAG chain
question = "What are the top AI risks and how to best manage them?"
result = retrieval_augmented_qa_chain.invoke({"question": question})
print(result["response"].content)
|