File size: 12,667 Bytes
eb93f4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
"""

## Sources

1.  Connecting to a Pinecone index: https://docs.pinecone.io/guides/inference/generate-embeddings

2.  Creating a text loader from a directory: https://github.com/langchain-ai/langchain/discussions/18559

3.  Using an LLM: https://python.langchain.com/docs/tutorials/rag/

4.  Evaluation with RAGAS: https://docs.ragas.io/en/stable/getstarted/evals/#analyzing-results

5.  Dataset creation: https://www.mongodb.com/developer/products/atlas/evaluate-llm-applications-rag/



## Preparation

First, the packages required for handling connections to the LLM and the vector database must be installed.



Subsequently, the corresponding packages are imported along with the `os` module. This module is utilized to handle the assignments to the environment variables for the API keys."""

from pinecone import Pinecone
import os

from langchain_mistralai import ChatMistralAI
from langchain_openai import ChatOpenAI

from langchain_community.document_loaders import DirectoryLoader
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_core.messages import HumanMessage, SystemMessage
import pathlib
from langchain.schema import Document
from langchain_community.document_loaders import (
    CSVLoader, PyPDFLoader, UnstructuredWordDocumentLoader,
    UnstructuredPowerPointLoader, UnstructuredMarkdownLoader,
    UnstructuredHTMLLoader, NotebookLoader
)

# -------------------------
# UTF-8 safe Text Loader
# -------------------------
class SafeTextLoader:
    """Loads a text file as a single Document, safely handling UTF-8 decoding errors."""
    def __init__(self, file_path):
        self.file_path = file_path

    def load(self):
        try:
            with open(self.file_path, "rb") as f:  # open in binary mode
                raw_bytes = f.read()
            text = raw_bytes.decode("utf-8", errors="ignore")  # decode safely
            return [Document(page_content=text, metadata={"source": str(self.file_path)})]
        except Exception as e:
            print(f"[Error] Failed to read {self.file_path}: {e}")
            return []

# -------------------------
# Loader mapping
# -------------------------
LOADER_MAPPING = {
    # Text
    ".txt": SafeTextLoader,
    ".json": SafeTextLoader,
    ".md": UnstructuredMarkdownLoader,
    ".csv": CSVLoader,
    ".yaml": SafeTextLoader,
    ".yml": SafeTextLoader,

    # Documents
    ".pdf": PyPDFLoader,
    ".docx": UnstructuredWordDocumentLoader,
    ".pptx": UnstructuredPowerPointLoader,
    ".html": UnstructuredHTMLLoader,
    ".htm": UnstructuredHTMLLoader,

    # Code / Notebook
    ".ipynb": NotebookLoader,
    ".py": SafeTextLoader,
    ".js": SafeTextLoader,
    ".sql": SafeTextLoader,
}

import pathlib

CONTEXT_ROOT = pathlib.Path(__file__).parent / "context"

# -------------------------
# Directory loader (recursive)
# -------------------------
def create_text_dir_loader(directory_path: str = ""):
    """

    Loads all supported files in the context directory (and subfolders) using the appropriate loader.

    - If directory_path is empty -> scans entire 'context' folder recursively.

    - If directory_path is given -> scans only that subfolder inside 'context'.

    """
    # Resolve the target directory
    target_dir = CONTEXT_ROOT / directory_path if directory_path else CONTEXT_ROOT

    if not target_dir.exists() or not target_dir.is_dir():
        print(f"[Error] Target directory does not exist: {target_dir}")
        return []

    documents = []

    for file_path in target_dir.rglob("*"):  # recursive
        if not file_path.is_file():
            continue

        ext = file_path.suffix.lower()
        loader_cls = LOADER_MAPPING.get(ext)

        if loader_cls is None:
            print(f"[Skip] Unsupported file type: {file_path}")
            continue

        try:
            loader = loader_cls(str(file_path))
            docs = loader.load()
            documents.extend(docs)
            print(f"[Loaded] {file_path} ({len(docs)} docs)")
        except Exception as e:
            print(f"[Error] Failed to load {file_path}: {e}")

    print(f"[Done] Finished scanning {target_dir}")
    return documents

# -------------------------
# Dataset creation
# -------------------------
def create_dataset(directory_path: str = "context"):
    """

    Loads all supported files from the given directory (recursively).

    Defaults to 'context' if no path is given.

    """
    target_dir = pathlib.Path(directory_path).resolve()

    if not target_dir.exists() or not target_dir.is_dir():
        print(f"[Error] Target directory does not exist: {target_dir}")
        return []

    documents = []

    for file_path in target_dir.rglob("*"):  # recursive
        if not file_path.is_file():
            continue

        ext = file_path.suffix.lower()
        loader_cls = LOADER_MAPPING.get(ext)

        if loader_cls is None:
            print(f"[Skip] Unsupported file type: {file_path}")
            continue

        try:
            loader = loader_cls(str(file_path))
            docs = loader.load()
            documents.extend(docs)
            print(f"[Loaded] {file_path} ({len(docs)} docs)")
        except Exception as e:
            print(f"[Error] Failed to load {file_path}: {e}")

    print(f"[Done] Finished scanning {target_dir}")
    print(f"Total documents loaded: {len(documents)}")
    return documents

############################################################################################

import time
import os
import math


def prepare_RAG(

    pinecone_API,

    index_name,

    chunk_size=1800,

    chunk_overlap=200,

    llm_model="gpt-5-nano",

    dir_name="context",

    info=True

):
    import time
    from langchain_openai import ChatOpenAI
    from langchain_mistralai import ChatMistralAI
    from langchain.text_splitter import RecursiveCharacterTextSplitter
    from pinecone import Pinecone

    if info:
        print(f"Prepare RAG with model={llm_model}, dir={dir_name}")
    
    if "gpt" in llm_model:
        llm = ChatOpenAI(model=llm_model, streaming=True)   # streaming enabled
    else:
        llm = ChatMistralAI(model=llm_model, streaming=True) 


    documents = create_dataset(dir_name)
    if not documents:
        print(f"[Warning] No documents found in directory '{dir_name}'. Using existing Pinecone index without upserting new vectors.")
        pc = Pinecone(api_key=pinecone_API)
        index = pc.Index(index_name)
        return index, pc, llm

    text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
    all_splits = text_splitter.split_documents(documents)
    if not all_splits:
        print(f"[Warning] No text chunks were created. Using existing Pinecone index.")
        pc = Pinecone(api_key=pinecone_API)
        index = pc.Index(index_name)
        return index, pc, llm

    if info:
        print("Number of chunks:", len(all_splits))

    pc = Pinecone(api_key=pinecone_API)
    index = pc.Index(index_name)

    initial_batch_size = 94
    min_batch_size = 1
    total_chunks = len(all_splits)
    records = []

    def retry_forever(func, *args, **kwargs):
        attempt = 1
        while True:
            try:
                return func(*args, **kwargs)
            except Exception as e:
                wait_time = min(60, 2 ** min(attempt, 6))
                print(f"[Retry] {func.__name__} failed (attempt {attempt}): {e}")
                print(f"Sleeping {wait_time} seconds before retry...")
                time.sleep(wait_time)
                attempt += 1

    start_idx = 0
    batch_size = initial_batch_size

    while start_idx < total_chunks:
        end_idx = min(start_idx + batch_size, total_chunks)
        batch_splits = all_splits[start_idx:end_idx]

        if info:
            print(f"Embedding batch {start_idx}{end_idx - 1} (batch_size={batch_size})")

        data = [
            {"id": f"vec{idx}", "text": chunk.page_content, "metadata": chunk.metadata or {}}
            for idx, chunk in enumerate(batch_splits, start=start_idx)
        ]

        # Attempt embedding
        embeddings = retry_forever(
            pc.inference.embed,
            model="llama-text-embed-v2",
            inputs=[d['text'] for d in data],
            parameters={"input_type": "passage", "truncate": "END"}
        )

        # Prepare records for upsert
        batch_records = [
            {"id": d['id'], "values": e['values'], "metadata": {"text": d['text'], **d.get('metadata', {})}}
            for d, e in zip(data, embeddings)
        ]

        # Dynamic upsert with batch size adjustment
        while batch_records:
            try:
                retry_forever(index.upsert, vectors=batch_records, namespace="example-namespace")
                records.extend(batch_records)
                break  # success → exit loop
            except Exception as e:
                if "Request size" in str(e) or "exceeds the maximum" in str(e):
                    if len(batch_records) == 1:
                        print(f"[Error] Single vector too large to upsert: {batch_records[0]['id']}")
                        break
                    # Reduce batch size by half
                    batch_records = batch_records[:len(batch_records) // 2]
                    print(f"[Warning] Batch too large. Reducing batch size to {len(batch_records)} and retrying upsert...")
                    time.sleep(1)  # small delay before retry
                else:
                    raise e

        start_idx += batch_size  # move to next batch
        # Optionally increase batch size gradually if previous upsert succeeded
        batch_size = min(initial_batch_size, batch_size * 2)

    if info:
        print(f"Completed upsert of {len(records)} vectors.")

    return index, pc, llm


def retrieve_RAG(prompt_message, pc, index, top_k=5, info=True):
    if info:
        print("Retrieve RAG with", prompt_message, pc, index, top_k)
    """## Retrieval

    The user query is embedded using the same model (specified in the `model` parameter of the `pc.inference.embed()` function) as for embedding the chunks originally upserted into the vector database.

    """

    query_embedding = pc.inference.embed(
        model="llama-text-embed-v2",
        inputs=[prompt_message],
        parameters={
            "input_type": "query"
        }
    )

    """The relevant chunks are retrieved using semantic search with the cosine distance similarity measure. The number of chunks to be retrieved is passed in the `top_k` variable."""

    retrieved_chunks_raw = index.query(
        namespace="example-namespace",
        vector=query_embedding[0].values,
        top_k=top_k,
        include_values=False,
        include_metadata=True
    )

    """The result of the retrieval is processed, so that the variable `retrieved_chunks` contains a list of the corresponding text splits.

    """

    retrieved_chunks = []
    for match in retrieved_chunks_raw.matches:
        retrieved_chunks.append({
            "text": match.metadata.get("text", ""),
            "source": match.metadata.get("source", "")
        })

    return retrieved_chunks

def generate_RAG(prompt_message, llm, retrieved_chunks, info=True):
    if info:
        print("Generate RAG with", prompt_message, llm)
    """## Generation

    The prompt is sent to the LLM together with the context consisting of the data considered most relevant according to the semantic search. These data are stored in the variable `retrieved_chunks`. The part of the prompt containing the explaination of the task to be performed on the provided context is in the variable `prompt_message`.

    """

    context_message = "You are an expert in the field of the documents that are loaded. Use only the these documents and source files as the context. If you don't know the answer or the answer is not included in the context, then do not answer."
    prompt = [HumanMessage(prompt_message),
            SystemMessage(context_message),
                HumanMessage(str(retrieved_chunks))]

    """The prompt is sent to the selected LLM using the `invoke()` function. As a return value, this function passes the respective answer of the LLM."""

    response = llm.invoke(prompt)
    return response