Metadata-Version: 2.4
Name: cogniform
Version: 0.2.0
Summary: Learn, inspect, transfer and evaluate decision policies from expert demonstrations.
License-Expression: MIT
Project-URL: Repository, https://github.com/AMallur/Cogniform
Project-URL: Issues, https://github.com/AMallur/Cogniform/issues
Keywords: ai,decision-policy,imitation-learning,agents,explainability
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# Cogniform

**Turn reviewed experience into portable, inspectable decision policies.**

Cogniform 0.2.0 is a zero-dependency Python SDK that learns an interpretable decision tree from approved examples. Optional model adapters can extract candidate examples from real records, generate grounded test scenarios, and conduct adaptive expert interviews. Model output is never treated as approved truth automatically.

This remains an alpha release. It is not a foundation model, autonomous retraining service, or production-safety guarantee.

## Install

```sh
pip install cogniform
```

Python 3.10+. OpenAI and Anthropic clients are optional.

## Learn and apply a policy

The 0.1 API is preserved:

```python
from cogniform import Judgment

examples = [
    {"facts": {"risk": "low", "amount": 100}, "decision": "approve"},
    {"facts": {"risk": "low", "amount": 200}, "decision": "approve"},
    {"facts": {"risk": "high", "amount": 100}, "decision": "reject"},
    {"facts": {"risk": "high", "amount": 200}, "decision": "reject"},
]

expert = Judgment.learn(examples)
result = expert.apply({"risk": "high", "amount": 150})
print(result.decision)    # reject
print(result.evidence)    # learned conditions followed
print(result.uncertainty) # empirical leaf impurity, not calibrated risk
```

Cogniform abstains on low support, ambiguous leaves, missing required branches, and unfamiliar values in strict mode.

## Extract candidates from real records

```python
from openai import OpenAI
from cogniform import Judgment, OpenAIModel

model = OpenAIModel(OpenAI(), model="YOUR_MODEL_ID")
batch = Judgment.from_documents(
    ["resolved_tickets.csv", "refund_policy.md"],
    model=model,
    feature_schema={
        "customer_years": {},
        "duplicate_charge": {},
        "company_error": {},
    },
    allowed_decisions=["refund", "refund_and_credit", "deny", "escalate"],
)

for index, candidate in enumerate(batch.candidates):
    print(index, candidate.demonstration, candidate.provenance, candidate.confidence)

# A reviewer approves, corrects, or rejects each candidate.
batch.approve(0)
batch.approve(1, decision="escalate", notes="Corrected by support lead")
batch.reject(2, notes="Outcome was not recorded")
expert = batch.learn()
```

Built-in sources are CSV, JSON, JSONL, Markdown, plain text, iterables, and read-only SQLite queries. A custom source only needs a `source_id` attribute and a `records()` iterator. PDF parsing and named SaaS connectors are not included.

Already structured exports can bypass a model while retaining the same review gate:

```python
from cogniform import import_demonstrations

batch = import_demonstrations(existing_rows, source_id="verified-export")
batch.approve_all()  # only after the caller verifies the export
expert = batch.learn()
```

Each candidate carries a source ID, record locator, and SHA-256 content digest. Raw source text is not stored in the learned profile. Approved provenance is stored, so review it before sharing a profile.

### Custom source adapter

```python
class TicketExport:
    source_id = "internal-ticket-export-2026-12"

    def records(self):
        for ticket in fetch_already_authorized_records():
            yield {
                "problem": ticket.problem,
                "resolution": ticket.resolution,
                "manager_decision": ticket.manager_decision,
            }

batch = Judgment.from_source(TicketExport(), model=model)
```

Cogniform does not ship or claim direct Zendesk, Salesforce, ServiceNow, Jira, Slack, or server-database integrations in 0.2.0.

## Grounded scenario generation and validation

```python
cases = expert.generate_cases(
    count=20,
    sources=approved_historical_examples,
    include_edge_cases=True,
    model=model,
)

for index, scenario in enumerate(cases.scenarios):
    print(scenario.grounded_in, scenario.validation_errors)
    if not scenario.validation_errors:
        cases.approve(index)  # expected decisions still require expert review

report = cases.evaluate(expert)
```

Generated scenarios must cite approved source IDs, use known features and decisions, and pass duplicate checks. Those checks establish structure and traceability, not factual correctness.

## Adaptive expert interviews

```python
from cogniform import Interview

session = Interview(
    domain="procurement",
    model=model,
    feature_schema={"reliability": {}, "cost_increase": {}, "alternative": {}},
    allowed_decisions=["retain", "replace", "qualify_alternative", "escalate"],
)

while (question := session.ask()) is not None:
    session.answer(input(question + "\n> "))

batch = session.candidates()
# Review candidates exactly as with record extraction.
```

Questions adapt to the transcript and target stated gaps. Transcript-derived examples are not trained until approved.

## Gaps, feedback, retraining, and versions

```python
expert = Judgment.learn(examples, retain_examples=True)
print(expert.find_gaps(min_examples=3))

expert.feedback(
    {"risk": "medium", "amount": 150},
    correct_decision="review",
    explanation="Medium risk requires a person.",
)
updated = expert.retrain()  # returns a new profile
print(updated.metadata["profile_version"])
print(updated.metadata["parent_profile_id"])
```

Training examples are not retained by default. With `retain_examples=False`, pass baseline examples to `retrain(examples)`. This avoids silently storing sensitive source records.

```python
from cogniform import ProfileRegistry

registry = ProfileRegistry("profiles")
registry.publish("refund-policy", expert)
registry.publish("refund-policy", updated)
print(registry.versions("refund-policy"))
```

`find_gaps()` reports observable weaknesses such as missing feature values, single observed categories, and low-support rules. It cannot discover situations absent from the dataset.

## Multi-step workflows

```python
from cogniform import DecisionWorkflow, WorkflowStep

workflow = DecisionWorkflow([
    WorkflowStep("risk_screen", risk_profile, select=["risk", "amount"]),
    WorkflowStep("resolution", resolution_profile,
                 select=["risk_screen", "customer_years"]),
])

result = workflow.run({"risk": "low", "amount": 100, "customer_years": 3})
print(result.completed, result.context, result.trace)
```

Each step writes its decision into shared context. The workflow stops when any policy abstains.

## Model adapters and data handling

`OpenAIModel` uses the Responses API and structured outputs when the supplied client supports them, with a Chat Completions fallback. `AnthropicModel` and `CallableModel` remain available.

Records and transcripts are sent to the provider configured by the caller. Cogniform has no telemetry. It separates instructions from untrusted records, validates returned JSON and domain values, enforces size/count limits, and requires review. Applications remain responsible for consent, access control, retention, redaction, provider settings, and human oversight.

## Evaluation, CLI, and development

```python
from cogniform import evaluate, split_demonstrations

train, test = split_demonstrations(examples, seed=42)
report = evaluate(Judgment.learn(train), test)
print(report.accuracy, report.coverage, report.selective_accuracy)
```

```sh
cogniform learn examples/demonstrations.json -o expert.json
cogniform apply expert.json examples/situation.json
cogniform rules expert.json
cogniform evaluate expert.json examples/heldout.json
```

```sh
python -m pip install -e . pytest build twine
python -m pytest -q
python -m build
python -m twine check --strict dist/*
```

The included data and model tests are deterministic functionality fixtures, not evidence of commercial accuracy. CI tests Python 3.10–3.14. The release workflow publishes through the configured PyPI Trusted Publisher only when the version-specific marker changes.

## 0.2.0 limitations

- Human review is required; model confidence is not calibrated probability.
- Only JSON scalar features are supported by the decision engine.
- The learned model is an entropy-based decision tree, not causal reasoning.
- Built-in document reading does not parse PDF, DOCX, email, images, or audio.
- SQLite is local and read-only; server databases need custom adapters.
- No named enterprise/SaaS connector is bundled.
- No hosted registry, access-control service, drift monitor, or model-weight training is included.
- Production suitability depends on representative data, independent evaluation, privacy controls, and domain-specific oversight.

See [PUBLISHING.md](PUBLISHING.md) and [CHANGELOG.md](CHANGELOG.md).
