Metadata-Version: 2.4
Name: prometheux_chain
Version: 0.4.10
Summary: Prometheux Chain is a Python SDK to build, evolve and deploy your ontologies.
Home-page: https://github.com/prometheuxresearch/prometheux-chain
Author: Prometheux Limited
Author-email: davben@prometheux.co.uk
License: BSD-3-Clause
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: License :: OSI Approved :: BSD License
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests
Requires-Dist: pyyaml
Requires-Dist: websocket-client
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license
Dynamic: license-file
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# Prometheux Chain

## Description
Prometheux Chain is a Python SDK designed to help you create, evolve, and deploy ontologies with ease. The SDK offers the following capabilities:

- Data Ingestion: Seamlessly integrate data from various sources, including databases and files.
- Reasoning & Knowledge Augmentation: Perform logical reasoning to derive new insights and augment your existing knowledge base.
- Explainability: Gain clear explanations of the results generated by the system.

For more information refer to the [documentation](https://docs.prometheux.ai/integrations/python-sdk)

## Features
- Supports a wide range of data sources.
- Built-in reasoning engine for deriving new knowledge.
- Easy-to-understand explanations for enhanced interpretability.
- Ready-to-use configurations for fast deployment.

## Installation

### Requirements
- Python 3.9 or higher (Python 3.13 recommended)

### Install Using pip

1. Set Up a Virtual Environment (recommended):

```bash
python3 -m venv myenv
source myenv/bin/activate  # On Windows: myenv\Scripts\activate
```

2. Install the SDK via pip:

```
pip install --upgrade prometheux-chain
```

## Usage

This guide demonstrates how to get started with the Prometheux Chain SDK. The example below outlines a typical workflow, including creating an ontology, defining concept logic, and running concepts to generate results.

### Workflow

#### Import the `prometheux_chain`
```python
import prometheux_chain as px
import os
```

#### Define the PMTX_TOKEN environment variable for authentication
```python
os.environ['PMTX_TOKEN'] = 'my_pmtx_token'
```

#### Configure the backend connection using your Prometheux account
```python
px.config.set('JARVISPY_URL', "https://platform.prometheux.ai/jarvispy/'my_organization'/'my_username'")
```

#### Create a new ontology
```python
ontology_id = px.save_ontology(ontology_name="test_ontology")
```

#### Define concept logic using Vadalog syntax and save it
```python
definition = """
company("Apple", "Redwood City, CA").
company("Google", "Mountain View, CA").
company("Microsoft", "Redmond, WA").
company("Amazon", "Seattle, WA").
company("Facebook", "Menlo Park, CA").
company("Twitter", "San Francisco, CA").
company("LinkedIn", "Sunnyvale, CA").
company("Instagram", "Menlo Park, CA").

location(Location) :- company(_,Location).

@output("location").
"""
px.save_concept(ontology_id=ontology_id, definition=definition)
```

#### Run the concept to generate results
```python
px.run_concept(ontology_id=ontology_id, concept_name="location")
```

#### Fetch the produced facts
```python
results = px.fetch_results(ontology_id=ontology_id, output_predicate="location")
```

---

## Domains

The SDK exposes a flat, function-based API (`import prometheux_chain as px`)
covering the user-facing JarvisPy backend:

- **Ontologies** — `save_ontology`, `list_ontologies`, `load_ontology`, `copy_ontology`,
  `export_ontology` / `import_ontology`, `export_workspace` / `import_workspace`,
  `list_templates`, `import_template`, `create_ontology_from_context`,
  `create_snapshot`, `list_snapshots`, `restore_snapshot`, `delete_snapshot`.
- **Data sources** — `connect_sources`, `list_sources`, `infer_schema`,
  `list_sheets`, `list_demo_sources`, `refresh_sources`, `preview_datasource`,
  `all_pairs_join`, `cleanup_sources`.
- **Files (disk/)** — `upload_file`, `list_files`, `make_directory`,
  `delete_files`, `move_file`, `download_file`.
- **Concepts** — `save_concept`, `rename_concept`, `run_concept`,
  `run_concept_stream`, `list_concepts`, `reorder_concepts`, `fetch_results`,
  `search_results`, `query_concept`, `search_similar_concepts`, `llm_analysis`,
  `download_concept`, `generate_concept_description`, `get_concept_description`,
  `get_execution_status`, `get_execution_statuses`, `cleanup_concepts`.
- **Knowledge graphs** — `visualize_concept_lineage`, `build_graph`,
  `list_graph_functions`, `run_graph_analytics`.
- **Ontology schema** — `save_ontology_schema`, `load_ontology_schema`,
  `update_concept_ontology_schema_type`, `add_to_lineage`, `import_owl`.
- **Knowledge / context layer** — `list_context_notes`, `create_context_note`,
  `create_context_notes_from_file`, `get_context_note`, `update_context_note`,
  `create_context_edge`, `delete_context_note`, `search_context_notes`,
  `auto_seed`, `interview_template`, `submit_interview`, `onboarding_status`,
  `ontology_text`.
- **Agent** — `agent_chat` (streaming), `agent_reset`.
- **Assistant** — `list_skills`, `get_skill`, `get_company_info`.
- **Sharing** — `create_share`, `revoke_share`, `update_share_role`,
  `list_shares`, `list_inbox`, `accept_share`, `leave_share`, `sync_inbox`.
- **Apps** — `list_all_apps`, `list_apps`, `get_app`,
  `save_app`, `delete_app`, `publish_app`, `unpublish_app`.
- **Schedules** — `create_policy`, `list_policies`, `get_policy`,
  `update_policy`, `delete_policy`, `trigger_policy`, `get_run_history`.
- **Alerts** — `get_alert_history`, `reprocess_alert`.
- **Chat history** — `list_sessions`, `get_session`, `rename_session`,
  `delete_session`.
- **Compute** — `check_compute_availability`, `list_machines_combined`,
  `set_machine_active`, `get_machine_status`, `use_machine`,
  `delete_user_machine`.
- **Users / account** — `save_user_config`, `load_user_config`, `get_role`,
  `list_llm_models`, `get_usage_status`, `get_login_activity`.
- **Auth / tokens** — `issue_token`, `list_tokens`, `revoke_token`,
  `revoke_specific_token`, `revoke_all_tokens`.
- **Vadalog authoring** — `analyze_program`, `build_bind`, `parse_binds`,
  `evaluate_program`, `generate_program`, `validate_concept`.
- **Vadalog checks** — `check_program`, `check_question`, `compare_rows`,
  `read_expected_csv` (see [Testing Vadalog programs](#testing-vadalog-programs)).
- **Engine workers** — `engine_workers`, `set_engine_workers`,
  `get_engine_workers`, `wait_for_engine_workers`.
- **Vadalingo translation** — `translate_sql_to_vadalog`,
  `translate_rdf_to_vadalog`, `translate_owl_to_vadalog`.

### Optional configuration

Some recipient-side sharing flows require a Supabase token. Set it via the
`SUPABASE_TOKEN` environment variable (or `px.config`) and it is attached
automatically as the `X-Supabase-Token` header when present.

## Streaming

A few endpoints stream results instead of returning a single response. These
return Python generators you iterate over.

#### Chat with the Vadalog AI agent (NDJSON stream)
```python
for event in px.agent_chat(ontology_id=ontology_id, message="What does this ontology do?"):
    if event.get("type") == "content":
        print(event["data"]["chunk"], end="")
```

#### Run a concept with live status updates (WebSocket stream)
WebSocket streaming requires the `websocket-client` dependency (installed
automatically with the SDK).
```python
for event in px.run_concept_stream(ontology_id=ontology_id, concept_name="location"):
    print(event.get("event"), event.get("data"))
    # iteration ends after the terminal "complete" or "error" event
```

#### Auto-seed the context layer from connected data sources (NDJSON stream)
```python
for event in px.auto_seed(scope="project", scope_id=ontology_id):
    print(event)
```

## Testing Vadalog programs

`check_program` evaluates a program on the platform engine and compares each
output predicate with the rows you expect, given as a CSV file (one row per
line, no header unless `header=True`) or as a list of rows. Numbers compare
equal however they were serialized, so `2`, `"2"` and `2.0` match.

```python
report = px.check_program(open("tc.vada").read(), expect={"tc": "tc.csv"})
print(report.summary())
report.assert_ok()   # raises AssertionError with the summary when a check fails
```

`mode="exact"` (the default) passes when the rows are the same and so is their
count; `mode="contains"` passes when every expected row was produced. The
report never raises on its own: an engine error or a predicate the program did
not produce is a failed report, so it drops straight into pytest:

```python
def test_transitive_closure():
    px.check_program(open("tc.vada").read(), expect={"tc": [[1, 2], [2, 3], [1, 3]]}).assert_ok()
```

`check_question` asks the natural-language translator for the program first,
then checks it the same way. Given a single CSV, it checks the generated
program's last `@output` predicate unless you name one with `expect_predicate`.
`report.program` holds the generated program. Each call counts as one program
generation in your usage.

```python
report = px.check_question("Transitive closure of edge(X,Y). Output as tc.",
                           expect="tc.csv", mode="contains")
```

The `px test` command of the [Prometheux CLI](https://github.com/prometheuxresearch/prometheux-cli)
runs the same checks from the shell and over a folder of test cases.

### Running a suite faster with engine workers

Engine workers are in preview and enabled on selected workspaces only; elsewhere
these calls raise "Engine workers are not available on this platform".

With a compute machine running, `engine_workers(n)` adds `n` engine-only
replicas beside it for the duration of a `with` block. Program evaluations sent
at the same time are spread across the machine and its workers, so a suite run
with parallel callers (threads, or `pytest -n` from `pytest-xdist`) finishes
sooner: 20 two-second cases took 7.5 s with six callers on a 4-core machine
alone, and 5.1 s with two warm workers. Each worker is another node of the
machine's size, billed at the machine's hourly rate until it is removed, and
takes up to a few minutes to start; its first programs run slower while the
engine warms up, so workers pay off on suites that take minutes. The block
waits until all are ready and removes them when it ends, even if a test raised.
Workers nobody sends a program to for ten minutes are removed automatically.

```python
from concurrent.futures import ThreadPoolExecutor

with px.engine_workers(2):
    with ThreadPoolExecutor(6) as pool:
        reports = list(pool.map(lambda case: px.check_program(case.program, expect=case.expect),
                                cases))
```

`set_engine_workers(n)` and `get_engine_workers()` do the same without the
block; `get_engine_workers()["engines"]` shows how many programs each engine
has run.

## Tokens

Issue and manage API tokens programmatically:
```python
token = px.issue_token(name="ci-bot", expires_in_minutes=60)
print(token["token"])   # the raw JWT — shown only once
px.list_tokens()
px.revoke_specific_token(token["jti"])
```

---

## For Maintainers

### Releasing a New Version

Merging a version bump into `main` publishes to PyPI — see
`.github/workflows/publish.yml`. Nothing is built from a laptop, so what customers
install is always a commit that was reviewed.

```bash
# 1. Bump the version. This is the only place it lives: setup.py stamps it into
#    the package metadata, and prometheux_chain.__version__ reads it back out.
echo "0.4.1" > version.txt

# 2. Open a PR with that change and merge it. That is the whole release.
```

The guard job compares `version.txt` against the tags that already exist, so a
merge that does not bump the version is a no-op. A merge that does bump it builds,
publishes, attests the artifacts, tags the commit `v0.4.1`, and opens a GitHub
Release with the SBOM and checksums attached. A version already on PyPI fails the
upload rather than being skipped quietly.

Do not push a `v*` tag by hand. Nothing listens for tags: the tag is written after
a successful upload as the record of what shipped, and it is what the guard reads
to decide whether the next merge is a release.

> **One-time PyPI setup.** The workflow authenticates with [trusted
> publishing](https://docs.pypi.org/trusted-publishers/) rather than a stored API
> token, so it must be registered once by a PyPI **owner** of the project:
> `prometheux-chain` → Manage → Publishing → add a GitHub publisher with owner
> `prometheuxresearch`, repository `prometheux-chain`, workflow `publish.yml`,
> environment `pypi`.
>
> The environment name is not optional. A trusted publisher is bound to the
> workflow filename rather than to any branch, so without it a branch carrying a
> modified `publish.yml` can mint a real publishing token. Naming `pypi` on both
> sides — and restricting that environment to `main` under Settings →
> Environments → `pypi` → deployment branch policy — is what ties a release to a
> reviewed commit. The environment has to exist before the workflow runs, or the
> publish job fails with `Missing environment 'pypi'`.

---

## Access to Prometheux Backend

The Prometheux backend is required to use this SDK. To request access:

- 📧 **Email**: davben@prometheux.co.uk, teodoro.baldazzi@prometheux.co.uk, or support@prometheux.co.uk
- 🌐 **Website**: https://www.prometheux.ai

## License

BSD 3-Clause License — see [LICENSE](LICENSE) file for details.

## About Prometheux

Prometheux is an **ontology native data engine** that processes data anywhere it lives. Define ontologies once and unlock knowledge that spans databases, warehouses, and platforms—built on the Vadalog reasoning engine.

**Key capabilities:**
- **Connect**: Query across Snowflake, Databricks, Neo4j, SQL, CSV, and more without ETL or vendor lock-in
- **Think**: Replace 100+ lines of PySpark/SQL with simple declarative logic. Power graph analytics without GraphDBs
- **Explain**: Full lineage & traceability with deterministic, repeatable results. Ground AI in structured, explainable context

Exponentially faster and simpler than traditional approaches. Learn more at [prometheux.ai](https://prometheux.ai/).

## Support

For issues, questions, or access requests:

- **Homepage**: https://www.prometheux.ai
- **PyPI**: https://pypi.org/project/prometheux-chain/
- **Email**: davben@prometheux.co.uk, teodoro.baldazzi@prometheux.co.uk, or support@prometheux.co.uk
- **Documentation**: https://docs.prometheux.ai/integrations/python-sdk
- **Issues**: [GitHub Issues](https://github.com/prometheuxresearch/prometheux-chain/issues)

## Related Projects

- [Prometheux MCP](https://pypi.org/project/prometheux-mcp/) — MCP client for AI agents
- [Vadalog Extension](https://pypi.org/project/vadalog-extension/) — JupyterLab extension for Vadalog
- [Vadalog Jupyter Kernel](https://pypi.org/project/vadalog-jupyter-kernel/) — Jupyter kernel for Vadalog
