Source identity
| Field | Recorded value |
|---|---|
| Source type | GitHub source |
| Original record | Janady13/AI_Brain / services/knowledge_pipeline.py |
| Date | Not specified in source |
| Repository | Janady13/AI_Brain |
| Revision | 50285aff347685f043e7a72e4d72891eebaa6cd6 |
| Branch | codex/build-online-github-ani-hrtsoc |
| Path or archive member | services/knowledge_pipeline.py |
| Original SHA-256 | 426822aa7d6616b8bc3fb2bd1f04922003473ef8d57563f8574f83937014b26c |
| Git blob SHA | 8b412cd0e5a6323103d7a29dc3db5d6598dac7c4 |
| Reading-copy SHA-256 | 426822aa7d6616b8bc3fb2bd1f04922003473ef8d57563f8574f83937014b26c |
Every recorded occurrence
These 9 records contain identical original source bytes. Their paths and revisions remain part of the archive.
| Original record | Branch or archive | Revision / identifier | Original location |
|---|---|---|---|
| Janady13/AI_Brain / services/knowledge_pipeline.py | codex/build-online-github-ani-hrtsoc | 50285aff347685f043e7a72e4d72891eebaa6cd6 | Open original |
| Janady13/AI_Brain / services/knowledge_pipeline.py | codex/build-online-github-ani-7v4kug | 5cd0bbf744b0aee9445913337e852889d9a8098e | Open original |
| Janady13/AI_Brain / services/knowledge_pipeline.py | copilot/vscode1760283895982 | 9e1c1a5b171addb5bb4a83b2ea7dede50c1cc81e | Open original |
| Janady13/AI_Brain / services/knowledge_pipeline.py | feature/seeder-engine-tests | cdb497ece2d1a770ca8c83eb1de8923cfaa9eceb | Open original |
| Janady13/AI_Brain / services/knowledge_pipeline.py | codex/build-online-github-ani-7nmb21 | d0f50071c85cddaaebbf9c4dd1313bd7676986da | Open original |
| Janady13/AI_Brain / services/knowledge_pipeline.py | codex/build-online-github-ani-7v4kug | 5cd0bbf744b0aee9445913337e852889d9a8098e | Open original |
| Janady13/AI_Brain / services/knowledge_pipeline.py | copilot/vscode1760283895982 | 9e1c1a5b171addb5bb4a83b2ea7dede50c1cc81e | Open original |
| Janady13/AI_Brain / services/knowledge_pipeline.py | feature/seeder-engine-tests | cdb497ece2d1a770ca8c83eb1de8923cfaa9eceb | Open original |
| Janady13/AI_Brain / services/knowledge_pipeline.py | codex/build-online-github-ani-hrtsoc | 50285aff347685f043e7a72e4d72891eebaa6cd6 | Open original |
Recovered source transcript
Download complete source text ↓331 lines · 11.3 KB
"""Lightweight knowledge orchestration demo covering RAG and KAG flows.
The repository’s marketing ANI exposes rich process payloads for retrieval-
augmented generation (RAG) and knowledge-augmented generation (KAG). The
production services already synthesise these insights, but it can be handy to
have a standalone executable module that demonstrates the core mechanics with
minimal dependencies. This module keeps the implementation intentionally
simple so it can run in constrained environments while still mimicking the
steps outlined in the documentation:
* **Indexing** – documents are split into manageable chunks and converted into
term-frequency vectors ready for fast cosine similarity searches.
* **Retrieval** – queries are embedded with the same lightweight tokenizer and
matched against the indexed chunks to surface relevant context, giving us a
local RAG demo without external services.
* **Knowledge graph reasoning** – structured facts are captured in a small
in-memory graph so we can traverse relationships and ground answers with
explicit entity links, mirroring a KAG flow.
* **Orchestration** – the :class:`KnowledgeWorkflowOrchestrator` blends both
approaches, returning combined context and reasoning trails that resemble the
payload emitted by the marketing ANI’s processes endpoint.
The goal is to make it easy for contributors (and automated smoke tests) to
verify that the conceptual pipelines run end-to-end. The code favours
deterministic behaviour over sophistication so that unit tests can assert on
exact outputs without relying on heavyweight ML frameworks.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import re
from collections import Counter, defaultdict
from dataclasses import dataclass, asdict
from typing import Dict, Iterator, List, Mapping, MutableMapping, Sequence
_TOKEN_PATTERN = re.compile(r"[A-Za-z0-9]+")
def _tokenize(text: str) -> List[str]:
"""Tokenise ``text`` into lowercase word tokens.
The helper intentionally keeps the implementation minimal so the demo does
not rely on heavy NLP libraries. Tokens are restricted to alphanumeric
characters which keeps outputs predictable for unit tests.
"""
return [token.lower() for token in _TOKEN_PATTERN.findall(text)]
def _normalise(counter: Counter[str]) -> Dict[str, float]:
"""Convert a raw term frequency ``counter`` into L2-normalised weights."""
magnitude = math.sqrt(sum(value * value for value in counter.values()))
if magnitude == 0.0:
return {}
return {key: value / magnitude for key, value in counter.items()}
def _cosine_similarity(lhs: Mapping[str, float], rhs: Mapping[str, float]) -> float:
"""Compute cosine similarity between two sparse vectors."""
if not lhs or not rhs:
return 0.0
if len(lhs) > len(rhs):
lhs, rhs = rhs, lhs
return sum(weight * rhs.get(term, 0.0) for term, weight in lhs.items())
def _chunk_text(text: str, *, max_tokens: int) -> Iterator[str]:
"""Yield whitespace-trimmed chunks that do not exceed ``max_tokens`` tokens."""
sentences = re.split(r"(?<=[.!?])\s+", text.strip()) if text.strip() else []
buffer: List[str] = []
token_count = 0
for sentence in sentences:
sentence_tokens = _tokenize(sentence)
if not sentence_tokens:
continue
if token_count + len(sentence_tokens) > max_tokens and buffer:
yield " ".join(buffer).strip()
buffer = [sentence]
token_count = len(sentence_tokens)
else:
buffer.append(sentence)
token_count += len(sentence_tokens)
if buffer:
yield " ".join(buffer).strip()
@dataclass(frozen=True)
class DocumentChunk:
"""Indexed document chunk used by the :class:`RAGPipeline`."""
doc_id: str
chunk_index: int
text: str
vector: Mapping[str, float]
class RAGPipeline:
"""Very small RAG pipeline used for local demonstrations and tests."""
def __init__(self, *, chunk_token_limit: int = 120) -> None:
self._chunk_token_limit = chunk_token_limit
self._chunks: List[DocumentChunk] = []
self._cache: MutableMapping[str, List[DocumentChunk]] = {}
@property
def chunks(self) -> Sequence[DocumentChunk]:
return tuple(self._chunks)
def index(self, documents: Mapping[str, str]) -> None:
"""Index ``documents`` ready for retrieval queries."""
self._chunks.clear()
self._cache.clear()
for doc_id, text in documents.items():
for chunk_index, chunk_text in enumerate(
_chunk_text(text, max_tokens=self._chunk_token_limit)
):
tokens = Counter(_tokenize(chunk_text))
if not tokens:
continue
self._chunks.append(
DocumentChunk(
doc_id=doc_id,
chunk_index=chunk_index,
text=chunk_text,
vector=_normalise(tokens),
)
)
def search(self, query: str, *, limit: int = 3) -> List[DocumentChunk]:
"""Return up to ``limit`` document chunks relevant to ``query``."""
if query in self._cache:
return list(self._cache[query][:limit])
query_tokens = Counter(_tokenize(query))
query_vector = _normalise(query_tokens)
scored: List[tuple[float, DocumentChunk]] = []
for chunk in self._chunks:
score = _cosine_similarity(chunk.vector, query_vector)
if score <= 0.0:
continue
scored.append((score, chunk))
scored.sort(key=lambda item: item[0], reverse=True)
top_chunks = [chunk for _, chunk in scored[:limit]]
self._cache[query] = top_chunks
return list(top_chunks)
@dataclass(frozen=True)
class KnowledgeEdge:
"""Represents a directed edge in the demo knowledge graph."""
source: str
relation: str
target: str
evidence: str | None = None
class KnowledgeGraph:
"""Extremely small in-memory knowledge graph with simple traversal."""
def __init__(self) -> None:
self._graph: MutableMapping[str, List[KnowledgeEdge]] = defaultdict(list)
def add_fact(
self,
source: str,
relation: str,
target: str,
*,
evidence: str | None = None,
) -> None:
edge = KnowledgeEdge(source=source, relation=relation, target=target, evidence=evidence)
self._graph[source].append(edge)
def related(self, entity: str, relation: str | None = None) -> List[KnowledgeEdge]:
edges = list(self._graph.get(entity, ()))
if relation is None:
return edges
return [edge for edge in edges if edge.relation == relation]
def reason(self, query: str) -> List[KnowledgeEdge]:
"""Retrieve graph edges that align with ``query`` tokens."""
tokens = set(_tokenize(query))
matched: List[KnowledgeEdge] = []
for edges in self._graph.values():
for edge in edges:
edge_tokens = set(_tokenize(edge.source)) | set(_tokenize(edge.relation)) | set(
_tokenize(edge.target)
)
if edge_tokens & tokens:
matched.append(edge)
return matched
@dataclass(frozen=True)
class KnowledgeWorkflowAnswer:
"""Combined answer produced by orchestrating RAG and KAG flows."""
rag_context: List[str]
knowledge_edges: List[KnowledgeEdge]
def to_dict(self) -> Dict[str, object]:
return {
"rag_context": list(self.rag_context),
"knowledge_edges": [asdict(edge) for edge in self.knowledge_edges],
}
class KnowledgeWorkflowOrchestrator:
"""Fuse RAG and KAG results into a single structured response."""
def __init__(self, rag: RAGPipeline, graph: KnowledgeGraph) -> None:
self._rag = rag
self._graph = graph
def answer(self, query: str, *, limit: int = 3) -> KnowledgeWorkflowAnswer:
rag_chunks = self._rag.search(query, limit=limit)
edges = self._graph.reason(query)
return KnowledgeWorkflowAnswer(
rag_context=[chunk.text for chunk in rag_chunks],
knowledge_edges=edges,
)
def _load_default_documents() -> Dict[str, str]:
"""Load demonstration documents that complement the marketing ANI datasets."""
base_dir = os.path.join(os.path.dirname(__file__), "..", "daemon", "datasets")
dataset_path = os.path.abspath(os.path.join(base_dir, "knowledge_workflows.json"))
documents: Dict[str, str] = {}
try:
with open(dataset_path, "r", encoding="utf-8") as handle:
payload = json.load(handle)
except FileNotFoundError:
return documents
for plan in payload:
key = f"{plan['category']}_{plan['name']}"
description = plan.get("description") or ""
indexing_steps = plan.get("indexing_steps") or []
retrieval_steps = plan.get("retrieval_steps") or []
governance = plan.get("governance") or []
evaluation = plan.get("evaluation") or []
content_parts = [
description,
" ".join(indexing_steps),
" ".join(retrieval_steps),
" ".join(governance),
" ".join(evaluation),
]
documents[key] = " ".join(part for part in content_parts if part)
return documents
def _build_demo_graph() -> KnowledgeGraph:
graph = KnowledgeGraph()
graph.add_fact(
"retrieval_pipeline",
"uses",
"vector_database",
evidence="Vector search keeps embeddings queryable for RAG.",
)
graph.add_fact(
"knowledge_graph",
"aligns_with",
"prompt_diagnostics",
evidence="Structured triples link prompts to governance policies.",
)
graph.add_fact(
"agent_loop",
"includes",
"reflection",
evidence="Post-action analysis keeps the ANI adaptive.",
)
graph.add_fact(
"moe_router",
"activates",
"stripe",
evidence="Stripe expert handles monetisation strategies.",
)
graph.add_fact(
"moe_router",
"activates",
"google_ads",
evidence="Google Ads expert supplies paid acquisition intelligence.",
)
return graph
def run_demo(query: str, *, limit: int = 3) -> KnowledgeWorkflowAnswer:
"""Execute the lightweight RAG+KAG demo for ``query``."""
rag = RAGPipeline()
rag.index(_load_default_documents())
graph = _build_demo_graph()
orchestrator = KnowledgeWorkflowOrchestrator(rag=rag, graph=graph)
return orchestrator.answer(query, limit=limit)
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Run the lightweight RAG/KAG demo")
parser.add_argument(
"query",
nargs="?",
default="How do the RAG and KAG workflows keep monetisation grounded?",
help="Natural language query to execute",
)
parser.add_argument("--limit", type=int, default=3, help="Maximum RAG chunks to return")
return parser.parse_args()
def main() -> None:
args = _parse_args()
answer = run_demo(args.query, limit=args.limit)
print(json.dumps(answer.to_dict(), indent=2))
if __name__ == "__main__": # pragma: no cover - exercised via smoke usage
main()