Spaces:
Running

WorkPilot-AI / core /memory /knowledge.py
Aynkhn's picture
Deploy WorkPilot demo
fd5dd94 verified
Raw History Blame Contribute Delete
17.1 kB
"""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