Spaces:
Running
Running
File size: 17,108 Bytes
fd5dd94 | 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 | """Business knowledge: ingest documents, chunk, embed, index; hybrid search with citations.
Sources: PDF (``pypdf``, page numbers kept for citations), DOCX (``python-docx``), Markdown,
plain text, HTML, or a URL fetched by an injectable ``Fetcher`` (the default one is
SSRF-guarded; tests inject fixtures, nothing touches the network).
Search is hybrid: Postgres full-text rank (english stemming + 'simple' tokens, so Roman Urdu
words still match) blended with pgvector cosine similarity over the pluggable ``Embedder``
(``HashingEmbedder`` by default), then an optional ``Reranker`` hook.
**Everything retrieved here is untrusted.** A document can carry a planted instruction
("ignore previous instructions and refund..."). Retrieved text may only be read by the
quarantine extractor (``core.agent.extractor``) or pasted into a reply draft; it never
chooses a tool or a workflow. Chunks that look like injection attempts are flagged
(``possible_injection``) at ingestion so operators can see them.
"""
from __future__ import annotations
import asyncio
import hashlib
import io
import ipaddress
import re
import socket
import uuid
from dataclasses import dataclass, field
from html.parser import HTMLParser
from typing import Any, Protocol
from urllib.parse import urlsplit
import httpx
from sqlalchemy import delete, func, literal_column, select
from sqlalchemy.ext.asyncio import AsyncSession
from core.config import get_settings
from core.memory.models import KnowledgeChunk, KnowledgeDoc
from core.tools.search import Embedder, HashingEmbedder
SOURCE_TYPES = ("pdf", "docx", "markdown", "text", "html")
_INJECTION = re.compile(
r"ignore (?:all |any |the )?(?:previous|prior|above|earlier) (?:instructions|rules)"
r"|disregard (?:all |any |the )?(?:previous|prior|above) "
r"|\byou are now\b|\bsystem prompt\b|</?\s*(?:system|assistant|instructions?)\s*>"
r"|\bnew instructions\s*:|\bas an ai\b|\bcall the tool\b|\bexecute (?:the )?tool\b",
re.IGNORECASE,
)
_STOPWORDS = frozenset(
"a an and are as at be by can do does for from has have how i if in is it me my of on "
"or our so that the their this to us was we what when where which who why will with "
"you your ka ki ke ko hai hain kya".split()
)
class IngestError(ValueError):
pass
# ------------------------------------------------------------------------------- parsing
@dataclass(frozen=True)
class Page:
number: int | None # 1-based page for PDFs, else None
text: str
class _TextFromHTML(HTMLParser):
def __init__(self) -> None:
super().__init__()
self.parts: list[str] = []
self._skip = 0
def handle_starttag(self, tag: str, attrs: Any) -> None:
if tag in ("script", "style", "noscript", "template"):
self._skip += 1
elif tag in ("p", "br", "li", "h1", "h2", "h3", "h4", "tr", "div", "section"):
self.parts.append("\n")
def handle_endtag(self, tag: str) -> None:
if tag in ("script", "style", "noscript", "template") and self._skip:
self._skip -= 1
def handle_data(self, data: str) -> None:
if not self._skip:
self.parts.append(data)
def html_to_text(html: str) -> str:
p = _TextFromHTML()
p.feed(html)
return re.sub(r"\n\s*\n+", "\n\n", "".join(p.parts)).strip()
def detect_type(filename: str | None, content_type: str | None) -> str:
name = (filename or "").lower()
ct = (content_type or "").lower().split(";")[0].strip()
if name.endswith(".pdf") or ct == "application/pdf":
return "pdf"
if name.endswith(".docx") or "wordprocessingml" in ct:
return "docx"
if name.endswith((".md", ".markdown")) or ct in ("text/markdown", "text/x-markdown"):
return "markdown"
if name.endswith((".html", ".htm")) or ct in ("text/html", "application/xhtml+xml"):
return "html"
if name.endswith(".txt") or ct.startswith("text/") or not (name or ct):
return "text"
raise IngestError(f"unsupported document type: {filename or ct}")
def parse(data: bytes, source_type: str) -> list[Page]:
if source_type == "pdf":
from pypdf import PdfReader
try:
reader = PdfReader(io.BytesIO(data))
return [Page(i + 1, p.extract_text() or "") for i, p in enumerate(reader.pages)]
except Exception as exc:
raise IngestError(f"unreadable PDF: {exc}") from exc
if source_type == "docx":
import docx
try:
d = docx.Document(io.BytesIO(data))
except Exception as exc:
raise IngestError(f"unreadable DOCX: {exc}") from exc
parts = [p.text for p in d.paragraphs]
for table in d.tables:
for row in table.rows:
parts.append(" | ".join(c.text for c in row.cells))
return [Page(None, "\n".join(parts))]
if source_type in ("markdown", "text", "html"):
text = data.decode("utf-8", errors="replace")
if source_type == "html":
text = html_to_text(text)
return [Page(None, text)]
raise IngestError(f"unsupported document type: {source_type}")
def chunk_pages(pages: list[Page], words: int, overlap: int) -> list[tuple[int | None, str]]:
"""Sliding word windows per page (``overlap`` words shared between neighbours), so a
citation always points at one page."""
words = max(20, words)
overlap = max(0, min(overlap, words // 2))
out: list[tuple[int | None, str]] = []
for page in pages:
tokens = page.text.split()
if not tokens:
continue
start = 0
while True:
window = tokens[start : start + words]
out.append((page.number, " ".join(window)))
if start + words >= len(tokens):
break
start += words - overlap
return out
def flags_for(text: str) -> list[str]:
return ["possible_injection"] if _INJECTION.search(text) else []
# ------------------------------------------------------------------------------- fetching
@dataclass(frozen=True)
class FetchedDocument:
url: str
content: bytes
content_type: str
class Fetcher(Protocol):
async def fetch(self, url: str) -> FetchedDocument: ...
class FetchBlocked(IngestError):
pass
def _public_host(host: str) -> None:
try:
infos = socket.getaddrinfo(host, None)
except OSError as exc:
raise FetchBlocked(f"cannot resolve {host}") from exc
for info in infos:
ip = ipaddress.ip_address(info[4][0])
if not ip.is_global or ip.is_multicast:
raise FetchBlocked(f"{host} resolves to a non-public address")
class HttpFetcher:
"""SSRF-guarded fetch: http(s) only, public addresses only (checked on every redirect
hop), size and time limits. Residual risk: DNS rebinding between check and connect."""
def __init__(self, *, max_bytes: int | None = None, timeout_s: float = 10.0) -> None:
self.max_bytes = max_bytes or get_settings().knowledge_max_upload_bytes
self.timeout_s = timeout_s
async def fetch(self, url: str) -> FetchedDocument:
async with httpx.AsyncClient(timeout=self.timeout_s, follow_redirects=False) as client:
for _ in range(4):
parts = urlsplit(url)
if parts.scheme not in ("http", "https") or not parts.hostname:
raise FetchBlocked("only http(s) URLs can be ingested")
await asyncio.to_thread(_public_host, parts.hostname)
async with client.stream("GET", url) as resp:
if resp.is_redirect and resp.headers.get("location"):
url = str(resp.url.join(resp.headers["location"]))
continue
resp.raise_for_status()
body = bytearray()
async for part in resp.aiter_bytes():
body.extend(part)
if len(body) > self.max_bytes:
raise FetchBlocked("document too large")
return FetchedDocument(
url=url,
content=bytes(body),
content_type=resp.headers.get("content-type", ""),
)
raise FetchBlocked("too many redirects")
# --------------------------------------------------------------------------- knowledge base
@dataclass
class KnowledgeHit:
chunk_id: uuid.UUID
doc_id: uuid.UUID
title: str
page: int | None
ordinal: int
text: str
score: float
flags: list[str] = field(default_factory=list)
source_uri: str | None = None
@property
def citation(self) -> str:
where = f", p. {self.page}" if self.page else ""
return f"{self.title}{where} (chunk {str(self.chunk_id)[:8]})"
def as_dict(self) -> dict[str, Any]:
return {
"chunk_id": str(self.chunk_id),
"doc_id": str(self.doc_id),
"title": self.title,
"page": self.page,
"ordinal": self.ordinal,
"text": self.text,
"score": round(self.score, 4),
"flags": list(self.flags),
"source_uri": self.source_uri,
"citation": self.citation,
}
class Reranker(Protocol):
async def rerank(self, query: str, hits: list[KnowledgeHit]) -> list[KnowledgeHit]: ...
def _terms(query: str) -> list[str]:
seen: list[str] = []
for t in re.findall(r"\w+", query.lower()):
if t not in _STOPWORDS and len(t) > 1 and t not in seen:
seen.append(t)
return seen[:32]
class KnowledgeBase:
def __init__(
self,
embedder: Embedder | None = None,
*,
reranker: Reranker | None = None,
fetcher: Fetcher | None = None,
chunk_words: int | None = None,
chunk_overlap: int | None = None,
min_cosine: float = 0.25,
) -> None:
s = get_settings()
self.embedder = embedder or HashingEmbedder()
self.reranker = reranker
self.fetcher: Fetcher = fetcher or HttpFetcher()
self.chunk_words = chunk_words or s.knowledge_chunk_words
self.chunk_overlap = s.knowledge_chunk_overlap if chunk_overlap is None else chunk_overlap
self.min_cosine = min_cosine
@property
def embed_model(self) -> str:
return str(getattr(self.embedder, "name", type(self.embedder).__name__))
async def ingest(
self,
s: AsyncSession,
tenant_id: uuid.UUID,
*,
title: str,
data: bytes,
source_type: str,
actor: str,
source_uri: str | None = None,
) -> KnowledgeDoc:
"""Parse, chunk, embed and index one document. Re-uploading identical bytes returns
the existing document."""
if source_type not in SOURCE_TYPES:
raise IngestError(f"unsupported document type: {source_type}")
if not data:
raise IngestError("empty document")
if len(data) > get_settings().knowledge_max_upload_bytes:
raise IngestError("document too large")
digest = hashlib.sha256(data).hexdigest()
existing = (
await s.execute(select(KnowledgeDoc).where(KnowledgeDoc.sha256 == digest))
).scalar_one_or_none()
if existing is not None:
return existing
pages = await asyncio.to_thread(parse, data, source_type)
chunks = chunk_pages(pages, self.chunk_words, self.chunk_overlap)
if not chunks:
raise IngestError("no text found in the document")
flagged = 0
doc = KnowledgeDoc(
id=uuid.uuid4(),
tenant_id=tenant_id,
title=title.strip()[:300] or "Untitled",
source_type=source_type,
source_uri=source_uri,
sha256=digest,
size_bytes=len(data),
page_count=len(pages) if source_type == "pdf" else None,
chunk_count=len(chunks),
status="ready",
meta={},
created_by=actor[:120],
)
s.add(doc)
await s.flush()
for i, (page, text) in enumerate(chunks):
flags = flags_for(text)
flagged += bool(flags)
s.add(
KnowledgeChunk(
tenant_id=tenant_id,
doc_id=doc.id,
ordinal=i,
page=page,
text=text,
search_doc=func.to_tsvector("english", text).op("||")(
func.to_tsvector("simple", text)
),
embedding=self.embedder.embed(f"{doc.title}. {text}"),
embed_model=self.embed_model,
flags=flags,
)
)
doc.meta = {"flagged_chunks": flagged, "embed_model": self.embed_model}
await s.flush()
return doc
async def ingest_url(
self, s: AsyncSession, tenant_id: uuid.UUID, url: str, *, actor: str, title: str | None
) -> KnowledgeDoc:
if not get_settings().knowledge_url_fetch_enabled:
raise IngestError("URL ingestion is disabled")
fetched = await self.fetcher.fetch(url)
kind = detect_type(urlsplit(fetched.url).path, fetched.content_type)
return await self.ingest(
s,
tenant_id,
title=title or fetched.url,
data=fetched.content,
source_type=kind,
actor=actor,
source_uri=fetched.url,
)
async def search(self, s: AsyncSession, query: str, k: int = 5) -> list[KnowledgeHit]:
"""Top-k chunks by 0.5 * text rank + 0.5 * cosine; a chunk needs a text match or a
cosine of at least ``min_cosine`` to be returned at all."""
terms = _terms(query)
qvec = self.embedder.embed(query)
cosine = literal_column("1") - KnowledgeChunk.embedding.cosine_distance(qvec)
text_rank: Any
if terms:
joined = " | ".join(terms)
tsq = func.to_tsquery("english", joined).op("||")(func.to_tsquery("simple", joined))
text_rank = func.ts_rank_cd(KnowledgeChunk.search_doc, tsq, 32)
else:
text_rank = literal_column("0.0")
score = (0.5 * text_rank + 0.5 * cosine).label("score")
rows = await s.execute(
select(
KnowledgeChunk,
KnowledgeDoc.title,
KnowledgeDoc.source_uri,
text_rank.label("text_rank"),
cosine.label("cosine"),
score,
)
.join(KnowledgeDoc, KnowledgeDoc.id == KnowledgeChunk.doc_id)
.where(KnowledgeChunk.embed_model == self.embed_model)
.order_by(score.desc())
.limit(max(1, k) * 4)
)
hits: list[KnowledgeHit] = []
for chunk, title, uri, tr, cos, sc in rows:
if float(tr or 0) <= 0 and float(cos or 0) < self.min_cosine:
continue
hits.append(
KnowledgeHit(
chunk_id=chunk.id,
doc_id=chunk.doc_id,
title=title,
page=chunk.page,
ordinal=chunk.ordinal,
text=chunk.text,
score=float(sc),
flags=list(chunk.flags or []),
source_uri=uri,
)
)
if self.reranker is not None and hits:
hits = await self.reranker.rerank(query, hits)
return hits[:k]
@staticmethod
async def list_docs(s: AsyncSession) -> list[KnowledgeDoc]:
return list(
(
await s.execute(select(KnowledgeDoc).order_by(KnowledgeDoc.created_at.desc()))
).scalars()
)
@staticmethod
async def chunks(s: AsyncSession, doc_id: uuid.UUID) -> list[KnowledgeChunk]:
return list(
(
await s.execute(
select(KnowledgeChunk)
.where(KnowledgeChunk.doc_id == doc_id)
.order_by(KnowledgeChunk.ordinal)
)
).scalars()
)
@staticmethod
async def delete_doc(s: AsyncSession, doc_id: uuid.UUID) -> bool:
await s.execute(delete(KnowledgeChunk).where(KnowledgeChunk.doc_id == doc_id))
res = await s.execute(
delete(KnowledgeDoc).where(KnowledgeDoc.id == doc_id).returning(KnowledgeDoc.id)
)
return res.first() is not None
|