33
44import os
55import logging
6+ import tqdm
67import yaml
78import re
89
2021# Import the new embedding utility
2122import sys
2223sys .path .append (os .path .join (os .path .dirname (__file__ ), '..' , 'src' ))
23- from climsight .embedding_utils import create_embeddings
2424
2525logger = logging .getLogger (__name__ )
2626logging .basicConfig (
@@ -141,22 +141,18 @@ def split_docs(documents, chunk_size=2000, chunk_overlap=200, separators=[" ", "
141141 return docs
142142
143143
144- def chunk_and_embed_documents (document_path , embedding_model , openai_api_key , aitta_url , model_type , chunk_size = 2000 , chunk_overlap = 200 , separators = [" " , "," , "\n " ]):
144+ def chunk_documents (document_path , chunk_size = 2000 , chunk_overlap = 200 , separators = [" " , "," , "\n " ]):
145145 """
146- Chunks and embeds documents from the specified directory using provided embedding function .
146+ Chunks documents from the specified directory.
147147
148148 Args:
149149 - document_path (str): The path to the directory containing the documents.
150- - embedding_model (str): The embedding model name to use for generating embeddings.
151- - openai_api_key (str): OpenAI API key for OpenAI models.
152- - aitta_url (str): AITTA API URL for open models.
153- - model_type (str): The type of embedding model backend (e.g., 'openai', 'aitta').
154150 - chunk_size (int): maximum number of characters per chunk. Default: 2000.
155151 - chunk_overlap (int): number of characters to overlap per chunk. Default: 200.
156152 - separators (list): list of characters where text can be split. Default: [" ", ",", "\n "]
157153
158154 Returns:
159- - list: A list of documents with embeddings .
155+ - list: A list of chunked documents .
160156 """
161157 # load documents
162158 file_names = get_file_names (document_path )
@@ -167,7 +163,7 @@ def chunk_and_embed_documents(document_path, embedding_model, openai_api_key, ai
167163 all_documents .extend (documents ) # save all of them into one
168164
169165 if not all_documents :
170- logger .info ("No documents found for chunking and embedding ." )
166+ logger .info ("No documents found for chunking." )
171167 return []
172168
173169 # Chunk documents
@@ -180,27 +176,7 @@ def chunk_and_embed_documents(document_path, embedding_model, openai_api_key, ai
180176
181177 logger .info (f"Chunked documents into { len (chunked_docs )} pieces." )
182178
183- # Create embedding model using the utility function
184- try :
185- aitta_api_key = os .getenv ('AITTA_API_KEY' )
186- embedding_item = create_embeddings (
187- embedding_model = embedding_model ,
188- openai_api_key = openai_api_key ,
189- aitta_api_key = aitta_api_key ,
190- aitta_url = aitta_url ,
191- model_type = model_type
192- )
193- # embedding documents
194- embedded_docs = []
195- for doc in chunked_docs :
196- embedding = embedding_item .embed_documents ([doc .page_content ])[0 ] # embed_documents returns a list, so we take the first element
197- embedded_docs .append ({"text" : doc .page_content , "embedding" : embedding , "metadata" : doc .metadata })
198- except Exception as e :
199- logger .error (f"Failed to embed document chunks: { e } " )
200- return []
201-
202- logger .info (f"Embedded { len (embedded_docs )} document chunks." )
203- return embedded_docs
179+ return chunked_docs
204180
205181
206182def initialize_rag (config ):
@@ -222,9 +198,9 @@ def initialize_rag(config):
222198 if embedding_model_type == 'openai' :
223199 embedding_model = rag_settings .get ('embedding_model_openai' )
224200 chroma_path = rag_settings .get ('chroma_path_ipcc_openai' )
225- elif embedding_model_type == 'aitta ' :
226- embedding_model = rag_settings .get ('embedding_model_aitta ' )
227- chroma_path = rag_settings .get ('chroma_path_ipcc_aitta ' )
201+ elif embedding_model_type == 'local ' :
202+ embedding_model = rag_settings .get ('embedding_model_local ' )
203+ chroma_path = rag_settings .get ('chroma_path_ipcc_local ' )
228204 # Add more types here as needed
229205 # elif embedding_model_type == 'mistral':
230206 # embedding_model = rag_settings.get('embedding_model_mistral')
@@ -233,8 +209,7 @@ def initialize_rag(config):
233209 raise ValueError (f"Unknown embedding_model_type: { embedding_model_type } " )
234210
235211 openai_api_key = os .getenv ('OPENAI_API_KEY' )
236- aitta_api_key = os .getenv ('AITTA_API_KEY' )
237- aitta_url = rag_settings .get ('aitta_url' , os .getenv ('AITTA_URL' , 'https://api-climatedt-aitta.2.rahtiapp.fi' ))
212+ local_api_key = os .getenv ('OPENAI_API_KEY_LOCAL' )
238213 document_path = rag_settings ['document_path' ]
239214 chunk_size = rag_settings ['chunk_size' ]
240215 chunk_overlap = rag_settings ['chunk_overlap' ]
@@ -244,8 +219,8 @@ def initialize_rag(config):
244219 if embedding_model_type == 'openai' and not openai_api_key :
245220 logger .warning ("No OpenAI API Key found. Skipping RAG initialization." )
246221 return False
247- if embedding_model_type == 'aitta ' and not aitta_api_key :
248- logger .warning ("No AITTA API Key found. Skipping RAG initialization." )
222+ if embedding_model_type == 'local ' and not local_api_key :
223+ logger .warning ("No local API Key found. Skipping RAG initialization." )
249224 return False
250225
251226 # check if documents are present and valid
@@ -255,24 +230,24 @@ def initialize_rag(config):
255230
256231 # Perform chunking and embedding
257232 try :
258- langchain_ef = create_embeddings (
259- embedding_model = embedding_model ,
260- openai_api_key = openai_api_key ,
261- aitta_api_key = aitta_api_key ,
262- aitta_url = aitta_url ,
263- model_type = embedding_model_type
264- )
265- documents = chunk_and_embed_documents (document_path , embedding_model , openai_api_key , aitta_url , embedding_model_type , chunk_size , chunk_overlap , separators )
266- converted_documents = [
267- Document (page_content = doc ['text' ], metadata = doc ['metadata' ])
268- for doc in documents
269- ]
270- rag_db = Chroma .from_documents (
271- documents = converted_documents ,
233+ if config ['rag_settings' ]['embedding_model_type' ] == 'local' :
234+ langchain_ef = OpenAIEmbeddings (
235+ api_key = local_api_key ,
236+ base_url = rag_settings .get ('local_endpoint_url' ),
237+ model = embedding_model ,
238+ tiktoken_enabled = False
239+ )
240+ else :
241+ langchain_ef = OpenAIEmbeddings (api_key = openai_api_key , model = embedding_model )
242+ documents = chunk_documents (document_path , chunk_size , chunk_overlap , separators )
243+ rag_db = Chroma (
244+ collection_name = "ipcc_collection" ,
272245 persist_directory = chroma_path ,
273- embedding = langchain_ef ,
274- collection_name = "ipcc_collection"
246+ embedding_function = langchain_ef
275247 )
248+ batch_size = 32
249+ for i in tqdm .tqdm (range (0 , len (documents ), batch_size )):
250+ rag_db .add_documents (documents [i :i + batch_size ])
276251 rag_ready = True
277252 logger .info (f"RAG ready: { rag_ready } " )
278253 logger .info ("RAG database has been initialized and documents embedded." )
0 commit comments