Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

fix(hybrid_rag_system): remove unresolved merge conflict markers

Rudy Celekli1deecb66a71a
diff --git a/rag_apps/hybrid_rag_system/.env.example b/rag_apps/hybrid_rag_system/.env.example
index 160dace..86490cc 100644
--- a/rag_apps/hybrid_rag_system/.env.example
+++ b/rag_apps/hybrid_rag_system/.env.example
@@ -1,5 +1,2 @@
-<<<<<<< HEAD
-=======
# Your Mistral AI API key. Get one for free at https://platform.mistral.ai
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
MISTRAL_API_KEY=your_mistral_api_key_here
diff --git a/rag_apps/hybrid_rag_system/app.py b/rag_apps/hybrid_rag_system/app.py
index 99eac49..4f34d45 100644
--- a/rag_apps/hybrid_rag_system/app.py
+++ b/rag_apps/hybrid_rag_system/app.py
@@ -1,7 +1,4 @@
-<<<<<<< HEAD
-=======
"""Streamlit application combining knowledge graph retrieval and vector retrieval into a hybrid RAG pipeline for document question answering."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import os
import sys
import time
diff --git a/rag_apps/hybrid_rag_system/src/context_fusion.py b/rag_apps/hybrid_rag_system/src/context_fusion.py
index e02db09..39b9ce5 100644
--- a/rag_apps/hybrid_rag_system/src/context_fusion.py
+++ b/rag_apps/hybrid_rag_system/src/context_fusion.py
@@ -2,10 +2,7 @@ from typing import Any
def format_graph_context(graph_results: dict[str, Any]) -> str:
-<<<<<<< HEAD
-=======
"""Formats graph retrieval results into a plain-text block listing entities and relationships."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
entities = graph_results.get("entities", [])
relationships = graph_results.get("relationships", [])
@@ -31,10 +28,7 @@ def format_graph_context(graph_results: dict[str, Any]) -> str:
def format_vector_context(vector_results: list[dict[str, Any]]) -> str:
-<<<<<<< HEAD
-=======
"""Formats vector retrieval results into a plain-text block of numbered chunks with similarity scores."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if not vector_results:
return "No vector context available."
lines = []
@@ -50,10 +44,7 @@ def fuse_context(
graph_results: dict[str, Any],
vector_results: list[dict[str, Any]],
) -> str:
-<<<<<<< HEAD
-=======
"""Combines formatted graph and vector contexts into a single prompt-ready string."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
graph_ctx = format_graph_context(graph_results)
vector_ctx = format_vector_context(vector_results)
return (
diff --git a/rag_apps/hybrid_rag_system/src/document_processor.py b/rag_apps/hybrid_rag_system/src/document_processor.py
index 53da6c9..23072b0 100644
--- a/rag_apps/hybrid_rag_system/src/document_processor.py
+++ b/rag_apps/hybrid_rag_system/src/document_processor.py
@@ -9,10 +9,7 @@ from config import CACHE_FILE, CHUNK_SIZE, CHUNK_OVERLAP
def load_document(file_bytes: bytes, filename: str) -> str:
-<<<<<<< HEAD
-=======
"""Reads a PDF or TXT file from bytes and returns its full text content."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
suffix = Path(filename).suffix.lower()
if suffix == ".pdf":
import io
@@ -30,10 +27,7 @@ def load_document(file_bytes: bytes, filename: str) -> str:
def chunk_text(text: str) -> list[str]:
-<<<<<<< HEAD
-=======
"""Splits text into overlapping chunks using LangChain's RecursiveCharacterTextSplitter."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
splitter = RecursiveCharacterTextSplitter(
chunk_size=CHUNK_SIZE,
chunk_overlap=CHUNK_OVERLAP,
@@ -43,18 +37,12 @@ def chunk_text(text: str) -> list[str]:
def compute_hash(content: str) -> str:
-<<<<<<< HEAD
-=======
"""Returns an MD5 hex digest of the given text string."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return hashlib.md5(content.encode()).hexdigest()
def load_cache() -> dict:
-<<<<<<< HEAD
-=======
"""Loads the processed-documents registry from disk, returning an empty dict if absent or unreadable."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if CACHE_FILE.exists():
try:
return json.loads(CACHE_FILE.read_text(encoding="utf-8"))
@@ -64,26 +52,17 @@ def load_cache() -> dict:
def save_cache(cache: dict) -> None:
-<<<<<<< HEAD
-=======
"""Writes the processed-documents registry to disk as JSON."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
CACHE_FILE.write_text(json.dumps(cache, indent=2), encoding="utf-8")
def is_cached(content_hash: str) -> Optional[dict]:
-<<<<<<< HEAD
-=======
"""Returns the cached metadata dict for a document hash, or None if it has not been indexed."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return load_cache().get(content_hash)
def add_to_cache(content_hash: str, filename: str, num_chunks: int, num_entities: int) -> None:
-<<<<<<< HEAD
-=======
"""Adds a processed document's metadata to the on-disk cache."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
cache = load_cache()
cache[content_hash] = {
"filename": filename,
@@ -95,8 +74,5 @@ def add_to_cache(content_hash: str, filename: str, num_chunks: int, num_entities
def list_cached_docs() -> list[dict]:
-<<<<<<< HEAD
-=======
"""Returns a list of all cached document metadata dicts."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return list(load_cache().values())
diff --git a/rag_apps/hybrid_rag_system/src/graph_indexer.py b/rag_apps/hybrid_rag_system/src/graph_indexer.py
index 2ab4e2f..b6458a4 100644
--- a/rag_apps/hybrid_rag_system/src/graph_indexer.py
+++ b/rag_apps/hybrid_rag_system/src/graph_indexer.py
@@ -31,10 +31,7 @@ JSON:"""
def _parse_extraction(raw: str) -> dict:
-<<<<<<< HEAD
-=======
"""Extracts the first JSON object from a raw string and returns it as a dict, or an empty scaffold on failure."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
match = re.search(r'\{.*\}', raw, re.DOTALL)
if match:
try:
@@ -45,10 +42,7 @@ def _parse_extraction(raw: str) -> dict:
def _extract_from_chunk(client: Mistral, text: str) -> dict:
-<<<<<<< HEAD
-=======
"""Sends a text chunk to Mistral and returns extracted entities and relationships, retrying up to three times."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
for attempt in range(3):
try:
resp = client.chat.complete(
@@ -69,10 +63,7 @@ def build_doc_graph(
client: Mistral,
progress_cb: Optional[Callable[[int, int], None]] = None,
) -> nx.Graph:
-<<<<<<< HEAD
-=======
"""Builds a NetworkX graph from a list of text chunks by extracting entities and relationships via Mistral."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
G = nx.Graph()
for i, chunk in enumerate(chunks):
if progress_cb:
@@ -118,10 +109,7 @@ def build_doc_graph(
def merge_into_combined(G_new: nx.Graph) -> nx.Graph:
-<<<<<<< HEAD
-=======
"""Merges a new document graph into the persisted combined graph and saves it."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
G = load_combined_graph()
for node, data in G_new.nodes(data=True):
if G.has_node(node):
@@ -143,20 +131,14 @@ def merge_into_combined(G_new: nx.Graph) -> nx.Graph:
def save_doc_graph(G: nx.Graph, doc_hash: str) -> None:
-<<<<<<< HEAD
-=======
"""Serialises a document graph to a JSON file named by its hash."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
path = GRAPHS_DIR / f"{doc_hash}.json"
data = nx.node_link_data(G)
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
def load_combined_graph() -> nx.Graph:
-<<<<<<< HEAD
-=======
"""Loads the combined graph from disk, returning an empty graph if not found."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if COMBINED_GRAPH_FILE.exists():
try:
data = json.loads(COMBINED_GRAPH_FILE.read_text(encoding="utf-8"))
@@ -167,9 +149,6 @@ def load_combined_graph() -> nx.Graph:
def save_combined_graph(G: nx.Graph) -> None:
-<<<<<<< HEAD
-=======
"""Serialises the combined graph to its fixed JSON path."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
data = nx.node_link_data(G)
COMBINED_GRAPH_FILE.write_text(json.dumps(data, indent=2), encoding="utf-8")
diff --git a/rag_apps/hybrid_rag_system/src/graph_retriever.py b/rag_apps/hybrid_rag_system/src/graph_retriever.py
index ffa01c0..cfac56a 100644
--- a/rag_apps/hybrid_rag_system/src/graph_retriever.py
+++ b/rag_apps/hybrid_rag_system/src/graph_retriever.py
@@ -14,19 +14,13 @@ _STOP_WORDS = {
def _query_terms(query: str) -> list[str]:
-<<<<<<< HEAD
-=======
"""Tokenises a query string and returns non-stop-word terms longer than two characters."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
words = re.findall(r'\b\w+\b', query.lower())
return [w for w in words if w not in _STOP_WORDS and len(w) > 2]
def _score_node(node_name: str, terms: list[str]) -> float:
-<<<<<<< HEAD
-=======
"""Returns a relevance score for a graph node based on how many query terms match its name."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
name_lower = node_name.lower()
score = 0.0
for term in terms:
@@ -38,10 +32,7 @@ def _score_node(node_name: str, terms: list[str]) -> float:
def retrieve_from_graph(G: nx.Graph, query: str, max_entities: int) -> dict[str, Any]:
-<<<<<<< HEAD
-=======
"""Performs BFS from top-scoring seed nodes and returns matched entities and relationships up to max_entities."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if G.number_of_nodes() == 0:
return {"entities": [], "relationships": [], "seed_nodes": []}
diff --git a/rag_apps/hybrid_rag_system/src/mistral_client.py b/rag_apps/hybrid_rag_system/src/mistral_client.py
index f852646..7e1d96d 100644
--- a/rag_apps/hybrid_rag_system/src/mistral_client.py
+++ b/rag_apps/hybrid_rag_system/src/mistral_client.py
@@ -18,10 +18,7 @@ Provide a clear, well-structured answer based on the context above."""
def generate_answer(client: Mistral, question: str, fused_context: str) -> str:
-<<<<<<< HEAD
-=======
"""Sends the fused context and question to Mistral Small 4 and returns the generated answer string."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
resp = client.chat.complete(
model="mistral-small-latest",
messages=[
diff --git a/rag_apps/hybrid_rag_system/src/vector_indexer.py b/rag_apps/hybrid_rag_system/src/vector_indexer.py
index b9f3805..b144fd7 100644
--- a/rag_apps/hybrid_rag_system/src/vector_indexer.py
+++ b/rag_apps/hybrid_rag_system/src/vector_indexer.py
@@ -21,10 +21,7 @@ class OllamaEmbeddingFunction(EmbeddingFunction):
def check_ollama() -> tuple[bool, str]:
-<<<<<<< HEAD
-=======
"""Checks whether Ollama is reachable and whether the embedding model is installed, returning a status tuple."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
try:
resp = requests.get(f"{OLLAMA_URL}/api/tags", timeout=5)
if resp.status_code == 200:
@@ -39,10 +36,7 @@ def check_ollama() -> tuple[bool, str]:
def get_chroma_collection() -> chromadb.Collection:
-<<<<<<< HEAD
-=======
"""Creates or retrieves the persistent ChromaDB collection using the Ollama embedding function."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
client = chromadb.PersistentClient(path=str(CHROMA_DIR))
return client.get_or_create_collection(
name=CHROMA_COLLECTION,
@@ -57,10 +51,7 @@ def index_chunks(
doc_hash: str,
progress_cb: Optional[Callable[[int, int], None]] = None,
) -> None:
-<<<<<<< HEAD
-=======
"""Embeds and stores text chunks in ChromaDB, calling progress_cb after each batch."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
batch_size = 5
total = len(chunks)
for i in range(0, total, batch_size):
@@ -73,10 +64,7 @@ def index_chunks(
def collection_has_doc(collection: chromadb.Collection, doc_hash: str) -> bool:
-<<<<<<< HEAD
-=======
"""Returns True if the ChromaDB collection already contains chunks for the given document hash."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
try:
results = collection.get(where={"doc_hash": doc_hash}, limit=1)
return len(results["ids"]) > 0
diff --git a/rag_apps/hybrid_rag_system/src/vector_retriever.py b/rag_apps/hybrid_rag_system/src/vector_retriever.py
index db44251..b3f7386 100644
--- a/rag_apps/hybrid_rag_system/src/vector_retriever.py
+++ b/rag_apps/hybrid_rag_system/src/vector_retriever.py
@@ -7,10 +7,7 @@ def retrieve_from_vector(
query: str,
top_k: int,
) -> list[dict[str, Any]]:
-<<<<<<< HEAD
-=======
"""Queries ChromaDB for the top-k most semantically similar chunks to the query string."""
->>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
count = collection.count()
if count == 0:
return []