File size: 18,225 Bytes
630790d
7d15e85
630790d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d15e85
630790d
 
 
49813d2
630790d
 
 
49813d2
 
 
 
630790d
 
 
 
49813d2
 
 
 
 
630790d
 
 
 
7d15e85
630790d
 
 
 
7d15e85
630790d
 
 
 
7d15e85
 
 
 
 
 
 
 
 
 
49813d2
 
 
 
 
630790d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49813d2
630790d
49813d2
 
630790d
 
 
 
 
 
 
 
 
 
 
 
49813d2
630790d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49813d2
630790d
 
 
49813d2
 
630790d
 
 
 
 
7d15e85
 
49813d2
 
630790d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d15e85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49813d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
630790d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d15e85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49813d2
 
 
 
 
 
 
 
 
 
 
 
 
 
630790d
 
 
 
 
 
 
7d15e85
 
 
 
 
 
49813d2
 
 
 
 
630790d
 
 
 
 
 
 
 
 
 
 
 
 
 
7d15e85
 
 
 
 
49813d2
7d15e85
630790d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
"""
Lógica de las 4 tools de RAG sobre ESL, ISLP, FES y PDSH.

Este módulo es agnóstico al transporte. Lo importan:
- `rag_books_mcp.server` → MCP stdio (FastMCP, para uso local con `mcp` SDK).
- `rag_books_mcp.app`    → Gradio app con `mcp_server=True` (para HF Spaces).

Mantener UNA sola fuente de verdad para las tools evita drift entre transportes.
Si modificas la lógica, hazlo aquí.
"""

from __future__ import annotations

import os
from pathlib import Path
from typing import Optional

import chromadb
from chromadb.utils.embedding_functions import SentenceTransformerEmbeddingFunction


# --- Configuración ---
EMBEDDING_MODEL = "all-MiniLM-L6-v2"
CHROMA_DIR = Path(__file__).parent.parent / "chroma_db"

# Inicialización lazy del cliente y embedding (singletons por proceso).
_client: Optional[chromadb.ClientAPI] = None
_embedding_fn = None


def get_client() -> chromadb.ClientAPI:
    """Cliente ChromaDB persistente (singleton). La ruta puede sobreescribirse
    con la variable de entorno `RAG_CHROMA_DIR`."""
    global _client
    if _client is None:
        chroma_path = os.environ.get("RAG_CHROMA_DIR", str(CHROMA_DIR))
        _client = chromadb.PersistentClient(path=chroma_path)
    return _client


def get_embedding_fn():
    """Función de embedding `sentence-transformers/all-MiniLM-L6-v2` (singleton)."""
    global _embedding_fn
    if _embedding_fn is None:
        _embedding_fn = SentenceTransformerEmbeddingFunction(model_name=EMBEDDING_MODEL)
    return _embedding_fn


def get_collection(name: str):
    """Obtiene una colección de ChromaDB por nombre."""
    return get_client().get_collection(name=name, embedding_function=get_embedding_fn())


# --- Tools (lógica pura, sin dependencias del transporte) ---

def search_theory(
    query: str,
    book: str = "all",
    top_k: int = 5,
) -> str:
    """
    Busca fragmentos relevantes en los libros ESL, ISLP, FES, PDSH y R4DS usando búsqueda semántica.

    Args:
        query (str): Consulta en lenguaje natural (ej: "bias-variance tradeoff",
                     "regularización L1 vs L2", "random forest out-of-bag error",
                     "exploratory data analysis iterative cycle").
        book (str): Libro donde buscar. Opciones: "esl", "islp", "fes", "pdsh", "r4ds",
                    "both" (ESL+ISLP, retro-compat) o "all" (los 5, default).
        top_k (int): Número de resultados a devolver (default: 5, máximo: 10).

    Returns:
        str: Fragmentos relevantes con metadata (libro, capítulo, sección, similitud).

    Nota:
        R4DS está escrito en R (tidyverse). Sus principios de EDA, transformación
        de datos y manipulación tabular son agnósticos del lenguaje y se traducen
        directamente a pandas/Python; el código en R debe leerse como pseudocódigo.
    """
    top_k = min(max(int(top_k), 1), 10)

    collections_to_search = []
    if book in ("esl", "both", "all"):
        try:
            collections_to_search.append(("ESL", get_collection("esl_chapters")))
        except Exception:
            pass
    if book in ("islp", "both", "all"):
        try:
            collections_to_search.append(("ISLP", get_collection("islp_chapters")))
        except Exception:
            pass
    if book in ("fes", "all"):
        try:
            collections_to_search.append(("FES", get_collection("fes_chapters")))
        except Exception:
            pass
    if book in ("pdsh", "all"):
        try:
            collections_to_search.append(("PDSH", get_collection("pdsh_chapters")))
        except Exception:
            pass
    if book in ("r4ds", "all"):
        try:
            collections_to_search.append(("R4DS", get_collection("r4ds_chapters")))
        except Exception:
            pass

    if not collections_to_search:
        return (
            "❌ No se encontraron colecciones. Ejecuta primero la ingesta: "
            "python -m rag_books_mcp.ingest"
        )

    results = []
    for book_label, collection in collections_to_search:
        res = collection.query(query_texts=[query], n_results=top_k)

        if res["documents"] and res["documents"][0]:
            for doc, meta, dist in zip(
                res["documents"][0], res["metadatas"][0], res["distances"][0]
            ):
                similarity = 1 - dist  # cosine distance → similarity
                results.append({
                    "book": book_label,
                    "chapter": meta.get("chapter", ""),
                    "section": meta.get("section", ""),
                    "similarity": similarity,
                    "content": doc,
                })

    # Ordenar por similitud descendente
    results.sort(key=lambda x: x["similarity"], reverse=True)
    results = results[:top_k]

    if not results:
        return f"No se encontraron resultados para: '{query}'"

    output_parts = [f"## Resultados para: \"{query}\"\n"]
    for i, r in enumerate(results, 1):
        output_parts.append(
            f"### [{i}] {r['book']}{r['chapter']} § {r['section']}\n"
            f"**Similitud:** {r['similarity']:.3f}\n\n"
            f"{r['content'][:1500]}\n\n---\n"
        )

    return "\n".join(output_parts)


def get_section(
    book: str,
    chapter: str,
    section: str = "",
    max_chunks: int = 5,
) -> str:
    """
    Recupera una sección específica de un libro por referencia exacta.

    Args:
        book (str): Libro a consultar. Opciones: "esl", "islp", "fes", "pdsh" o "r4ds".
        chapter (str): Nombre del capítulo (ej: "3 Linear Methods for Regression",
                       "8 Tree-Based Methods", "10 Exploratory data analysis").
                       Búsqueda parcial soportada.
        section (str): Nombre de la sección dentro del capítulo (opcional).
                       Si se omite, devuelve el inicio del capítulo.
        max_chunks (int): Máximo de chunks a devolver (default: 5).

    Returns:
        str: Contenido de la sección con metadata.
    """
    max_chunks = int(max_chunks)
    collection_name = f"{book}_chapters"
    try:
        collection = get_collection(collection_name)
    except Exception:
        return f"❌ Colección '{collection_name}' no encontrada. Opciones: esl, islp, fes, pdsh, r4ds"

    # Intentar con filtro de metadata
    try:
        if section:
            results = collection.get(
                where={"$and": [
                    {"chapter": {"$contains": chapter}},
                    {"section": {"$contains": section}},
                ]},
                limit=max_chunks,
            )
        else:
            results = collection.get(
                where={"chapter": {"$contains": chapter}},
                limit=max_chunks,
            )
    except Exception:
        # Fallback: búsqueda semántica con el nombre del capítulo/sección
        search_query = f"{chapter} {section}".strip()
        results = collection.query(query_texts=[search_query], n_results=max_chunks)
        if results["documents"] and results["documents"][0]:
            output_parts = [f"## {book.upper()}{chapter}\n"]
            for doc, meta in zip(results["documents"][0], results["metadatas"][0]):
                output_parts.append(
                    f"### § {meta.get('section', 'N/A')}\n\n{doc}\n\n---\n"
                )
            return "\n".join(output_parts)
        return f"No se encontró el capítulo '{chapter}' en {book.upper()}"

    if not results["documents"]:
        # Fallback semántico
        search_query = f"{chapter} {section}".strip()
        results = collection.query(query_texts=[search_query], n_results=max_chunks)
        if results["documents"] and results["documents"][0]:
            output_parts = [f"## {book.upper()}{chapter}\n"]
            for doc, meta in zip(results["documents"][0], results["metadatas"][0]):
                output_parts.append(
                    f"### § {meta.get('section', 'N/A')}\n\n{doc}\n\n---\n"
                )
            return "\n".join(output_parts)
        return f"No se encontró el capítulo '{chapter}' en {book.upper()}"

    output_parts = [f"## {book.upper()}{chapter}"]
    if section:
        output_parts[0] += f" § {section}"
    output_parts[0] += "\n"

    for doc, meta in zip(results["documents"], results["metadatas"]):
        sec_title = meta.get("section", "")
        chunk_idx = meta.get("chunk_index", 0)
        total = meta.get("total_chunks_in_section", 1)
        output_parts.append(
            f"### § {sec_title} (parte {chunk_idx + 1}/{total})\n\n{doc}\n\n---\n"
        )

    return "\n".join(output_parts)


def cite_foundation(
    topic: str,
    detail_level: str = "medium",
) -> str:
    """
    Devuelve la fundamentación teórica para un tema de ML/estadística,
    citando los libros (ESL, ISLP, FES, PDSH, R4DS) para dar perspectiva completa.

    Args:
        topic (str): Tema a fundamentar (ej: "ridge regression", "bagging",
                     "cross-validation", "feature engineering", "missing data",
                     "exploratory data analysis").
        detail_level (str): Nivel de detalle. Opciones: "brief" (1-2 fragmentos clave),
                            "medium" (3-4 fragmentos, default),
                            "deep" (6-8 fragmentos con contexto amplio).

    Returns:
        str: Fundamentación teórica con citas de los libros, organizada para
             entender el concepto desde lo intuitivo (ISLP) hasta lo riguroso (ESL),
             más prácticas de feature engineering (FES), código Python (PDSH)
             y workflow iterativo de EDA / data wrangling (R4DS, ejemplos en R).
    """
    top_k_map = {"brief": 2, "medium": 4, "deep": 8}
    top_k = top_k_map.get(detail_level, 4)

    islp_results = []
    try:
        islp_col = get_collection("islp_chapters")
        res = islp_col.query(query_texts=[topic], n_results=top_k)
        if res["documents"] and res["documents"][0]:
            for doc, meta, dist in zip(
                res["documents"][0], res["metadatas"][0], res["distances"][0]
            ):
                islp_results.append({
                    "content": doc,
                    "chapter": meta.get("chapter", ""),
                    "section": meta.get("section", ""),
                    "similarity": 1 - dist,
                })
    except Exception:
        pass

    esl_results = []
    try:
        esl_col = get_collection("esl_chapters")
        res = esl_col.query(query_texts=[topic], n_results=top_k)
        if res["documents"] and res["documents"][0]:
            for doc, meta, dist in zip(
                res["documents"][0], res["metadatas"][0], res["distances"][0]
            ):
                esl_results.append({
                    "content": doc,
                    "chapter": meta.get("chapter", ""),
                    "section": meta.get("section", ""),
                    "similarity": 1 - dist,
                })
    except Exception:
        pass

    fes_results = []
    try:
        fes_col = get_collection("fes_chapters")
        res = fes_col.query(query_texts=[topic], n_results=top_k)
        if res["documents"] and res["documents"][0]:
            for doc, meta, dist in zip(
                res["documents"][0], res["metadatas"][0], res["distances"][0]
            ):
                fes_results.append({
                    "content": doc,
                    "chapter": meta.get("chapter", ""),
                    "section": meta.get("section", ""),
                    "similarity": 1 - dist,
                })
    except Exception:
        pass

    pdsh_results = []
    try:
        pdsh_col = get_collection("pdsh_chapters")
        res = pdsh_col.query(query_texts=[topic], n_results=top_k)
        if res["documents"] and res["documents"][0]:
            for doc, meta, dist in zip(
                res["documents"][0], res["metadatas"][0], res["distances"][0]
            ):
                pdsh_results.append({
                    "content": doc,
                    "chapter": meta.get("chapter", ""),
                    "section": meta.get("section", ""),
                    "similarity": 1 - dist,
                })
    except Exception:
        pass

    r4ds_results = []
    try:
        r4ds_col = get_collection("r4ds_chapters")
        res = r4ds_col.query(query_texts=[topic], n_results=top_k)
        if res["documents"] and res["documents"][0]:
            for doc, meta, dist in zip(
                res["documents"][0], res["metadatas"][0], res["distances"][0]
            ):
                r4ds_results.append({
                    "content": doc,
                    "chapter": meta.get("chapter", ""),
                    "section": meta.get("section", ""),
                    "similarity": 1 - dist,
                })
    except Exception:
        pass

    if not islp_results and not esl_results and not fes_results and not pdsh_results and not r4ds_results:
        return (
            f"❌ No se encontró fundamentación para '{topic}'. "
            "Verifica que la ingesta se haya ejecutado correctamente."
        )

    output_parts = [
        f"# Fundamentación Teórica: {topic}\n",
        f"**Nivel de detalle:** {detail_level}\n",
    ]

    if islp_results:
        output_parts.append("\n## 📘 ISLP (Explicación Intuitiva)\n")
        for i, r in enumerate(islp_results, 1):
            output_parts.append(
                f"### [{i}] Cap. {r['chapter']} § {r['section']} "
                f"(sim: {r['similarity']:.3f})\n\n"
                f"{r['content'][:1200]}\n\n---\n"
            )

    if esl_results:
        output_parts.append("\n## 📗 ESL (Tratamiento Riguroso)\n")
        for i, r in enumerate(esl_results, 1):
            output_parts.append(
                f"### [{i}] Cap. {r['chapter']} § {r['section']} "
                f"(sim: {r['similarity']:.3f})\n\n"
                f"{r['content'][:1200]}\n\n---\n"
            )

    if fes_results:
        output_parts.append("\n## 📙 FES (Feature Engineering Práctico)\n")
        for i, r in enumerate(fes_results, 1):
            output_parts.append(
                f"### [{i}] Cap. {r['chapter']} § {r['section']} "
                f"(sim: {r['similarity']:.3f})\n\n"
                f"{r['content'][:1200]}\n\n---\n"
            )

    if pdsh_results:
        output_parts.append("\n## 📓 PDSH (Código Práctico Python)\n")
        for i, r in enumerate(pdsh_results, 1):
            output_parts.append(
                f"### [{i}] Cap. {r['chapter']} § {r['section']} "
                f"(sim: {r['similarity']:.3f})\n\n"
                f"{r['content'][:1200]}\n\n---\n"
            )

    if r4ds_results:
        output_parts.append(
            "\n## 📕 R4DS (EDA & Data Wrangling — ejemplos en R, principios universales)\n"
            "> ⚠️ El código está en R con tidyverse. Léelo como pseudocódigo: el flujo, "
            "las heurísticas y la filosofía iterativa de EDA se traducen directamente a "
            "pandas/Python.\n"
        )
        for i, r in enumerate(r4ds_results, 1):
            output_parts.append(
                f"### [{i}] Cap. {r['chapter']} § {r['section']} "
                f"(sim: {r['similarity']:.3f})\n\n"
                f"{r['content'][:1200]}\n\n---\n"
            )

    output_parts.append("\n## 📚 Referencias\n")
    if islp_results:
        chapters = set(r["chapter"] for r in islp_results)
        output_parts.append(f"- **ISLP:** {', '.join(chapters)}\n")
    if esl_results:
        chapters = set(r["chapter"] for r in esl_results)
        output_parts.append(f"- **ESL:** {', '.join(chapters)}\n")
    if fes_results:
        chapters = set(r["chapter"] for r in fes_results)
        output_parts.append(f"- **FES:** {', '.join(chapters)}\n")
    if pdsh_results:
        chapters = set(r["chapter"] for r in pdsh_results)
        output_parts.append(f"- **PDSH:** {', '.join(chapters)}\n")
    if r4ds_results:
        chapters = set(r["chapter"] for r in r4ds_results)
        output_parts.append(
            f"- **R4DS:** {', '.join(chapters)} _(R / tidyverse — principios transferibles a pandas)_\n"
        )

    return "\n".join(output_parts)


def list_available_topics() -> str:
    """
    Lista los capítulos y temas disponibles en la base de conocimiento.
    Útil para saber qué contenido está indexado y qué consultas se pueden hacer.

    Returns:
        str: Lista organizada de capítulos por libro con sus secciones principales.
    """
    output_parts = ["# 📚 Contenido Disponible en la Base de Conocimiento\n"]

    for book_key, collection_name in [
        ("ESL", "esl_chapters"),
        ("ISLP", "islp_chapters"),
        ("FES", "fes_chapters"),
        ("PDSH", "pdsh_chapters"),
        ("R4DS", "r4ds_chapters"),
    ]:
        try:
            collection = get_collection(collection_name)
            all_data = collection.get(include=["metadatas"])

            if not all_data["metadatas"]:
                output_parts.append(f"\n## {book_key}: Sin datos\n")
                continue

            chapters = {}
            for meta in all_data["metadatas"]:
                chapter = meta.get("chapter", "Unknown")
                section = meta.get("section", "")
                if chapter not in chapters:
                    chapters[chapter] = set()
                if section:
                    chapters[chapter].add(section)

            output_parts.append(f"\n## 📗 {book_key}\n")
            for chapter in sorted(chapters.keys()):
                sections = sorted(chapters[chapter])
                output_parts.append(f"\n### {chapter}\n")
                if sections:
                    for sec in sections[:8]:
                        output_parts.append(f"  - {sec}\n")
                    if len(sections) > 8:
                        output_parts.append(f"  - ... y {len(sections) - 8} secciones más\n")

            total = collection.count()
            output_parts.append(f"\n**Total chunks indexados:** {total}\n")

        except Exception as e:
            output_parts.append(f"\n## {book_key}: ❌ Error ({e})\n")

    return "\n".join(output_parts)