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 ---------
229 lines
8.5 KiB
Python
229 lines
8.5 KiB
Python
"""
|
|
Tests for SemanticaKnowledgeSource — CrewAI knowledge source backed by a
|
|
Semantica ContextGraph.
|
|
|
|
Runs with the crewai stubs installed by conftest, so ``CREWAI_AVAILABLE`` is
|
|
``True`` and the real Pydantic/BaseKnowledgeSource subclassing path (including
|
|
the current ``validate_content`` / ``add`` / ``aadd`` contract) is exercised.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import unittest
|
|
|
|
from integrations.crewai import SemanticaKnowledgeSource
|
|
from integrations.crewai.knowledge_source import CREWAI_AVAILABLE, _chunk_text_manual
|
|
from semantica.context import ContextGraph
|
|
|
|
|
|
class _FakeStorage:
|
|
def __init__(self):
|
|
self.saved_chunks: list = []
|
|
|
|
def save(self, chunks: list) -> None:
|
|
self.saved_chunks.extend(chunks)
|
|
|
|
async def asave(self, chunks: list) -> None:
|
|
self.saved_chunks.extend(chunks)
|
|
|
|
|
|
class _RaisingStorage(_FakeStorage):
|
|
"""Mirrors real crewai: storage is wired but ``save`` raises ``ValueError``
|
|
(e.g. the embedder has no credentials configured)."""
|
|
|
|
def save(self, chunks: list) -> None:
|
|
raise ValueError("The OPENAI_API_KEY environment variable is not set.")
|
|
|
|
async def asave(self, chunks: list) -> None:
|
|
raise ValueError("The OPENAI_API_KEY environment variable is not set.")
|
|
|
|
|
|
def _build_graph() -> ContextGraph:
|
|
graph = ContextGraph()
|
|
graph.add_node(node_id="privacy", node_type="policy", content="privacy policy doc")
|
|
graph.add_node(node_id="fraud", node_type="risk", content="fraud detection rules")
|
|
graph.add_edge(source_id="privacy", target_id="fraud", edge_type="constrains")
|
|
return graph
|
|
|
|
|
|
class TestSemanticaKnowledgeSourceInit(unittest.TestCase):
|
|
|
|
def test_crewai_available_via_stub(self):
|
|
self.assertTrue(CREWAI_AVAILABLE)
|
|
|
|
def test_is_base_knowledge_source_subclass(self):
|
|
from crewai.knowledge.source import BaseKnowledgeSource
|
|
|
|
self.assertTrue(issubclass(SemanticaKnowledgeSource, BaseKnowledgeSource))
|
|
|
|
def test_creates_with_explicit_graph(self):
|
|
graph = _build_graph()
|
|
src = SemanticaKnowledgeSource(graph=graph)
|
|
self.assertIs(src.graph, graph)
|
|
|
|
def test_creates_fresh_graph_when_none(self):
|
|
src = SemanticaKnowledgeSource()
|
|
self.assertIsNotNone(src.graph)
|
|
self.assertIsInstance(src.graph, ContextGraph)
|
|
|
|
def test_default_metadata(self):
|
|
src = SemanticaKnowledgeSource(graph=_build_graph())
|
|
self.assertEqual(src.name, "semantica_knowledge_graph")
|
|
self.assertEqual(src.chunk_size, 4000)
|
|
self.assertEqual(src.chunk_overlap, 200)
|
|
|
|
def test_custom_chunking_params(self):
|
|
src = SemanticaKnowledgeSource(
|
|
graph=_build_graph(), chunk_size=50, chunk_overlap=10
|
|
)
|
|
self.assertEqual(src.chunk_size, 50)
|
|
self.assertEqual(src.chunk_overlap, 10)
|
|
|
|
|
|
class TestLoadContent(unittest.TestCase):
|
|
|
|
def setUp(self):
|
|
self.graph = _build_graph()
|
|
self.src = SemanticaKnowledgeSource(graph=self.graph)
|
|
|
|
def test_nodes_serialized(self):
|
|
content = self.src.load_content()
|
|
text = "\n".join(content.values())
|
|
self.assertIn("privacy", text)
|
|
self.assertIn("fraud", text)
|
|
self.assertIn("policy", text)
|
|
|
|
def test_edges_serialized(self):
|
|
content = self.src.load_content()
|
|
text = "\n".join(content.values())
|
|
self.assertIn("-[" + "constrains" + "]->", text)
|
|
|
|
def test_empty_graph_returns_empty(self):
|
|
src = SemanticaKnowledgeSource(graph=ContextGraph())
|
|
self.assertEqual(src.load_content(), {})
|
|
|
|
def test_validate_content_passes(self):
|
|
self.assertTrue(self.src.validate_content())
|
|
|
|
def test_validate_content_raises_without_graph(self):
|
|
self.src.graph = None
|
|
with self.assertRaises(ValueError):
|
|
self.src.validate_content()
|
|
|
|
|
|
class TestAdd(unittest.TestCase):
|
|
|
|
def setUp(self):
|
|
self.graph = _build_graph()
|
|
self.src = SemanticaKnowledgeSource(
|
|
graph=self.graph, chunk_size=40, chunk_overlap=5
|
|
)
|
|
|
|
def test_add_saves_chunks_to_storage(self):
|
|
storage = _FakeStorage()
|
|
self.src.storage = storage
|
|
self.src.add()
|
|
self.assertGreater(len(storage.saved_chunks), 0)
|
|
self.assertTrue(all(isinstance(c, str) and c for c in storage.saved_chunks))
|
|
|
|
def test_add_without_storage_keeps_chunks_in_memory(self):
|
|
self.src.add()
|
|
self.assertGreater(len(self.src.chunks), 0)
|
|
self.assertGreater(len(self.src._chunks), 0)
|
|
|
|
def test_add_wired_storage_failure_logs_error_not_debug(self):
|
|
"""Regression: real crewai raises ``ValueError`` for a missing embedder
|
|
even though storage IS wired. That used to fall into the "storage not
|
|
wired" DEBUG branch, silently hiding the failure — it must log an
|
|
actionable ERROR instead."""
|
|
self.src.storage = _RaisingStorage()
|
|
with self.assertLogs(
|
|
f"semantica.{SemanticaKnowledgeSource.__module__}", level="ERROR"
|
|
) as caught:
|
|
self.src.add()
|
|
joined = "\n".join(caught.output)
|
|
self.assertIn("storage save FAILED", joined)
|
|
self.assertIn("OPENAI_API_KEY", joined)
|
|
self.assertGreater(len(self.src.chunks), 0)
|
|
|
|
def test_add_empty_graph_no_chunks(self):
|
|
src = SemanticaKnowledgeSource(
|
|
graph=ContextGraph(), chunk_size=40, chunk_overlap=5
|
|
)
|
|
src.add()
|
|
self.assertEqual(src.chunks, [])
|
|
|
|
def test_aadd_async(self):
|
|
storage = _FakeStorage()
|
|
self.src.storage = storage
|
|
asyncio.run(self.src.aadd())
|
|
self.assertGreater(len(storage.saved_chunks), 0)
|
|
|
|
def test_content_summary(self):
|
|
summary = self.src.get_content_summary()
|
|
self.assertEqual(summary["name"], "semantica_knowledge_graph")
|
|
self.assertGreater(summary["source_count"], 0)
|
|
self.assertTrue(summary["crewai_available"])
|
|
|
|
|
|
class TestSemanticaKnowledgeSourceSerialization(unittest.TestCase):
|
|
"""CrewAI checkpoints serialise their models via ``model_dump(mode="json")``
|
|
— the live graph must not break that (regression for
|
|
PydanticSerializationError on arbitrary state objects)."""
|
|
|
|
def test_model_dump_json_excludes_graph(self):
|
|
src = SemanticaKnowledgeSource(graph=_build_graph())
|
|
dumped = src.model_dump(mode="json")
|
|
self.assertNotIn("graph", dumped)
|
|
self.assertEqual(dumped["name"], "semantica_knowledge_graph")
|
|
|
|
def test_model_validate_restores_graph(self):
|
|
src = SemanticaKnowledgeSource(graph=_build_graph())
|
|
restored = SemanticaKnowledgeSource.model_validate(src.model_dump(mode="json"))
|
|
self.assertIsInstance(restored.graph, ContextGraph)
|
|
|
|
def test_restored_source_still_loads_content(self):
|
|
"""A checkpoint-restored source gets a fresh graph (the live graph is
|
|
excluded from serialisation); once a graph is attached it works."""
|
|
src = SemanticaKnowledgeSource(graph=_build_graph())
|
|
restored = SemanticaKnowledgeSource.model_validate(src.model_dump(mode="json"))
|
|
restored.graph = _build_graph()
|
|
self.assertNotEqual(restored.load_content(), {})
|
|
|
|
def test_restore_flags_lost_live_state(self):
|
|
"""A source restored from a checkpoint must signal that its live graph
|
|
was excluded and an empty one reconstructed (``reconstructed_state``).
|
|
Regression: an eager graph build in ``__init__`` used to hide this."""
|
|
src = SemanticaKnowledgeSource(graph=_build_graph())
|
|
dumped = src.model_dump(mode="json")
|
|
self.assertTrue(dumped["had_live_state"])
|
|
self.assertNotIn("reconstructed_state", dumped)
|
|
restored = SemanticaKnowledgeSource.model_validate(dumped)
|
|
self.assertTrue(restored.reconstructed_state)
|
|
self.assertFalse(SemanticaKnowledgeSource().reconstructed_state)
|
|
self.assertIsInstance(SemanticaKnowledgeSource().graph, ContextGraph)
|
|
|
|
|
|
class TestManualChunker(unittest.TestCase):
|
|
|
|
def test_short_text_single_chunk(self):
|
|
self.assertEqual(_chunk_text_manual("hello", 40, 5), ["hello"])
|
|
|
|
def test_empty_text(self):
|
|
self.assertEqual(_chunk_text_manual("", 40, 5), [])
|
|
|
|
def test_long_text_overlaps(self):
|
|
chunks = _chunk_text_manual("a" * 100, 40, 10)
|
|
self.assertGreater(len(chunks), 1)
|
|
self.assertTrue(all(len(c) <= 40 for c in chunks))
|
|
# Overlap means consecutive chunks share tail/head content
|
|
self.assertIn("a" * 10, chunks[0][-10:] + chunks[1][:10])
|
|
|
|
def test_zero_chunk_size_guarded(self):
|
|
self.assertEqual(_chunk_text_manual("hello world", 0, 5), ["hello world"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|