Chapter 117
RAG with Vector Search
NotebookPython 3 (ipykernel)25 cells
In [1]python · cell 1
python
import requests
docs_url = 'https://github.com/alexeygrigorev/llm-rag-workshop/raw/main/notebooks/documents.json'
docs_response = requests.get(docs_url)
documents_raw = docs_response.json()
documents = []
for course in documents_raw:
course_name = course['course']
for doc in course['documents']:
doc['course'] = course_name
documents.append(doc)In [2]python · cell 2
python
documents[2]Output
{'text': "Yes, even if you don't register, you're still eligible to submit the homeworks.\nBe aware, however, that there will be deadlines for turning in the final projects. So don't leave everything for the last minute.",
'section': 'General course-related questions',
'question': 'Course - Can I still join the course after the start date?',
'course': 'data-engineering-zoomcamp'}In [3]python · cell 3
python
import minsearch
index = minsearch.Index(
text_fields=["question", "text", "section"],
keyword_fields=["course"]
)
index.fit(documents)Output
C:\Users\alexe\miniconda3\Lib\site-packages\sklearn\utils\_param_validation.py:11: UserWarning: A NumPy version >=1.23.5 and <2.3.0 is required for this version of SciPy (detected version 2.3.0) from scipy.sparse import csr_matrix, issparse
<minsearch.minsearch.Index at 0x24a2177c320>
In [8]python · cell 4
python
from openai import OpenAI
openai_client = OpenAI()In [5]python · cell 5
python
def search(query):
boost = {'question': 3.0, 'section': 0.5}
results = index.search(
query=query,
filter_dict={'course': 'data-engineering-zoomcamp'},
boost_dict=boost,
num_results=5
)
return resultsIn [9]python · cell 6
python
def build_prompt(query, search_results):
prompt_template = """
You're a course teaching assistant. Answer the QUESTION based on the CONTEXT from the FAQ database.
Use only the facts from the CONTEXT when answering the QUESTION.
QUESTION: {question}
CONTEXT:
{context}
""".strip()
context = ""
for doc in search_results:
context = context + f"section: {doc['section']}\nquestion: {doc['question']}\nanswer: {doc['text']}\n\n"
prompt = prompt_template.format(question=query, context=context).strip()
return promptIn [10]python · cell 7
python
def llm(prompt):
response = openai_client.chat.completions.create(
model='gpt-4o-mini',
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.contentIn [11]python · cell 8
python
def rag(query):
search_results = search(query)
prompt = build_prompt(query, search_results)
answer = llm(prompt)
return answerIn [12]python · cell 9
python
rag('how do I run kafka?')Output
'To run Kafka, you can execute the following command in your project directory for the Java Kafka producer:\n\n```\njava -cp build/libs/<jar_name>-1.0-SNAPSHOT.jar:out src/main/java/org/example/JsonProducer.java\n```\n\nFor Python, ensure that you create a virtual environment and run the necessary dependencies as indicated. First, create the virtual environment and activate it:\n\n```\npython -m venv env\nsource env/bin/activate # On MacOS/Linux\n# or\nenv\\Scripts\\activate # On Windows\n```\n\nThen, install the required packages from `requirements.txt`. After setting up the environment, you can run your Python scripts. Remember that Docker images should be up and running before executing any Python files.'
In [18]python · cell 10
python
rag('the course has already started, can I still enroll?')Output
'Yes, you can still enroll in the course even if it has already started. You are also eligible to submit the homework assignments. However, make sure to pay attention to the deadlines for turning in the final projects to avoid leaving everything until the last minute.'
RAG with Vector Search
In [13]python · cell 12
python
from qdrant_client import QdrantClient, modelsIn [14]python · cell 13
python
qd_client = QdrantClient("http://localhost:6333")In [17]python · cell 14
python
EMBEDDING_DIMENSIONALITY = 512
model_handle = "jinaai/jina-embeddings-v2-small-en"In [15]python · cell 15
python
collection_name = "zoomcamp-faq"In [ ]python · cell 16
python
qd_client.delete_collection(collection_name=collection_name)In [18]python · cell 17
python
qd_client.create_collection(
collection_name=collection_name,
vectors_config=models.VectorParams(
size=EMBEDDING_DIMENSIONALITY,
distance=models.Distance.COSINE
)
)Output
True
In [35]python · cell 18
python
qd_client.create_payload_index(
collection_name=collection_name,
field_name="course",
field_schema="keyword"
)Output
UpdateResult(operation_id=2, status=<UpdateStatus.COMPLETED: 'completed'>)
In [20]python · cell 19
python
points = []
for i, doc in enumerate(documents):
text = doc['question'] + ' ' + doc['text']
vector = models.Document(text=text, model=model_handle)
point = models.PointStruct(
id=i,
vector=vector,
payload=doc
)
points.append(point)In [22]python · cell 20
python
qd_client.upsert(
collection_name=collection_name,
points=points
)Output
UpdateResult(operation_id=0, status=<UpdateStatus.COMPLETED: 'completed'>)
In [24]python · cell 21
python
question = 'I just discovered the course. Can I still join it?'In [43]python · cell 22
python
def vector_search(question):
print('vector_search is used')
course = 'data-engineering-zoomcamp'
query_points = qd_client.query_points(
collection_name=collection_name,
query=models.Document(
text=question,
model=model_handle
),
query_filter=models.Filter(
must=[
models.FieldCondition(
key="course",
match=models.MatchValue(value=course)
)
]
),
limit=5,
with_payload=True
)
results = []
for point in query_points.points:
results.append(point.payload)
return resultsIn [44]python · cell 23
python
def rag(query):
search_results = vector_search(query)
prompt = build_prompt(query, search_results)
answer = llm(prompt)
return answerIn [45]python · cell 24
python
rag('how do I run kafka?')Output
vector_search is used
'To run Kafka, you need to follow these steps based on your scripts:\n\n1. Make sure your Kafka broker is running. You can confirm this by running `docker ps`. If the broker is not active, navigate to the folder with your docker-compose yaml file and run `docker compose up -d` to start all instances.\n\n2. In your project directory, to run the producer, use the following command:\n ```\n java -cp build/libs/<jar_name>-1.0-SNAPSHOT.jar:out src/main/java/org/example/JsonProducer.java\n ```\n\n3. Ensure that the `StreamsConfig.BOOTSTRAP_SERVERS_CONFIG` in your Java scripts (e.g., JsonProducer.java, JsonConsumer.java) is set to the correct server URL. Also, verify that the cluster key and secrets in `src/main/java/org/example/Secrets.java` are updated with the correct values.\n\nBy following these steps, you should be able to run Kafka successfully.'
In [ ]python · cell 25
python
