mirror of
https://github.com/semantica-agi/semantica.git
synced 2026-08-29 04:26:20 +00:00
* feat(crewai): add first-class CrewAI integration (#962) Add native CrewAI support so Crew agents can share a ContextGraph and AgentContext via BaseTool subclasses and a BaseKnowledgeSource, matching the existing agno integration pattern. - SemanticaKGTool: 5 KG actions (extract_entities, extract_relations, add_to_graph, query_graph, find_related) with sync run()/async arun() - SemanticaDecisionTool: 5 decision-intelligence actions (record_decision, find_precedents, trace_causal_chain, analyze_impact, check_policy) over AgentContext - SemanticaKnowledgeSource: serializes a ContextGraph into crew knowledge storage; bridges legacy load_content() and current validate_content()/aadd() contracts for crewai>=0.80.0 - All classes degrade gracefully when crewai is absent - New pip extra crewai=... included in the all bundle - 70 new tests (stub-based present-case + subprocess degradation path) - Docs: integrations/crewai.md, docs.json nav, README matrix updates * fix(crewai): harden tools against real Semantica dataclass shapes (#962) Bugs found during live testing with crewai 1.15.16: - SemanticaKGTool.add_to_graph crashed on real Entity/Relation dataclasses ('str' object has no attribute 'end_char'): string names were passed to extract_relations(entities=...), which requires Entity objects, and the tool read .name/.source/.target instead of Entity's .text/.label and Relation's .subject/.object. Add shape-agnostic field helpers. - SemanticaDecisionTool() created an AgentContext without a knowledge_graph, so _decision_backend was never set and record_decision raised 'Decision tracking is not enabled'. Wire in a ContextGraph. - record_decision hard-failed when the agent omitted optional fields; fall back to category='general', reasoning='agent decision', outcome='recorded'. Add tests covering real Entity/Relation dataclass shapes and the live auto-created AgentContext path (now 77 crewai tests, 212 total). * fix(crewai): make find_related traverse edges undirected (#962) ContextGraph.get_neighbors only follows outgoing edges, so a node whose only edge is incoming (A -> B) reported no related concepts. Rebuild a bidirectional adjacency from find_edges() in SemanticaKGTool._find_related so 'related' honors both directions. * fix(crewai): harden tools for checkpoint serialization and correct action semantics (#962) - Exclude live graph/context/extractor state from JSON serialization (model_dump(mode="json")) so CrewAI checkpointing no longer raises PydanticSerializationError; model_post_init self-heals defaults on restore - query_graph now searches node content via graph.query() plus id/type - trace_causal_chain returns an explicit error when causal tracing is unavailable instead of substituting similarity precedents; call trace_decision_causality(..., max_depth=...) with the correct kwarg name - find_precedents propagates max_precedents/limit to the backend instead of being silently capped at 10 - Serialize add_to_graph batches under a module lock to prevent concurrent double-counting; skip nameless entities instead of creating repr()-junk nodes - aadd() runs CPU-bound serialization in a thread executor - Mirror crewai args_schema serialize/restore in the conftest stub and add serialization regression tests (crewai: 92 tests) * fix(crewai): correct check_policy coercion, guard causal tracing, and harden concurrency (#962) - _eval_rule now coerces rule values type-aware: bool("false") was truthy, so 'enabled == false' reported a violation for enabled=false, and string datums like "0.90" were compared lexicographically instead of numerically - _trace_causal_chain no longer raises AttributeError (which escaped _run) when the decision context lacks knowledge_graph; returns honest error JSON - SemanticaKnowledgeSource storage failures log an actionable ERROR; without a configured crew embedder agents previously retrieved nothing silently - add_to_graph uses a per-graph re-entrant lock (WeakKeyDictionary) instead of a process-global one: independent graphs no longer serialize each other and re-entrant extractor callbacks cannot deadlock - entity/relation confidence=None normalizes to 1.0 instead of failing the whole extraction with float(None) - add subprocess integration test against real crewai covering Crew-level serialization round-trip and checkpoint restore (stub tests cannot see it) - docs: embedder requirement for SemanticaKnowledgeSource; resume contract note * fix(crewai): surface knowledge-source save failures at ERROR when storage is wired (#962) Re-verification against real crewai showed the embedder-missing failure raises ValueError even though storage IS wired, so the old except-ValueError branch mislabeled it as 'storage not wired' and logged DEBUG — hiding the failure. Distinguish by storage presence instead of exception type: storage is None -> DEBUG keep-in-memory (legitimate standalone use); storage wired but save() raises -> actionable ERROR. Add regression test mirroring real crewai's ValueError-on-missing-embedder behavior. * fix(crewai): expose run()/arun() entry points in degraded mode (#962) The public crewai contract is run()/arun(); without crewai installed they were missing (only the private _run existed), so the documented 'usable without crewai' path raised AttributeError at the entry point. Define them in degraded mode only, leaving crewai's BaseTool implementations untouched when present. Extend the degradation subprocess test to exercise run() and arun(). * fix(crewai): standardize query shape, field-name rules, and restore-state flag - _query_graph: id/type matches now return the same schema as content matches (id/type/label/content/score) instead of a bare list - _eval_rule: non-greedy field capture so hyphen/dot/space JSON keys (e.g. "risk-score >= 0.9") are addressable in policy rules - add had_live_state/reconstructed_state so checkpoint-restored tools and knowledge sources signal that their live graph/context was lost and an empty one reconstructed; knowledge source no longer hides the loss by eagerly rebuilding its graph inside __init__ (pydantic calls __init__ during model_validate) * fix(crewai): address Qodo review — confidence errors, string trim, holistic availability - record_decision: stop calling float() in _run, so malformed confidence values surface as JSON errors (via _record_decision's handling) instead of crashing the tool - _coerce_value: return the stripped string for non-numeric literals so whitespace-padded decision_data fields match policy rules - centralize crewai availability in _availability.py so the exported CREWAI_AVAILABLE flag is holistic across tools and knowledge source (previously each module probed crewai independently and the package flag came from decision_tool only) * ci: regenerate requirements-ci.txt for the crewai extra The crewai extra in pyproject.toml brings in crewai, crewai-tools and transitive deps (chromadb, lancedb, ...). Recompile with uv==0.12.1 per CONTRIBUTING.md so the CI staleness check passes. * ci: keep crewai out of the locked CI dependency set crewai (all versions) hard-requires chromadb~=1.1.0, which carries a pre-authentication code-injection advisory (CVE-2026-45829 / GHSA-f4j7-r4q5-qw2c) with NO fixed release — even the latest 1.5.9 is affected. Keeping crewai in the 'all' extra failed pip-audit and the safety check on requirements-ci.txt. - drop crewai from the 'all' aggregate (standalone semantica[crewai] extra is unchanged and still installs crewai) - stop listing crewai-tools in the extra: the integration only uses crewai core (BaseTool, BaseKnowledgeSource) and crewai-tools pulled extra transitive deps - regenerate requirements-ci.txt: OSV/pip-audit 0 vulnerabilities, safety 0 vulnerabilities, staleness check matches * docs(crewai): document crewai extra scope and chromadb CVE-2026-45829 - CHANGELOG: extra is crewai>=0.80.0 only (no crewai-tools) and is not part of the 'all' bundle, with the chromadb CVE-2026-45829 reason - integrations/crewai/README.md: add a security warning that installing the extra pulls chromadb~=1.1.0, which is affected by the unpatched pre-auth code-injection CVE-2026-45829 ---------
332 lines
12 KiB
Python
332 lines
12 KiB
Python
"""
|
|
SemanticaKnowledgeSource — expose a Semantica ``ContextGraph`` as a CrewAI
|
|
knowledge source.
|
|
|
|
Lets a ``Crew`` load the current state of a knowledge graph (nodes, edges,
|
|
metadata) into its knowledge storage, so every agent gets retrieval access to
|
|
graph knowledge during the kickoff.
|
|
|
|
Install
|
|
-------
|
|
pip install semantica[crewai]
|
|
|
|
Example
|
|
-------
|
|
>>> from integrations.crewai import SemanticaKnowledgeSource
|
|
>>> from semantica.context import ContextGraph
|
|
>>> from crewai import Agent, Crew, Task
|
|
>>> graph = ContextGraph()
|
|
>>> graph.add_node(node_id="privacy", node_type="policy")
|
|
>>> crew = Crew(
|
|
... agents=[...],
|
|
... tasks=[...],
|
|
... knowledge_sources=[SemanticaKnowledgeSource(graph=graph)],
|
|
... )
|
|
|
|
Compatibility
|
|
-------------
|
|
Works with ``crewai >= 0.80.0``. The ``BaseKnowledgeSource`` contract changed
|
|
between versions (``load_content`` → ``validate_content``/``aadd``), so this
|
|
source implements both legacy and current methods. It degrades gracefully
|
|
when ``crewai`` is not installed: the class is still importable and carries the
|
|
full Semantica API, but cannot be passed to a ``Crew``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
from pydantic import Field
|
|
|
|
from semantica.utils.logging import get_logger
|
|
|
|
from ._availability import CREWAI_AVAILABLE
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Optional: CrewAI BaseKnowledgeSource base class
|
|
# ---------------------------------------------------------------------------
|
|
_BaseKnowledgeSource: Any = object
|
|
|
|
if CREWAI_AVAILABLE:
|
|
from crewai.knowledge.source.base_knowledge_source import (
|
|
BaseKnowledgeSource as _BaseKnowledgeSource, # type: ignore
|
|
)
|
|
|
|
|
|
def _chunk_text_manual(text: str, chunk_size: int, chunk_overlap: int) -> List[str]:
|
|
"""Fallback plain-text chunker for when CrewAI helpers are unavailable."""
|
|
if not text:
|
|
return []
|
|
if int(chunk_size) <= 0:
|
|
return [text]
|
|
size = max(1, int(chunk_size))
|
|
overlap = max(0, int(chunk_overlap))
|
|
if len(text) <= size:
|
|
return [text]
|
|
step = max(1, size - overlap)
|
|
return [text[i : i + size] for i in range(0, len(text), step)]
|
|
|
|
|
|
class SemanticaKnowledgeSource(_BaseKnowledgeSource): # type: ignore[misc]
|
|
"""
|
|
CrewAI knowledge source backed by a Semantica ``ContextGraph``.
|
|
|
|
On ``add()`` the graph's nodes and edges are serialised into readable text
|
|
and pushed through the standard CrewAI chunking / storage pipeline, making
|
|
graph knowledge retrievable by every agent in the crew.
|
|
|
|
Parameters
|
|
----------
|
|
graph:
|
|
A ``semantica.context.ContextGraph`` to expose. A fresh in-memory
|
|
graph is created when ``None``.
|
|
name:
|
|
Source name. Defaults to ``"semantica_knowledge_graph"``.
|
|
chunk_size:
|
|
Max characters per chunk (default 4000).
|
|
chunk_overlap:
|
|
Character overlap between adjacent chunks (default 200).
|
|
"""
|
|
|
|
name: str = "semantica_knowledge_graph"
|
|
graph: Any = Field(default=None, exclude=True)
|
|
chunk_size: int = 4000
|
|
chunk_overlap: int = 200
|
|
had_live_state: bool = False
|
|
reconstructed_state: bool = Field(default=False, exclude=True)
|
|
|
|
def __init__(
|
|
self,
|
|
graph: Any = None,
|
|
name: Optional[str] = None,
|
|
chunk_size: int = 4000,
|
|
chunk_overlap: int = 200,
|
|
**kwargs: Any,
|
|
) -> None:
|
|
if CREWAI_AVAILABLE:
|
|
# Do NOT eagerly build a graph here: pydantic calls this ``__init__``
|
|
# during ``model_validate`` (checkpoint restore), and the eager
|
|
# build would hide that a live graph was lost. ``model_post_init``
|
|
# rebuilds defaults and flags ``reconstructed_state`` instead.
|
|
super().__init__(
|
|
graph=graph,
|
|
name=name or "semantica_knowledge_graph",
|
|
chunk_size=int(chunk_size),
|
|
chunk_overlap=int(chunk_overlap),
|
|
**kwargs,
|
|
)
|
|
else:
|
|
if graph is None:
|
|
from semantica.context import ContextGraph
|
|
|
|
graph = ContextGraph()
|
|
super().__init__()
|
|
self.graph = graph
|
|
self.name = name or "semantica_knowledge_graph"
|
|
self.chunk_size = int(chunk_size)
|
|
self.chunk_overlap = int(chunk_overlap)
|
|
|
|
logger.info(
|
|
"SemanticaKnowledgeSource initialised (crewai=%s, chunk_size=%d)",
|
|
CREWAI_AVAILABLE,
|
|
self.chunk_size,
|
|
)
|
|
self.had_live_state = True
|
|
|
|
def model_post_init(self, __context: Any) -> None:
|
|
"""Re-create default state after validation/deserialisation.
|
|
|
|
``graph`` is excluded from JSON serialisation (CrewAI checkpoints
|
|
serialise their models via ``model_dump(mode="json")``), so a source
|
|
restored from a checkpoint has ``None`` state until this runs.
|
|
"""
|
|
if self.graph is None:
|
|
from semantica.context import ContextGraph
|
|
|
|
self.graph = ContextGraph()
|
|
if self.had_live_state:
|
|
self.reconstructed_state = True
|
|
logger.warning(
|
|
"SemanticaKnowledgeSource: the live graph was lost during "
|
|
"serialization/checkpoint restore — an EMPTY graph was "
|
|
"reconstructed; re-attach the original graph before "
|
|
"continuing"
|
|
)
|
|
else:
|
|
logger.warning(
|
|
"SemanticaKnowledgeSource created a fresh in-memory "
|
|
"ContextGraph — sources sharing knowledge must be wired to "
|
|
"the same graph explicitly"
|
|
)
|
|
self.had_live_state = True
|
|
super().model_post_init(__context)
|
|
|
|
# ------------------------------------------------------------------
|
|
# Content extraction
|
|
# ------------------------------------------------------------------
|
|
|
|
def load_content(self) -> Dict[str, str]:
|
|
"""
|
|
Serialise the graph into ``{id: readable_text}`` pairs.
|
|
|
|
Nodes are rendered with their type/content/metadata, edges with their
|
|
source, relation type and target. This satisfies the legacy CrewAI
|
|
``BaseKnowledgeSource.load_content`` contract.
|
|
"""
|
|
content: Dict[str, str] = {}
|
|
graph = self.graph
|
|
if graph is None:
|
|
return content
|
|
|
|
try:
|
|
for node in graph.find_nodes() or []: # type: ignore[attr-defined]
|
|
nid = node.get("id") or node.get("node_id") or ""
|
|
if not nid:
|
|
continue
|
|
parts = [
|
|
"Entity",
|
|
str(nid),
|
|
"type: " + str(node.get("type", "entity")),
|
|
]
|
|
if node.get("content"):
|
|
parts.append("content: " + str(node["content"]))
|
|
if node.get("metadata"):
|
|
try:
|
|
import json
|
|
|
|
parts.append("metadata: " + json.dumps(node["metadata"]))
|
|
except Exception:
|
|
parts.append("metadata: " + str(node["metadata"]))
|
|
content[str(nid)] = " | ".join(parts)
|
|
except Exception as exc:
|
|
logger.warning(
|
|
"SemanticaKnowledgeSource.load_content (nodes) failed: %s", exc
|
|
)
|
|
|
|
try:
|
|
for idx, edge in enumerate(
|
|
graph.find_edges() or [] # type: ignore[attr-defined]
|
|
):
|
|
src = edge.get("source")
|
|
tgt = edge.get("target")
|
|
if not src or not tgt:
|
|
continue
|
|
rel = edge.get("type") or edge.get("edge_type") or "related_to"
|
|
weight = edge.get("weight")
|
|
text = f"{src} -[{rel}]-> {tgt}"
|
|
if weight is not None:
|
|
text += f" (weight: {weight})"
|
|
content[f"edge-{idx}"] = text
|
|
except Exception as exc:
|
|
logger.warning(
|
|
"SemanticaKnowledgeSource.load_content (edges) failed: %s", exc
|
|
)
|
|
|
|
return content
|
|
|
|
def validate_content(self) -> Any:
|
|
"""
|
|
Validate that a readable graph is attached.
|
|
|
|
Satisfies the current CrewAI ``BaseKnowledgeSource.validate_content``
|
|
contract.
|
|
"""
|
|
if self.graph is None:
|
|
raise ValueError("SemanticaKnowledgeSource requires a ContextGraph.")
|
|
return True
|
|
|
|
# ------------------------------------------------------------------
|
|
# Chunking + storage (abstract in both CrewAI generations)
|
|
# ------------------------------------------------------------------
|
|
|
|
def _chunk(self, text: str) -> List[str]:
|
|
"""Chunk ``text`` using CrewAI's helper when available, else manual."""
|
|
helper = getattr(self, "_chunk_text", None)
|
|
if helper is not None:
|
|
try:
|
|
return list(helper(text) or [])
|
|
except Exception as exc:
|
|
logger.debug(
|
|
"SemanticaKnowledgeSource._chunk_text failed, falling back: %s", exc
|
|
)
|
|
return _chunk_text_manual(text, self.chunk_size, self.chunk_overlap)
|
|
|
|
def add(self) -> None:
|
|
"""
|
|
Process the graph into chunks and store them via CrewAI storage.
|
|
|
|
Sets both ``chunks`` (current CrewAI) and ``_chunks`` (legacy CrewAI)
|
|
so either ``_save_documents`` implementation picks them up. If no
|
|
storage has been wired (e.g. not yet attached to a ``Crew``), chunks
|
|
are kept in memory.
|
|
"""
|
|
content = self.load_content()
|
|
if not content:
|
|
logger.debug("SemanticaKnowledgeSource.add: empty graph — nothing to store")
|
|
return
|
|
|
|
chunks: List[str] = []
|
|
for _, text in content.items():
|
|
if text:
|
|
chunks.extend(self._chunk(text))
|
|
|
|
self.chunks = chunks
|
|
self._chunks = chunks
|
|
|
|
save = getattr(self, "_save_documents", None)
|
|
if save is not None:
|
|
if getattr(self, "storage", None) is None:
|
|
logger.debug(
|
|
"SemanticaKnowledgeSource.add: storage not wired — "
|
|
"keeping chunks in memory"
|
|
)
|
|
else:
|
|
try:
|
|
save()
|
|
logger.info(
|
|
"SemanticaKnowledgeSource.add: stored %d chunks", len(chunks)
|
|
)
|
|
return
|
|
except Exception as exc:
|
|
logger.error(
|
|
"SemanticaKnowledgeSource.add: storage save FAILED (%s) — "
|
|
"chunks are only kept in memory and agents will retrieve "
|
|
"nothing. Configure the Crew embedder (e.g. an OpenAI "
|
|
"embedder with OPENAI_API_KEY, or a local embedder) before "
|
|
"running the crew.",
|
|
exc,
|
|
)
|
|
|
|
logger.info(
|
|
"SemanticaKnowledgeSource.add: %d chunks ready in memory", len(chunks)
|
|
)
|
|
|
|
async def aadd(self) -> None:
|
|
"""
|
|
Asynchronous variant of ``add()`` (current CrewAI contract).
|
|
|
|
The graph serialisation is CPU-bound, so it runs in a thread pool to
|
|
avoid blocking the event loop.
|
|
"""
|
|
loop = asyncio.get_running_loop()
|
|
await loop.run_in_executor(None, self.add)
|
|
|
|
# ------------------------------------------------------------------
|
|
# Inspection helpers
|
|
# ------------------------------------------------------------------
|
|
|
|
def get_content_summary(self) -> Dict[str, Any]:
|
|
"""
|
|
Summarise what the source exposes (helpful for debugging / testing).
|
|
"""
|
|
content = self.load_content()
|
|
return {
|
|
"name": self.name,
|
|
"source_count": len(content),
|
|
"chunks": len(getattr(self, "chunks", []) or []),
|
|
"crewai_available": CREWAI_AVAILABLE,
|
|
}
|