mirror of
https://github.com/semantica-agi/semantica.git
synced 2026-09-03 04:00:18 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
365391cb5b |
@@ -30,7 +30,8 @@ each file's own autogenerated header comment for its exact command).
|
||||
| `pep517-build.txt` | ci.yml, benchmark.yml, Dockerfile | exact `[build-system] requires` from `pyproject.toml` (setuptools, wheel) - installed with `--no-build-isolation` before any `pip install -e .` / `pip install .`, since `--no-deps` alone doesn't stop pip's PEP 517 build isolation from fetching those two *unhashed* |
|
||||
| `explorer-extra-py311.txt` | ci.yml | semantica's base deps + the `explorer` extra, resolved for python 3.11 |
|
||||
| `explorer-extra-py313.txt` | Dockerfile | the same, resolved for python 3.13 (the image's actual interpreter) |
|
||||
| `pytest-tool.txt` | ci.yml | pytest, for the pre-all-extras deterministic test |
|
||||
| `pgvector-extra.txt` | integration.yml | semantica's base deps + the `vectorstore-pgvector` extra, resolved for python 3.11 |
|
||||
| `pytest-tool.txt` | ci.yml, integration.yml | pytest, for the pre-all-extras deterministic test |
|
||||
| `uv-tool.txt` | ci.yml | uv, to verify requirements-ci.txt is current |
|
||||
| `build-tools.txt` | ci.yml, release.yml | build, wheel |
|
||||
| `twine.txt` | release.yml | twine |
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,91 @@
|
||||
name: Integration Tests
|
||||
|
||||
# Separate from ci.yml, which is a required check: a slow image pull or a
|
||||
# container flake must not block unrelated merges.
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
- 'docs/**'
|
||||
- 'docs_check.py'
|
||||
- '**/*.md'
|
||||
schedule:
|
||||
- cron: '0 5 * * 1'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
pgvector:
|
||||
name: pgvector (live PostgreSQL)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
|
||||
services:
|
||||
postgres:
|
||||
# pgvector/pgvector:pg16 as published 2026-08-13. Pinned by digest like
|
||||
# the action pins, though verify-action-pins.sh does not check images.
|
||||
image: pgvector/pgvector@sha256:ccc6e83d6e35e931dc7c5def2022729d5a6c370318d099181995567ff1fb4d6b
|
||||
env:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_DB: test
|
||||
# Throwaway container reachable only from this job, so trust auth
|
||||
# avoids putting a credential in the workflow at all.
|
||||
POSTGRES_HOST_AUTH_METHOD: trust
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U postgres -d test"
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 10
|
||||
|
||||
env:
|
||||
TEST_PGVECTOR_URL: postgresql://postgres@localhost:5432/test
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7
|
||||
with:
|
||||
python-version: '3.11'
|
||||
cache: 'pip'
|
||||
|
||||
- name: Install semantica with the pgvector extra
|
||||
# Hash-verified installs throughout, matching ci.yml/security.yml/etc
|
||||
# (OpenSSF Scorecard's Pinned-Dependencies check). --no-deps here
|
||||
# skips runtime dependency resolution for the editable install itself
|
||||
# (nothing to hash); pep517-build.txt + --no-build-isolation stops
|
||||
# its PEP 517 build from separately fetching an unhashed
|
||||
# setuptools/wheel via build isolation.
|
||||
run: |
|
||||
pip install -r .github/requirements/bootstrap.txt --require-hashes
|
||||
pip install -r .github/requirements/pep517-build.txt --require-hashes
|
||||
pip install --no-deps --no-build-isolation -e .
|
||||
pip install -r .github/requirements/pgvector-extra.txt --require-hashes
|
||||
pip install -r .github/requirements/pytest-tool.txt --require-hashes
|
||||
|
||||
- name: Create the vector extension
|
||||
# PgVectorStore._verify_pgvector_extension() requires it and refuses to
|
||||
# create it. Doubles as the connectivity gate.
|
||||
run: |
|
||||
python - <<'PY'
|
||||
import os
|
||||
|
||||
import psycopg
|
||||
|
||||
with psycopg.connect(os.environ["TEST_PGVECTOR_URL"]) as conn:
|
||||
conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
|
||||
conn.commit()
|
||||
print("vector extension ready")
|
||||
PY
|
||||
|
||||
- name: Run the live pgvector suite
|
||||
# pg_available raises rather than skipping when TEST_PGVECTOR_URL was
|
||||
# set explicitly (which this job always does), so a service that's
|
||||
# actually unreachable fails this step instead of the suite quietly
|
||||
# reporting green having run nothing.
|
||||
run: |
|
||||
pytest tests/vector_store/test_pgvector_store.py -v -rs
|
||||
@@ -11,14 +11,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Added
|
||||
|
||||
- **Salesforce ingestor** (#1240) by @Sameer6305
|
||||
- New `SalesforceConnector` / `SalesforceData` / `SalesforceIngestor` (`semantica.ingest`, lazy export), following the same Connector + Data + Ingestor pattern already used for Snowflake/Databricks/SAP
|
||||
- Auth covers both landscapes Salesforce actually uses: username + password + security token (SOAP login), session_id + instance_url (reusing an existing session), and username + consumer_key + private key (JWT Bearer); production and sandbox are selected via `domain`, and credentials can come from environment variables. Credential material is never intentionally written to logs, exceptions, or `repr()`
|
||||
- `ingest_sobject()`, `ingest_query()`, `list_sobjects()`, `get_sobject_schema()`, `export_as_documents()` against standard sObjects, custom objects (`__c`), custom metadata (`__mdt`), platform events (`__e`), namespaced objects, and relationship-field traversal (e.g. `Owner.Name`); pagination follows `nextRecordsUrl`/`query_more()` and stops once a caller's `limit` is satisfied
|
||||
- New `pip install semantica[db-salesforce]` extra (`simple-salesforce>=1.12.0`)
|
||||
- New `tests/test_salesforce_ingestor.py`
|
||||
- Docs: `docs/integrations/salesforce.md`
|
||||
|
||||
- **`ErasureCoordinator` completes the erasure workflow `purge_node()` only starts — the graph node was removed while the same content survived verbatim in `AgentMemory` and as an embedding** (closes #1018) by @pravit-amp
|
||||
- New `semantica/context/erasure.py`, exporting `ErasureCoordinator` and `ErasureReceipt` from `semantica.context`. `purge_node()`/`purge_edge()` (#957) are graph-scope by design and their changelog entry documents this gap explicitly; the changelog also names GDPR Article 17 as the motivation, and an Article 17 erasure that removes the node while the content stays retrievable by similarity search is not an erasure — it is worse than not offering one, because `purge_node()` returns `True` and writes a tombstone attesting the content is gone
|
||||
- The coordinator **composes** the existing public APIs — nothing in `context_graph.py` or `agent_memory.py` changes behaviorally, and `ContextGraph` keeps its documented graph-scope contract rather than acquiring references to `AgentMemory`/`vector_store` that would invert the dependency
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
**Context Management · Knowledge Modeling · Deterministic Reasoning · Ontology Management · Decision Intelligence · End-to-End Traceability**
|
||||
|
||||
**Open Source · Governed · Zero Vendor Lock-In**
|
||||
**Open Source · Self-Hostable · Auditable · Governed · Zero Vendor Lock-In**
|
||||
|
||||
**Polyglot Graph Storage · RDF & LPG Support · W3C Standards · Interoperable**
|
||||
|
||||
@@ -62,12 +62,12 @@ Most AI agents run on embeddings, not meaning: similarity scores with no structu
|
||||
|
||||
**Who it's for:**
|
||||
|
||||
- **AI/ML platform teams** shipping agents that make consequential decisions and need structured, queryable context, not just a vector index
|
||||
- **Data platform teams on Databricks or Snowflake** turning tables already in Unity Catalog or a warehouse into a governed, lineage-tracked knowledge graph, without exporting to a third-party SaaS
|
||||
- **Compliance, risk, and audit teams** who need a straight answer to "why did the AI do that?" in a format a regulator accepts
|
||||
- **Regulated enterprises** (finance, healthcare, legal, government, defense) that can't ship a black box or send their data to someone else's SaaS to get one
|
||||
- **AI/ML platform teams** shipping agents that make consequential decisions and need structured, queryable context built from fragmented raw data, not just a vector index
|
||||
- **Data platform teams on Databricks or Snowflake** who need to turn tables already sitting in Unity Catalog or a Snowflake warehouse into a governed, lineage-tracked knowledge graph, without exporting that data to a third-party SaaS first
|
||||
- **Compliance, risk, and audit teams** who need a straight answer to "why did the AI do that?" in a format a regulator will actually accept
|
||||
- **Regulated enterprises** (finance, healthcare, legal, government, defense) that can't ship a black box, and can't send their data to someone else's SaaS to get one
|
||||
- **Platform and infra engineers** who want the KG, reasoning, and provenance stack self-hosted and swappable, not locked to one vendor's backend
|
||||
- **Data and knowledge engineers** building a KG from messy, multi-source data, where conflicting facts get flagged and duplicates get merged, not silently overwritten
|
||||
- **Data and knowledge engineers** building a KG from messy, multi-source data: entities and relationships get extracted, conflicting or contradictory facts are flagged instead of silently overwritten, and duplicates are merged before they turn into noise
|
||||
|
||||
**[Quick Start](#quick-start)** · **[Architecture](#architecture)** · **[What You Get](#what-semantica-gives-you)** · **[Why Semantica](#why-semantica)** · **[Decision Intelligence](#decision-intelligence)** · **[Context Graphs](#context-graphs)** · **[Recipe: Audit Trail](#recipe-audit-trail-for-a-regulated-decision)** · **[Module Reference](#module-reference)** · **[Integrations](#integrations)** · **[CLI](#cli)** · **[Performance](#performance)** · **[Install](#installation)**
|
||||
|
||||
@@ -81,7 +81,7 @@ Most AI agents run on embeddings, not meaning: similarity scores with no structu
|
||||
- **Full Auditability:** W3C PROV-O provenance on every fact, with audit trails exportable to JSON, CSV, or RDF
|
||||
- **Deterministic Reasoning:** Forward chaining, Rete network, Datalog, and SPARQL with fully explainable paths, not black boxes
|
||||
- **Knowledge Pipeline:** Multi-source ingestion, entity-aware chunking, NER/relation/event extraction, and knowledge graph construction, with semantic deduplication and provenance-preserving merges throughout
|
||||
- **Enterprise Data Platforms:** Native connectors for Databricks (Unity Catalog + Delta Lake, PAT/OAuth M2M auth, catalog/schema/table/lineage introspection), Snowflake (warehouse/database/schema, key-pair and OAuth auth), and SAP OData (Business Partners, Sales Orders, OAuth2/Basic auth), so data already living in your lakehouse or warehouse becomes graph nodes with provenance, not another export/import hop
|
||||
- **Enterprise Data Platforms:** Native connectors for Databricks (Unity Catalog + Delta Lake, PAT/OAuth M2M auth, catalog/schema/table/lineage introspection) and Snowflake (warehouse/database/schema, key-pair and OAuth auth), so tables already living in your lakehouse or warehouse become graph nodes with provenance, not another export/import hop
|
||||
- **Graph Analytics:** Centrality, community detection, link prediction, and shortest-path queries over the graph you just built
|
||||
- **Polyglot Graph Storage:** Native RDF (embedded Oxigraph, Blazegraph, Apache Jena, Eclipse RDF4J via SPARQL) and Labeled Property Graphs (Neo4j, FalkorDB, Apache AGE, AWS Neptune via Cypher), plus vector stores, all swappable without touching your code
|
||||
- **Visualization:** Explore any graph, ontology, or timeline in an interactive browser workbench
|
||||
@@ -139,6 +139,10 @@ compliant = graph.check_decision_rules({"category": "vendor_selection"}) # poli
|
||||
|
||||
```bash
|
||||
semantica doctor
|
||||
# Python 3.11.9 pass
|
||||
# semantica 0.6.7 pass
|
||||
# faiss vector store pass
|
||||
# Config file pass ~/.semantica/config.yaml
|
||||
```
|
||||
|
||||
**Running in a script or CI?** Progress bars are written only when stdout is an interactive terminal (or a Jupyter notebook), so piping and redirecting stay clean by default. Override with `SEMANTICA_DISABLE_PROGRESS=1` to silence progress everywhere, or `SEMANTICA_FORCE_PROGRESS=1` to keep it when stdout is redirected. `SEMANTICA_DISABLE_PROGRESS` takes precedence.
|
||||
@@ -163,7 +167,7 @@ Sources → Ingest → Parse → Normalize → Split → Extract → Conflict De
|
||||
→ Vector Store + Polyglot Graph Store (RDF & LPG) → Export / Visualize / REST · MCP · CLI
|
||||
```
|
||||
|
||||
- **Ingest:** files, web, databases, enterprise data platforms (Databricks, Snowflake, SAP), cloud (Google Drive, Elasticsearch), streams (Kafka, Kinesis), Git, email, MCP
|
||||
- **Ingest:** files, web, databases, enterprise data platforms (Databricks, Snowflake), cloud (Google Drive, Elasticsearch), streams (Kafka, Kinesis), Git, email, MCP
|
||||
- **Parse → Normalize → Split:** document parsing, text/entity/date normalization, GraphRAG-native entity-aware chunking
|
||||
- **Extract → Conflict Detection → Deduplication:** NER, relations, events, triplets; conflicting facts flagged and resolved before they merge
|
||||
- **Knowledge Graph:** `GraphBuilder` constructs the graph; bi-temporal facts and full graph analytics (centrality, communities, link prediction) run on top of it
|
||||
@@ -316,7 +320,7 @@ Every module below is independently importable, with working code samples verifi
|
||||
|
||||
| Module | What it does |
|
||||
| --- | --- |
|
||||
| [`semantica.ingest`](#semanticaingest-multi-source-ingestion) | Files, web, databases, APIs, streams, email, Git, Parquet, Databricks, Snowflake, SAP, MCP |
|
||||
| [`semantica.ingest`](#semanticaingest-multi-source-ingestion) | Files, web, databases, APIs, streams, email, Git, Parquet, Databricks, Snowflake, MCP |
|
||||
| [`semantica.semantic_extract`](#semanticasemantic_extract-ner-relations-events-triplets) | NER, relation extraction, event detection, triplet generation |
|
||||
| [`semantica.kg`](#semanticakg-knowledge-graph-construction--analysis) | Graph construction, centrality, communities, link prediction |
|
||||
| [`semantica.reasoning`](#semanticareasoning-forward-chaining-rete-datalog-sparql) | Forward chaining, Rete, Datalog, SPARQL, fully explainable |
|
||||
@@ -345,7 +349,7 @@ Expand any module below for its runnable example.
|
||||
<summary><b><code>semantica.ingest</code></b>: Multi-Source Ingestion</summary>
|
||||
<a id="semanticaingest-multi-source-ingestion"></a>
|
||||
|
||||
Ingest from files, web, databases, APIs, streams, email, Git repos, Parquet, Databricks, Snowflake, SAP, or MCP servers, all through a unified interface.
|
||||
Ingest from files, web, databases, APIs, streams, email, Git repos, Parquet, Databricks, Snowflake, or MCP servers, all through a unified interface.
|
||||
|
||||
```python
|
||||
from semantica.ingest import FileIngestor, WebIngestor, ParquetIngestor, DBIngestor
|
||||
@@ -396,7 +400,7 @@ orders = snowflake.ingest_table("ORDERS", limit=10_000)
|
||||
|
||||
> **Security Note:** Never hardcode credentials (`token`, `password`, `private_key`) in production code; pass them via environment variables (e.g., `DATABRICKS_TOKEN`, `SNOWFLAKE_PASSWORD`) or a secrets manager.
|
||||
|
||||
**Supported sources:** Local files (PDF, DOCX, PPTX, HTML, TXT, CSV, JSON, YAML, Excel, XML) · Web pages · RSS/Atom feeds · REST APIs · Databases (PostgreSQL, MySQL, SQLite, Oracle, SQL Server) · Parquet datasets · Databricks (Unity Catalog + Delta Lake) · Snowflake · SAP (OData v2/v4) · Git repositories · Email (IMAP/POP3) · Message streams (Kafka, RabbitMQ, Kinesis, Pulsar) · MCP resources · Apache Arrow/Feather/IPC (`ArrowIngestor`)
|
||||
**Supported sources:** Local files (PDF, DOCX, PPTX, HTML, TXT, CSV, JSON, YAML, Excel, XML) · Web pages · RSS/Atom feeds · REST APIs · Databases (PostgreSQL, MySQL, SQLite, Oracle, SQL Server) · Parquet datasets · Databricks (Unity Catalog + Delta Lake) · Snowflake · Git repositories · Email (IMAP/POP3) · Message streams (Kafka, RabbitMQ, Kinesis, Pulsar) · MCP resources · Apache Arrow/Feather/IPC (`ArrowIngestor`)
|
||||
|
||||
DuckDB, Elasticsearch, Google Drive, HuggingFace, MongoDB, and Pandas ingestion also ship (`DuckDBIngestor`, `ElasticIngestor`, `GDriveIngestor`, `HuggingFaceIngestor`, `MongoIngestor`, `PandasIngestor`) but aren't re-exported from the top-level `semantica.ingest` namespace yet — import them directly: `from semantica.ingest.duckdb_ingestor import DuckDBIngestor`.
|
||||
|
||||
@@ -1141,7 +1145,7 @@ if report.valid:
|
||||
| **Vector Store** | FAISS · Pinecone · Weaviate · Qdrant · Milvus · PgVector · hybrid + filtered search |
|
||||
| **Graph Databases (LPG)** | Neo4j · FalkorDB · Apache AGE · AWS Neptune |
|
||||
| **Triple Stores (RDF)** | Oxigraph (embedded) · Blazegraph · Apache Jena · Eclipse RDF4J · unified `TripletStore` interface · SPARQL query & bulk load |
|
||||
| **Enterprise Data Platforms** | Databricks (`DatabricksIngestor`: Unity Catalog + Delta Lake, PAT/OAuth M2M, table/query ingestion, catalog/schema/table/lineage introspection) · Snowflake (`SnowflakeIngestor`: warehouse/database/schema, password/key-pair/OAuth auth) · SAP (`SAPIngestor`: OData v2/v4, OAuth2/Basic auth, Business Partners/Sales Orders) |
|
||||
| **Enterprise Data Platforms** | Databricks (`DatabricksIngestor`: Unity Catalog + Delta Lake, PAT/OAuth M2M, table/query ingestion, catalog/schema/table/lineage introspection) · Snowflake (`SnowflakeIngestor`: warehouse/database/schema, password/key-pair/OAuth auth) |
|
||||
| **LLM Providers** | **All already supported today:** OpenAI (GPT-4o, o1, o3) · Anthropic (Claude) · Google Gemini · Mistral · Meta Llama · Groq · Cohere · Azure OpenAI · AWS Bedrock · Ollama · DeepSeek · Perplexity · Together AI · Fireworks AI · Replicate · HuggingFace · via `semantica.llms` and LiteLLM |
|
||||
|
||||
---
|
||||
@@ -1513,7 +1517,6 @@ pip install semantica[vectorstore-qdrant] # Qdrant vector store
|
||||
pip install semantica[vectorstore-pinecone] # Pinecone vector store
|
||||
pip install semantica[db-snowflake] # Snowflake
|
||||
pip install semantica[db-databricks] # Databricks (SDK + SQL connector)
|
||||
pip install semantica[ingest-sap] # SAP OData
|
||||
pip install semantica[ingest-parquet] # Parquet / PyArrow
|
||||
pip install semantica[ingest-arrow] # Apache Arrow, Feather, IPC
|
||||
pip install semantica[viz] # HTML interactive visualization
|
||||
|
||||
+46
-203
@@ -1,221 +1,64 @@
|
||||
---
|
||||
title: "Evals Module"
|
||||
description: "Score decision records, audit trails, and reasoning output with deterministic and model-backed evaluators plus a small run harness."
|
||||
description: "Evaluation framework for measuring Knowledge Graph quality, extraction accuracy, and pipeline performance: coming soon."
|
||||
icon: "chart-line"
|
||||
---
|
||||
|
||||
`semantica.evals` measures the quality of decision intelligence outputs. It takes
|
||||
the decisions, audit trails, and reasoning text your pipeline produces and scores
|
||||
them against expectations you define, returning a structured summary you can log,
|
||||
assert on in tests, or track across runs.
|
||||
**`semantica.evals`** is planned as a comprehensive evaluation framework for measuring **extraction accuracy, graph quality, and pipeline performance**.
|
||||
|
||||
- A registry of named evaluators, from exact string matching to ROUGE overlap and
|
||||
LLM-as-judge
|
||||
- `decision_scores`, a composite evaluator for `Decision` objects that checks
|
||||
outcome, confidence bounds, required fields, provenance, and (optionally)
|
||||
policy compliance
|
||||
- A `evaluate()` runner that applies several evaluators to a list of cases and
|
||||
aggregates pass / fail / error counts
|
||||
- Per-evaluator **objectives** that let you override an evaluator's built-in
|
||||
verdict at the run level
|
||||
<Warning>
|
||||
**`semantica.evals` is not yet implemented.** The module is a placeholder with `__all__ = []`. No classes or functions are available for import. This page describes the planned API only.
|
||||
</Warning>
|
||||
|
||||
<Note>
|
||||
The module is versioned separately from the package: `semantica.evals.__version__`
|
||||
is `"0.1.0"`. The public surface described here is stable, but expect additive
|
||||
changes (new evaluators, new objective options) before it reaches 1.0.
|
||||
</Note>
|
||||
## Planned Features
|
||||
|
||||
## Public API
|
||||
When released, `semantica.evals` will provide:
|
||||
|
||||
| Name | Kind | Role |
|
||||
| :--- | :--- | :--- |
|
||||
| `evaluate(cases, evaluators, config=None, target_fn=None)` | function | Run named evaluators over each case, return an `EvalSummary` |
|
||||
| `list_evaluators()` | function | Sorted names of every registered evaluator |
|
||||
| `get_evaluator(name)` | function | Look up a single evaluator function by name |
|
||||
| `EvalMetric` | dataclass (frozen) | One evaluator's result: `score`, `passed`, `meta` |
|
||||
| `CaseResult` | namedtuple | One case's result: `case_id`, `status`, `metrics`, `details` |
|
||||
| `EvalSummary` | dataclass | Aggregate across cases: `total`, `passed`, `failed`, `errors`, `pass_rate`, `cases` |
|
||||
|
||||
```python
|
||||
import semantica.evals as evals
|
||||
from semantica.evals import evaluate, list_evaluators, get_evaluator
|
||||
```
|
||||
|
||||
## Built-in evaluators
|
||||
|
||||
Every evaluator is a plain function `fn(actual, expected, config=None) -> EvalMetric`
|
||||
registered under a stable name. `list_evaluators()` returns the current set:
|
||||
|
||||
```python
|
||||
>>> list_evaluators()
|
||||
['decision_scores', 'exact_match', 'keyword_check', 'length_range',
|
||||
'levenshtein', 'llm_as_judge', 'numeric_range', 'regex_match', 'rouge',
|
||||
'temporal_range']
|
||||
```
|
||||
|
||||
| Name | Passes when | Relevant `config` keys |
|
||||
| :--- | :--- | :--- |
|
||||
| `exact_match` | `actual == expected` | none |
|
||||
| `regex_match` | `re.search(expected, actual)` matches | none |
|
||||
| `keyword_check` | every required term appears in `actual` (word-boundary) | `required` (falls back to `expected`) |
|
||||
| `numeric_range` | `min <= actual <= max` | `min`, `max` (both required) |
|
||||
| `temporal_range` | ISO datetime `actual` falls in `[min, max]` | `min`, `max` as ISO strings (both required) |
|
||||
| `length_range` | `min <= len(actual) <= max` | `min` (default 0), `max` (required) |
|
||||
| `levenshtein` | normalized similarity `>= threshold` | `threshold` (default 0.8) |
|
||||
| `rouge` | ROUGE-1 F1 `> 0` and `>= threshold` | `threshold` (default 0.0) |
|
||||
| `llm_as_judge` | caller-supplied `judge_fn(actual, expected)` returns truthy | `judge_fn` (required callable) |
|
||||
| `decision_scores` | all configured sub-checks on a `Decision` pass | see below |
|
||||
|
||||
An evaluator that cannot run (bad regex, missing bound, no `judge_fn`) returns an
|
||||
`EvalMetric` with an `"error"` key in `meta` rather than raising.
|
||||
|
||||
### `decision_scores`
|
||||
|
||||
`decision_scores` accepts a `Decision` (from `semantica.context.decision_models`)
|
||||
or its dict form and runs a set of field-level and governance checks. The score is
|
||||
the fraction of checks that passed; `passed` is `True` only when all of them did.
|
||||
|
||||
| Sub-check | Controlled by |
|
||||
| Planned Class | Role |
|
||||
| :--- | :--- |
|
||||
| Outcome matches | `expected_outcome` in config, or the case's `expected` |
|
||||
| Confidence in range | `min_confidence` (default 0.0), `max_confidence` (default 1.0) |
|
||||
| `decision_maker`, `reasoning`, `scenario` non-empty | always run |
|
||||
| Provenance present in metadata | `provenance_key` (default `"provenance"`) |
|
||||
| Policy compliance | `policy_engine` and `policy_id` both set; skipped otherwise |
|
||||
| `KGEvaluator` | Completeness, consistency, schema compliance, coverage, and orphan node detection |
|
||||
| `ExtractionEvaluator` | NER precision / recall / F1 and relation extraction metrics against gold datasets |
|
||||
| `PipelineBenchmark` | Throughput (docs/sec), per-step latency, peak memory, and error rate |
|
||||
| `RegressionTracker` | Record runs and compare metrics across commits or config changes |
|
||||
| `EvalReport` | Structured report: `{scores, regressions, recommendations}` |
|
||||
| `DeduplicationEvaluator` | Merge precision, false positive / false negative rates |
|
||||
| `ReasoningEvaluator` | Inference accuracy, rule coverage, and derivation depth |
|
||||
|
||||
Passing `causal_chain_exists` in config raises `NotImplementedError`. That key is a
|
||||
reserved slot for a future release.
|
||||
## Current Workaround
|
||||
|
||||
## Running an evaluation
|
||||
|
||||
`evaluate()` takes a list of cases and a list of evaluator names. A case is either
|
||||
a `(expected, actual)` tuple or a dict:
|
||||
Until `semantica.evals` ships, use `semantica.ontology.OntologyEvaluator` for ontology quality metrics:
|
||||
|
||||
```python
|
||||
{
|
||||
"id": "loan-001", # optional, generated if absent
|
||||
"expected": ..., # optional; some evaluators read it, some don't
|
||||
"actual": ..., # the value under test
|
||||
"config": {...}, # optional, per-evaluator settings for this case
|
||||
"target_fn": callable, # optional, called with the case to produce `actual`
|
||||
}
|
||||
from semantica.ontology import OntologyEvaluator
|
||||
|
||||
evaluator = OntologyEvaluator()
|
||||
|
||||
# evaluate_ontology takes the ontology dict only
|
||||
result = evaluator.evaluate_ontology(ontology)
|
||||
|
||||
print("Coverage: ", result.coverage_score)
|
||||
print("Completeness:", result.completeness_score)
|
||||
print("Gaps: ", result.gaps)
|
||||
print("Suggestions: ", result.suggestions)
|
||||
|
||||
# Full report with class granularity and relation completeness
|
||||
report = evaluator.generate_report(ontology)
|
||||
print("Coverage score: ", report["evaluation"]["coverage_score"])
|
||||
print("Completeness score:", report["evaluation"]["completeness_score"])
|
||||
print("Relation coverage: ", report["relation_completeness"]["relation_coverage"])
|
||||
```
|
||||
|
||||
If `actual` is missing, the runner calls the case's `target_fn` (or the
|
||||
`target_fn` passed to `evaluate()`) to produce it. Per-case `config` is deep-merged
|
||||
over the top-level `config`, so a case can override one evaluator's settings
|
||||
without discarding the rest.
|
||||
`EvaluationResult` fields returned by `evaluate_ontology()`:
|
||||
|
||||
```python
|
||||
from datetime import datetime
|
||||
| Field | Type | Description |
|
||||
| :----- | :---- | :----------- |
|
||||
| `coverage_score` | `float` | Fraction of competency questions answerable by the ontology |
|
||||
| `completeness_score` | `float` | Average of class and property completeness scores |
|
||||
| `gaps` | `List[str]` | Identified gaps in coverage |
|
||||
| `suggestions` | `List[str]` | Improvement suggestions |
|
||||
| `metrics` | `dict` | Detailed sub-metrics |
|
||||
|
||||
from semantica.context.decision_models import Decision
|
||||
from semantica.evals import evaluate
|
||||
|
||||
decision = Decision(
|
||||
decision_id="d-1",
|
||||
category="loan",
|
||||
scenario="loan-request",
|
||||
reasoning="vetted against lending policy v3",
|
||||
outcome="approve",
|
||||
confidence=0.87,
|
||||
timestamp=datetime.now(),
|
||||
decision_maker="approver-a",
|
||||
metadata={"provenance": "workflow:loan/v3"},
|
||||
)
|
||||
|
||||
cases = [
|
||||
{
|
||||
"id": "loan-001",
|
||||
"actual": decision,
|
||||
"config": {
|
||||
"decision_scores": {
|
||||
"expected_outcome": "approve",
|
||||
"min_confidence": 0.7,
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
summary = evaluate(cases, ["decision_scores"])
|
||||
print(summary.pass_rate) # 1.0
|
||||
```
|
||||
|
||||
Evaluators run independently per case. If one raises, that case's `status` becomes
|
||||
`"error"` and the exception text is captured in the metric's `meta`; the rest of
|
||||
the run continues.
|
||||
|
||||
## Objectives
|
||||
|
||||
By default each evaluator decides its own pass / fail. An **objective** overrides
|
||||
that verdict at the run level, keyed by evaluator name under `config`:
|
||||
|
||||
```python
|
||||
# Raise levenshtein's bar from its default 0.8 to 0.9
|
||||
evaluate(
|
||||
[("apple", "aple")],
|
||||
evaluators=["levenshtein"],
|
||||
config={"levenshtein": {"objective": {"direction": "maximize", "threshold": 0.9}}},
|
||||
)
|
||||
|
||||
# Lower is better
|
||||
evaluate(
|
||||
[("night", "nacht")],
|
||||
evaluators=["levenshtein"],
|
||||
config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.5}}},
|
||||
)
|
||||
|
||||
# Expect the metric NOT to match
|
||||
evaluate(
|
||||
[("ok", "ok")],
|
||||
evaluators=["exact_match"],
|
||||
config={"exact_match": {"objective": {"expect": False}}},
|
||||
)
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `maximize` with `threshold`: pass iff `score >= threshold`. `maximize` with no
|
||||
threshold is a no-op and the evaluator's own verdict stands.
|
||||
- `minimize` with `threshold`: pass iff `score <= threshold`. `minimize`
|
||||
**requires** a threshold; omitting it raises `ValueError`.
|
||||
- `expect` (`True` / `False`): pass iff `bool(score)` equals it. Cannot be combined
|
||||
with `direction` or `threshold`, and must be a real boolean.
|
||||
- A metric that already carries an `"error"` in its `meta` is unaffected by any
|
||||
objective.
|
||||
- Invalid objective config is validated for every case before any evaluator runs,
|
||||
so a bad objective fails the whole run up front rather than partway through.
|
||||
|
||||
## Reading the summary
|
||||
|
||||
```python
|
||||
summary = evaluate(cases, ["decision_scores"])
|
||||
|
||||
summary.total, summary.passed, summary.failed, summary.errors
|
||||
summary.pass_rate # passed / total, or 1.0 for an empty case list
|
||||
|
||||
for case in summary.cases:
|
||||
print(case.case_id, case.status) # status: "pass" | "fail" | "error"
|
||||
for name, metric in case.metrics.items():
|
||||
print(name, metric.score, metric.passed)
|
||||
print(metric.meta.get("reasons", {})) # per-sub-check failure reasons
|
||||
```
|
||||
|
||||
`EvalMetric` is frozen (`score: float`, `passed: bool`, `meta: dict`). `CaseResult`
|
||||
is a namedtuple, and `EvalSummary` is a plain dataclass, so all three are
|
||||
straightforward to serialize for logging or regression tracking.
|
||||
|
||||
## Notes
|
||||
|
||||
- `llm_as_judge` needs `config["judge_fn"]`, a callable
|
||||
`judge_fn(actual, expected) -> bool` you supply. No LLM backend is imported
|
||||
unless you pass one in.
|
||||
- `decision_scores` governance checks are opt-in: policy compliance is only
|
||||
evaluated when both `policy_engine` and `policy_id` are present.
|
||||
|
||||
## See also
|
||||
|
||||
- [Decision Intelligence](../guides/decision-intelligence) — producing the `Decision` records this module scores
|
||||
- [Reasoning](reasoning) — inference output that reasoning-text evaluators can measure
|
||||
- [Policy Engine](../guides/policy-engine) — the `policy_engine` used by `decision_scores`
|
||||
- [Ontology Evaluator](ontology) — separate tooling for ontology quality metrics
|
||||
- [Semantic Extract](semantic_extract) — Extraction module.
|
||||
- [Knowledge Graph](kg) — Graph quality assessment.
|
||||
- [Pipeline](pipeline) — Pipeline performance metrics.
|
||||
- [Ontology Evaluator](ontology) — Available now for ontology quality metrics.
|
||||
|
||||
@@ -10,7 +10,7 @@ To run these tests locally with Docker:
|
||||
-e POSTGRES_PASSWORD=postgres \
|
||||
-e POSTGRES_DB=test \
|
||||
-p 5432:5432 \
|
||||
ankane/pgvector:latest
|
||||
pgvector/pgvector:pg16
|
||||
|
||||
pytest tests/vector_store/test_pgvector_store.py -v
|
||||
|
||||
@@ -63,29 +63,37 @@ TEST_CONNECTION_STRING = os.getenv(
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def pg_available() -> bool:
|
||||
"""Check if PostgreSQL with pgvector is available."""
|
||||
"""Check if PostgreSQL with pgvector is available.
|
||||
|
||||
A connection failure only means "skip" when TEST_PGVECTOR_URL wasn't set
|
||||
explicitly, i.e. this is a local run falling back to the documented
|
||||
default. CI sets it on purpose, so a failure there means the service is
|
||||
genuinely broken and the suite should fail loudly instead of skipping.
|
||||
"""
|
||||
if not psycopg_available:
|
||||
return False
|
||||
|
||||
explicit_url = "TEST_PGVECTOR_URL" in os.environ
|
||||
|
||||
try:
|
||||
if psycopg_available:
|
||||
try:
|
||||
import psycopg
|
||||
try:
|
||||
import psycopg
|
||||
|
||||
conn = psycopg.connect(TEST_CONNECTION_STRING, connect_timeout=5)
|
||||
except ImportError:
|
||||
import psycopg2
|
||||
conn = psycopg.connect(TEST_CONNECTION_STRING, connect_timeout=5)
|
||||
except ImportError:
|
||||
import psycopg2
|
||||
|
||||
conn = psycopg2.connect(TEST_CONNECTION_STRING, connect_timeout=5)
|
||||
conn = psycopg2.connect(TEST_CONNECTION_STRING, connect_timeout=5)
|
||||
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT 1")
|
||||
cur.close()
|
||||
conn.close()
|
||||
return True
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT 1")
|
||||
cur.close()
|
||||
conn.close()
|
||||
return True
|
||||
except Exception:
|
||||
if explicit_url:
|
||||
raise
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -191,7 +199,13 @@ class TestPgVectorStoreAdd:
|
||||
ids = store.add(vectors, metadata)
|
||||
|
||||
assert len(ids) == 5
|
||||
assert all(id.startswith("vec_") for id in ids)
|
||||
assert len(set(ids)) == 5
|
||||
# add() assigns uuid4 identifiers, not a "vec_" prefix
|
||||
for vector_id in ids:
|
||||
try:
|
||||
uuid.UUID(vector_id)
|
||||
except ValueError:
|
||||
pytest.fail(f"{vector_id!r} is not a valid uuid4 id")
|
||||
|
||||
def test_add_auto_generate_ids(self, store):
|
||||
"""Test that IDs are auto-generated if not provided."""
|
||||
@@ -290,38 +304,40 @@ class TestPgVectorStoreSearch:
|
||||
if not pg_available:
|
||||
pytest.skip("PostgreSQL not available")
|
||||
|
||||
from semantica.vector_store.pgvector_store import PgVectorStore
|
||||
from semantica.vector_store.pgvector_store import PgVectorStore, psycopg_sql
|
||||
|
||||
# setup_vectors is autouse and seeds unique_table_name, and fixtures are
|
||||
# cached per test, so this needs a table of its own to be empty at all.
|
||||
empty_table = f"{unique_table_name}_empty"
|
||||
empty_store = PgVectorStore(
|
||||
connection_string=TEST_CONNECTION_STRING,
|
||||
table_name=unique_table_name,
|
||||
table_name=empty_table,
|
||||
dimension=128,
|
||||
distance_metric="cosine",
|
||||
)
|
||||
|
||||
query = np.random.rand(128).astype(np.float32)
|
||||
results = empty_store.search(query, top_k=5)
|
||||
|
||||
assert len(results) == 0
|
||||
|
||||
# Cleanup: Drop test table after test completes
|
||||
# Uses best-effort cleanup - failures are silently ignored since
|
||||
# this is teardown of optional test resources
|
||||
try:
|
||||
with empty_store._get_connection() as conn:
|
||||
cur = conn.cursor()
|
||||
from semantica.vector_store.pgvector_store import psycopg_sql
|
||||
drop_sql = psycopg_sql.SQL("DROP TABLE IF EXISTS {}").format(
|
||||
psycopg_sql.Identifier(unique_table_name)
|
||||
)
|
||||
cur.execute(drop_sql)
|
||||
conn.commit()
|
||||
cur.close()
|
||||
empty_store.close()
|
||||
except Exception:
|
||||
# Best-effort cleanup: PostgreSQL may be unavailable during teardown
|
||||
# This is expected when tests are skipped or connection is lost
|
||||
pass
|
||||
query = np.random.rand(128).astype(np.float32)
|
||||
results = empty_store.search(query, top_k=5)
|
||||
|
||||
assert len(results) == 0
|
||||
finally:
|
||||
try:
|
||||
with empty_store._get_connection() as conn:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
psycopg_sql.SQL("DROP TABLE IF EXISTS {}").format(
|
||||
psycopg_sql.Identifier(empty_table)
|
||||
)
|
||||
)
|
||||
conn.commit()
|
||||
cur.close()
|
||||
empty_store.close()
|
||||
except Exception:
|
||||
# Best-effort cleanup: PostgreSQL may be unavailable during
|
||||
# teardown. This is expected when tests are skipped or the
|
||||
# connection is lost.
|
||||
pass
|
||||
|
||||
|
||||
class TestPgVectorStoreGet:
|
||||
|
||||
Reference in New Issue
Block a user