File size: 8,091 Bytes
f45a28c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
"""

STEP 4 — CREATE VECTOR DATABASE

Loads data from JSONL, creates embeddings, and stores in ChromaDB

"""

import os
import sys
import json
from pathlib import Path

# Add parent directory to path for imports
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)

from sentence_transformers import SentenceTransformer
import chromadb
from logger_config import setup_logger
import config

logger = setup_logger(__name__)


def load_data(file_path):
    """

    Load data from JSONL file

    

    Args:

        file_path: Path to JSONL file

    

    Returns:

        list: List of parsed JSON objects

    """
    try:
        logger.info(f"Loading data from: {file_path}")
        data = []
        with open(file_path, 'r', encoding='utf-8') as f:
            for line_num, line in enumerate(f, 1):
                try:
                    item = json.loads(line.strip())
                    data.append(item)
                except json.JSONDecodeError as e:
                    logger.warning(f"Skipping invalid JSON on line {line_num}: {str(e)}")
                    continue
        
        logger.info(f"Loaded {len(data)} items from JSONL file")
        return data
    except FileNotFoundError:
        logger.error(f"Data file not found: {file_path}")
        raise
    except Exception as e:
        logger.error(f"Error loading data: {str(e)}", exc_info=True)
        raise


def extract_chunks(data):
    """

    Extract assistant message content from data

    

    Args:

        data: List of JSON objects with messages

    

    Returns:

        list: List of text chunks (assistant messages)

    """
    try:
        logger.info("Extracting assistant messages from data")
        chunks = []
        for item in data:
            if "messages" not in item:
                logger.warning("Item missing 'messages' key, skipping")
                continue
            
            for msg in item["messages"]:
                if msg.get("role") == "assistant":
                    content = msg.get("content", "").strip()
                    if content:  # Only add non-empty content
                        chunks.append(content)
        
        logger.info(f"Extracted {len(chunks)} chunks from data")
        return chunks
    except Exception as e:
        logger.error(f"Error extracting chunks: {str(e)}", exc_info=True)
        raise


def create_embeddings(chunks, embedder):
    """

    Create embeddings for text chunks

    

    Args:

        chunks: List of text chunks

        embedder: SentenceTransformer model

    

    Returns:

        list: List of embedding vectors

    """
    try:
        if not chunks:
            logger.warning("No chunks to embed")
            return []
        
        logger.info(f"Creating embeddings for {len(chunks)} chunks...")
        embeddings = embedder.encode(chunks, show_progress_bar=True, convert_to_numpy=True)
        embeddings_list = embeddings.tolist()
        logger.info(f"Created {len(embeddings_list)} embeddings")
        return embeddings_list
    except Exception as e:
        logger.error(f"Error creating embeddings: {str(e)}", exc_info=True)
        raise


def store_in_chromadb(chunks, embeddings, collection):
    """

    Store chunks and embeddings in ChromaDB

    

    Args:

        chunks: List of text chunks

        embeddings: List of embedding vectors

        collection: ChromaDB collection object

    """
    try:
        if not chunks or not embeddings:
            logger.warning("No chunks or embeddings to store")
            return
        
        if len(chunks) != len(embeddings):
            logger.error(f"Mismatch: {len(chunks)} chunks but {len(embeddings)} embeddings")
            raise ValueError("Chunks and embeddings must have the same length")
        
        logger.info(f"Storing {len(chunks)} documents in ChromaDB...")
        
        # Check if collection already has data
        existing_count = collection.count()
        if existing_count > 0:
            logger.warning(f"Collection already contains {existing_count} documents")
            logger.info("Adding new documents to existing collection")
            # Start IDs from existing count to avoid conflicts
            start_id = existing_count
        else:
            start_id = 0
        
        # Prepare data for batch insertion
        ids = [str(i + start_id) for i in range(len(chunks))]
        documents = chunks
        embeddings_list = embeddings
        
        # Add in batches to handle large datasets
        batch_size = 100
        total_batches = (len(chunks) + batch_size - 1) // batch_size
        
        for batch_idx in range(0, len(chunks), batch_size):
            batch_ids = ids[batch_idx:batch_idx + batch_size]
            batch_docs = documents[batch_idx:batch_idx + batch_size]
            batch_embeddings = embeddings_list[batch_idx:batch_idx + batch_size]
            
            collection.add(
                ids=batch_ids,
                documents=batch_docs,
                embeddings=batch_embeddings
            )
            
            current_batch = (batch_idx // batch_size) + 1
            logger.info(f"Stored batch {current_batch}/{total_batches} ({len(batch_ids)} documents)")
        
        final_count = collection.count()
        logger.info(f"Successfully stored {final_count} documents in ChromaDB")
        
    except Exception as e:
        logger.error(f"Error storing in ChromaDB: {str(e)}", exc_info=True)
        raise


def create_vector_database():
    """

    Main function to create the vector database

    """
    try:
        logger.info("=" * 60)
        logger.info("Starting vector database creation")
        logger.info("=" * 60)
        
        # Initialize embedder
        logger.info(f"Loading embedding model: {config.EMBEDDING_MODEL}")
        embedder = SentenceTransformer(config.EMBEDDING_MODEL)
        logger.info("Embedding model loaded successfully")
        
        # Initialize ChromaDB
        logger.info(f"Initializing ChromaDB at: {config.EMBEDDINGS_PATH}")
        db = chromadb.PersistentClient(path=config.EMBEDDINGS_PATH)
        collection = db.get_or_create_collection(
            name="dhigrowth",
            metadata={"description": "Dhigrowth RAG knowledge base"}
        )
        logger.info("ChromaDB collection ready")
        
        # Load data
        data_path = Path(config.DATA_PATH)
        if not data_path.exists():
            logger.error(f"Data file does not exist: {data_path}")
            raise FileNotFoundError(f"Data file not found: {data_path}")
        
        data = load_data(data_path)
        
        if not data:
            logger.error("No data loaded from file")
            raise ValueError("No data to process")
        
        # Extract chunks
        chunks = extract_chunks(data)
        
        if not chunks:
            logger.error("No chunks extracted from data")
            raise ValueError("No chunks to embed")
        
        # Create embeddings
        embeddings = create_embeddings(chunks, embedder)
        
        if not embeddings:
            logger.error("No embeddings created")
            raise ValueError("Failed to create embeddings")
        
        # Store in ChromaDB
        store_in_chromadb(chunks, embeddings, collection)
        
        logger.info("=" * 60)
        logger.info("Vector database creation complete!")
        logger.info("=" * 60)
        
        return True
        
    except Exception as e:
        logger.error(f"Failed to create vector database: {str(e)}", exc_info=True)
        return False


if __name__ == "__main__":
    """

    Run this script to create the vector database

    Usage: python src/embed_loader.py

    """
    success = create_vector_database()
    sys.exit(0 if success else 1)