Metadata-Version: 2.4
Name: semantic-lexicon
Version: 0.1.1
Summary: Neural semantic modeling toolkit with persona-aware generation and diagnostics.
Author: Semantic Lexicon Team
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/farukalpay/Semantic-Lexicon
Project-URL: Documentation, https://github.com/farukalpay/Semantic-Lexicon#readme
Project-URL: Issues, https://github.com/farukalpay/Semantic-Lexicon/issues
Keywords: nlp,semantics,persona,knowledge-graph,cli
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python
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
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy<2.0,>=1.23
Requires-Dist: typer<0.20,>=0.13
Requires-Dist: PyYAML<7.0,>=6.0
Requires-Dist: matplotlib<4.0,>=3.8
Provides-Extra: dev
Requires-Dist: black>=23.0; extra == "dev"
Requires-Dist: ruff>=0.4; extra == "dev"
Requires-Dist: mypy>=1.4; extra == "dev"
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1; extra == "dev"
Provides-Extra: docs
Requires-Dist: mkdocs>=1.5; extra == "docs"
Requires-Dist: mkdocs-material>=9.5; extra == "docs"
Provides-Extra: tadkit
Requires-Dist: transformers>=4.37; extra == "tadkit"
Requires-Dist: torch>=2.1; extra == "tadkit"
Requires-Dist: pandas>=2.0; extra == "tadkit"
Requires-Dist: streamlit>=1.30; extra == "tadkit"
Provides-Extra: personarag
Requires-Dist: langchain>=0.2; extra == "personarag"
Requires-Dist: langchain-core>=0.2; extra == "personarag"
Requires-Dist: langchain-openai>=0.1; extra == "personarag"
Requires-Dist: langchain-community>=0.2; extra == "personarag"
Requires-Dist: langgraph>=0.0.64; extra == "personarag"
Requires-Dist: faiss-cpu>=1.7; extra == "personarag"
Requires-Dist: openai>=1.0; extra == "personarag"
Dynamic: license-file

# Semantic Lexicon

[![CLI Tests](https://github.com/farukalpay/Semantic-Lexicon/actions/workflows/cli-tests.yml/badge.svg)](https://github.com/semantic-lexicon/Semantic-Lexicon/actions/workflows/cli-tests.yml)

Semantic Lexicon is a NumPy-first research toolkit that demonstrates persona-aware semantic modelling. The project packages a compact neural stack consisting of intent understanding, a light-weight knowledge network, persona management, and text generation into an automated Python library and CLI.

The name reflects the long-standing academic concept of the [semantic lexicon](https://en.wikipedia.org/wiki/Semantic_lexicon); this repository contributes an applied, open implementation that operationalises those ideas for persona-aware experimentation.

## Citation

Semantic Lexicon operationalises the reproducible persona-aware pipeline introduced in the accompanying preprint. If you build on this toolkit, please cite the work so other researchers can trace the connection between the paper's methodology and this implementation.

```bibtex
@misc{alpay2025reproduciblescalablepipelinesynthesizing,
      title={A Reproducible, Scalable Pipeline for Synthesizing Autoregressive Model Literature}, 
      author={Faruk Alpay and Bugra Kilictas and Hamdi Alakkad},
      year={2025},
      eprint={2508.04612},
      archivePrefix={arXiv},
      primaryClass={cs.IR},
      url={https://arxiv.org/abs/2508.04612}, 
}
```

You can read the preprint online at [https://arxiv.org/abs/2508.04612](https://arxiv.org/abs/2508.04612); it documents the scalable data curation and evaluation strategy that directly powers the automation, diagnostics, and persona controls exposed by this repository.

## Features

- **Modular architecture** – dedicated submodules for embeddings, intent classification, knowledge graphs, persona handling, and persona-aware generation.
- **Deterministic NumPy training loops** – simple yet reproducible optimisation routines for intents and knowledge edges.
- **Automated workflows** – Typer-powered CLI (`semantic-lexicon`) for corpus preparation, training, diagnostics, and generation.
- **Extensible configuration** – YAML/JSON configuration loading with dataclass-backed defaults.
- **Diagnostics** – structured reports covering embeddings, intents, knowledge neighbours, personas, and generation previews.
- **Adversarial style selection** – EXP3 utilities for experimenting with persona choices under bandit feedback.
- **Analytical guarantees** – composite reward shaping, Bayesian calibration, and regret tooling with documented proofs.
- **Graph-based knowledge curation** – SPPMI-weighted co-occurrence graphs, smoothed relevance, and greedy facility-location selection produce calibrated “Knowledge” scores that surface tightly connected concepts.
- **Docs & tests** – MkDocs documentation, pytest-based regression tests, prompt evaluation hub (`docs/prompt-evaluations/index.md`), and CI-ready tooling (black, ruff, mypy).
- **Primal–dual safety tuning** – projected primal–dual controller that auto-tunes exploration, pricing, and knowledge gates until all residuals vanish.

## Installation

1. **Create a virtual environment** (recommended):

   ```bash
   python -m venv .venv
   source .venv/bin/activate
   ```

2. **Install Semantic Lexicon directly from GitHub** using pip's `name @ URL` syntax (avoids
   future deprecation warnings while matching the hosted repository):

   ```bash
   pip install "semantic-lexicon[dev,docs] @ git+https://github.com/farukalpay/Semantic-Lexicon.git"
   ```

   Use the table below to tailor optional extras to your workflow:

   | Goal | Command |
   | --- | --- |
   | Minimal CLI & library | `pip install "semantic-lexicon @ git+https://github.com/farukalpay/Semantic-Lexicon.git"` |
   | Docs + developer tooling | `pip install "semantic-lexicon[dev,docs] @ git+https://github.com/farukalpay/Semantic-Lexicon.git"` |
   | TADKit demos (needs PyTorch + Streamlit) | `pip install "semantic-lexicon[tadkit] @ git+https://github.com/farukalpay/Semantic-Lexicon.git"` |
   | PersonaRAG demos (LangChain/LangGraph stack) | `pip install "semantic-lexicon[personarag] @ git+https://github.com/farukalpay/Semantic-Lexicon.git"` |

> **Note:** `tadkit` relies on PyTorch for logits processing. Install a CPU build with
> `pip install torch --index-url https://download.pytorch.org/whl/cpu` if it is not already
> included in your environment.

## Project Layout

```
src/semantic_lexicon/
├── cli.py                # Typer CLI entry point
├── config.py             # Dataclass-backed configuration helpers
├── embeddings.py         # GloVe-style embeddings and persistence
├── intent.py             # NumPy multinomial logistic regression intents
├── knowledge.py          # Simple relation network with gradient updates
├── persona.py            # Persona profiles and blending logic
├── generator.py          # Persona-aware response generation
├── model.py              # Orchestration façade
├── training.py           # Training pipeline and diagnostics integration
├── diagnostics.py        # Structured diagnostics reports
├── utils/                # Tokenisation, seeding, and I/O helpers
└── data/                 # Sample intent & knowledge datasets for tests
```

## Quick Start

1. **Prepare the corpus** (optional if using bundled sample data):

   ```bash
   semantic-lexicon prepare --intent src/semantic_lexicon/data/intent.jsonl --knowledge src/semantic_lexicon/data/knowledge.jsonl --workspace artifacts
   ```

2. **Train the model** (uses processed datasets in `artifacts/`):

   ```bash
   semantic-lexicon train --workspace artifacts
   ```

The CLI saves embeddings, intent weights, and knowledge matrices to the workspace directory.

3. **Run diagnostics**:

   ```bash
   semantic-lexicon diagnostics --workspace artifacts --output diagnostics.json
   ```

   The command prints a JSON summary to stdout and optionally writes the report to disk.

4. **Generate responses**:

   ```bash
   semantic-lexicon generate "Explain neural networks" --workspace artifacts --persona tutor
   ```

## Truth-Aware Decoding Walkthrough

Truth-aware decoding (TAD) combines a model's logits with declarative knowledge supplied by one or more safety oracles. Each decode step (a) queries the model for logits, (b) consults the oracle for a boolean allow/block mask plus diagnostic labels, (c) computes the probability mass that remains safe, and (d) either selects the highest-probability safe token or abstains when the safe mass falls below a configurable threshold. The [`semantic_lexicon.decoding_tad.truth_aware_decode`](src/semantic_lexicon/decoding_tad.py) loop is pure NumPy and logs every decision in a `TADStepLog`, making it easy to audit or integrate into research pipelines.

### Reproducing the toy capital-of demo

The repository includes a fully-worked, research-grade example that resolves the prompt *“Paris is the capital of …”* against a knowledge-base oracle. The script reproduces the toy model from the TAD unit tests, injects a fact table with a single triple `(Paris, capital_of, France)`, and records all decode-time telemetry to disk.

```bash
python examples/truth_aware_decode_demo.py
```

Running the demo prints the safe decoding trace and saves the structured log to `examples/logs/paris_capital_truth_aware_decode.json`:

```
Prompt tokens: <BOS> Paris is the capital of
Generated tokens: France <EOS>
Log written to examples/logs/paris_capital_truth_aware_decode.json
```

The JSON log captures every metric needed for a forensic audit. Each entry in `steps` reports the decode index `t`, the safe probability mass `pi_safe` (after masking), the selected token, the number of blocked vocabulary entries, and the oracle-provided reason labels. A shortened excerpt is shown below; the full file is part of the repository so you can cite or diff it in papers and lab notebooks.

```json
{
  "prompt_tokens": ["<BOS>", "Paris", "is", "the", "capital", "of"],
  "generated_tokens": ["France", "<EOS>"],
  "abstained": false,
  "steps": [
    {
      "t": 0,
      "pi_safe": 0.3390092760113778,
      "picked_token": "France",
      "blocked_count": 3,
      "reasons_for_picked": ["kb:required_object"]
    },
    {
      "t": 1,
      "pi_safe": 1.0,
      "picked_token": "<EOS>",
      "blocked_count": 0,
      "reasons_for_picked": []
    }
  ]
}
```

From here you can: (1) swap in the graph-backed oracle to ground against a larger knowledge base, (2) set `TADConfig.abstain_token` to emit a sentinel when `pi_safe` drops below the threshold, and (3) feed the logged `pi_safe` sequence into your own reliability analyses (e.g., cumulative risk bounds or safe-mass histograms). Because `truth_aware_decode` works with any `Oracle` implementation, PhD students can plug in bespoke symbolic checkers—factuality verifiers, contradiction detectors, or mathematical solvers—without touching the decoding loop itself.

## TADKit — drop-in logits processor and CLI

The repository now exposes a standalone [`tadkit`](src/tadkit) package so you can pip-install the truth-aware decoding utilities outside of the monolithic CLI. TADKit mirrors the “expected product” shown in the product brief:

- `TruthOracle` turns CSV/JSON/YAML rules into prompt-activated constraints.
- `TADLogitsProcessor` plugs into `transformers` generation loops and injects abstain tokens when a rule is violated.
- `TADTrace` logs token-level actions and renders console tables or Pandas dataframes for audits.
- `tadkit compile` converts spreadsheets to JSON payloads; `tadkit demo` spins up a tiny `sshleifer/tiny-gpt2` demo using the compiled oracle.
- `examples/tadkit_quickstart.py` and `examples/tadkit_streamlit_app.py` are copy-pasteable quickstarts, matching the walkthrough in the brief.

Install extras as needed:

```bash
pip install "git+https://github.com/farukalpay/Semantic-Lexicon.git#egg=semantic-lexicon[tadkit]"
tadkit compile capitals.csv --out oracle.json --tokenizer gpt2
tadkit demo --oracle oracle.json --model sshleifer/tiny-gpt2 \
  --prompt "Q: What is the capital of France?\nA:"
```

> **Note:** `tadkit` relies on PyTorch for logits processing. Install a CPU
> build with `pip install torch --index-url https://download.pytorch.org/whl/cpu`
> if you do not already have `torch` available.

## PersonaRAG — EXP3 personas with decode-time truth gates

PersonaRAG is a thin layer on top of LangChain/LangGraph that routes tone, enforces truth, and records feedback telemetry. The [`personarag`](src/personarag) package exposes:

- `BrandStyle` persona descriptors.
- `PersonaPolicyEXP3` — contextual EXP3 with weight telemetry and bulk feedback helpers.
- `KnowledgeGate` — wraps LangChain LLMs and installs `TADLogitsProcessor` when the underlying model exposes Hugging Face hooks.
- `examples/personarag_quickstart.py` — the complete “expected product” script from the brief.

Install with optional dependencies when you want the full LangChain stack:

```bash
pip install "git+https://github.com/farukalpay/Semantic-Lexicon.git#egg=semantic-lexicon[personarag]"
python examples/personarag_quickstart.py
```

Decode-time gating is enabled automatically for Hugging Face models (local or
via LangChain wrappers). Hosted chat models (e.g., OpenAI) receive trace
metadata only.

`KnowledgeGate` attaches `trace.events` to `response_metadata` (when available), so observability dashboards can render trace heatmaps alongside persona win-rates and abstain telemetry.

## Knowledge Selection Playbook

The knowledge selector now treats every AGENTS.md instruction as a hard feasibility constraint. Broad concepts can still join the shortlist, but only when they collaborate with prompt-relevant anchors *and* all group bounds are respected.

> **Note:** The full mathematical specification for the selector — including the object definitions, scoring components, constraints, and optimisation guarantees — now lives in [`docs/articles/knowledge-selector.tex`](docs/articles/knowledge-selector.tex). The README keeps the practitioner-focused workflow and validation guidance below; consult the article whenever you need the derivations or precise notation.

### Workflow

1. **Graph construction.** Estimate shifted PPMI weights with smoothing \(p(i)^\gamma\); derive \(S\), \(D\), \(L\), and \(P\).
2. **Relevance smoothing.** Compute raw cosine relevance, solve the graph-regularised system, and classify on/off-topic nodes via the topic threshold.
3. **Anchoring.** Select anchors, compute personalised PageRank bridges, and form soft gates \(g_i\).
4. **Group configuration.** Register AGENTS.md groups with `set_concept_groups` and interval bounds with `set_group_bounds`; the selector automatically adds on/off-topic ratios.
5. **Greedy selection.** Evaluate admissible candidates, compute marginal coverage, cohesion, collaboration, and diversity, and add the best concept while updating group capacities.
6. **Reporting.** Emit the chosen concepts plus relevance, coverage, cohesion, collaboration, diversity, raw knowledge score, and mean gate.

Defaults \((\alpha, \lambda, \mu, \gamma, \tau, \lambda_1, \lambda_2, K, \tau_g, \text{on/off ratios}) = (0.12, 0.08, 0.5, 0.35, 0.1, 0.6, 0.4, 12, 0.08, 0.6/0.2/0.4)) ship in `KnowledgeConfig`. Additional per-group intervals can be supplied at runtime. The legacy phrase planner (MMR phrase selection with PMI bonuses) remains available inside the generator for reproducibility.
Use the CLI to inspect the concepts chosen for a prompt without rendering a full response:

```bash
semantic-lexicon knowledge "Explain matrix multiplication" --workspace artifacts
```

The JSON payload now includes gated relevance, coverage, cohesion, collaboration reward, log-det diversity, the raw knowledge score,
and the mean gate value across selected concepts.

### Go/No-Go Validation

Before shipping a new persona or pricing configuration, run the Go/No-Go suite to certify that knowledge selection obeys AGENTS.md, the deployment policy respects the exploration rules, and the off-policy lift is trustworthy.

1. **Rule feasibility.** Map each concept to its groups and bounds, count how many selections fall inside every group, and reject whenever any lower or upper bound is violated. `SelectionSpec` now bundles a `KnowledgeSignals` payload so the same object carries the calibrated knowledge metrics required later in the gate.

2. **Policy consistency.** For each logged step, rebuild the policy that was deployed using the stored logits, temperature, exploration mixture, and whichever penalty mode (prices or congestion) was active. The policy gate fails if any logged action falls below its exploration floor, if prices and congestion penalties are mixed, if the knowledge weight leaves the [0,1] range, or if the SNIPS floor dips below the exploration limit — guarding the AGENTS exploration guarantees.

3. **Off-policy value & fairness.** Using tuples (x_i, a_i, r_i, p_i) and the reconstructed target policy, compute SNIPS weights, the estimated value, and the effective sample size. Enforce a non-negative lower confidence bound on the lift, require the effective sample size to exceed one percent of the log length, and evaluate fairness either on action frequencies or KPI gaps via `FairnessConfig`.

4. **Price/congestion stability.** Aggregate the penalty vector each timestep and ensure the most recent window keeps total variation below the configured threshold. `StabilityCheckResult` records the peak deviation so you can tighten rho or beta when oscillations appear.

5. **Knowledge lift.** Compare the calibrated score and graph metrics captured in `KnowledgeSignals`. The gate demands the calibrated knowledge score stay above the trailing median and both coverage and cohesion deltas remain non-negative against the baseline selection size.

6. **Go/No-Go decision.** `run_go_no_go` wires the six checks together and emits a `GoNoGoResult` containing the selection feasibility, policy mode, OPE summary (with ESS target), stability diagnostics, and knowledge lift verdict. The `accepted` flag only flips to `True` when **every** gate passes. If any condition fails, follow the fix-once cascade in the specification — tweak the single knob (e.g., adjust `l_off`, `tau_g`, `eta`, or `rho`) and re-run the optimisation exactly once before re-testing.


### Primal–Dual Safety Gate Autotuning

Manual gate sweeps are still supported, but the preferred workflow is to run the projected primal–dual controller introduced in `semantic_lexicon.safety`. The controller now minimises the supplied objective while enforcing convex constraints, matching the textbook projected primal–dual loop.

```python
from semantic_lexicon.safety import (
    ConstraintSpec,
    GateBounds,
    ObjectiveSpec,
    run_primal_dual_autotune,
)

objective = ObjectiveSpec(
    function=lambda params: params["x1"] ** 2
    + params["x2"] ** 2
    - params["x1"]
    - params["x2"],
    gradient=lambda params: {
        "x1": 2.0 * params["x1"] - 1.0,
        "x2": 2.0 * params["x2"] - 1.0,
    },
)

constraints = [
    ConstraintSpec(
        "linear",
        lambda params: params["x1"] + params["x2"] - 1.0,
        gradient=lambda params: {"x1": 1.0, "x2": 1.0},
    )
]

result = run_primal_dual_autotune(
    objective,
    constraints,
    initial_parameters={"x1": 0.2, "x2": 0.8},
    parameter_names=("x1", "x2"),
    bounds={
        "x1": GateBounds(lower=0.0, upper=1.0),
        "x2": GateBounds(lower=0.0, upper=1.0),
    },
    primal_step=0.2,
    dual_step=0.4,
)

print("before", result.history[0])
print("after", result.parameters)
```

The first history entry captures the primal iterate after the initial step alongside its constraint violation, while the final snapshot records the tuned solution and dual multiplier. Swapping in exploration, fairness, or stability constraints follows the same pattern—only the callbacks change.

### Single-change presentation planner

When time only allows one tweak before a repeat talk, call `build_single_adjustment_plan()` to fetch a rehearsable experiment and a set of intent-hidden contingency moves. The helper keeps pacing and visuals frozen, picks *story beats* as the highest-leverage lever, and returns:

- A 20-minute rehearsal script that remaps the 12-minute slot into five beats, captures the headline you expect listeners to write down in each block, logs energy scores, and enforces a pass/fail line that demands fresh takeaways past minute seven.
- Five backup drills covering energy checkpoints, a slide trim for mixed audiences, a Q&A guardrail, a warmth-restoring micro-story, and a lighting plus breathing tweak for filler-word control.

```python
from semantic_lexicon.presentation import build_single_adjustment_plan

experiment, backups = build_single_adjustment_plan()
print(experiment.focus)
for move in backups:
    print(move.label)
```

Backups remain intent-hidden so you can pivot mid-practice without exposing the heuristic to the audience.

## Lightweight Q&A Demo

Semantic Lexicon can answer short questions after its bundled model components are trained. The stack is intentionally tiny, so
the phrasing is concise, but the generator now runs a compact optimisation loop that:

1. **Classifies intent** with the logistic-regression intent model.
2. **Builds noun-phrase and collocation candidates** whose adjacent tokens clear an adaptive pointwise mutual information (PMI)
   threshold, keeping multi-word ideas intact.
3. **Scores each candidate** via cosine relevance to the blended persona/prompt embedding, tf–idf salience, and a capped PMI
   cohesion bonus.
4. **Selects diverse topics** with Maximum Marginal Relevance (MMR) plus an n-gram overlap penalty so the guidance does not echo
   the question verbatim.
5. **Optimises knowledge coverage** by running the gated SPPMI graph objective (smoothed relevance, anchor gating, collaboration
   reward, log-det diversity, and group-aware constraints) and appending the resulting knowledge focus and related concepts.
6. **Aligns journaling actions** with the detected intent so each topic carries a concise Explore/Practice/Reflect-style cue.

1. Install the project in editable mode:

   ```bash
   pip install -e .
   ```

2. Run a quick script that trains the miniature model and generates answers for a few prompts:

   ```bash
   python - <<'PY'
   from semantic_lexicon import NeuralSemanticModel, SemanticModelConfig
   from semantic_lexicon.training import Trainer, TrainerConfig

   config = SemanticModelConfig()
   model = NeuralSemanticModel(config)
   trainer = Trainer(model, TrainerConfig())
   trainer.train()

   for prompt in [
       "How do I improve my public speaking?",
       "Explain matrix multiplication",
       "What is machine learning?",
       "Tips for staying productive while studying",
       "Clarify the concept of photosynthesis",
       "How can I organize my research presentation effectively?",
       "Define gravitational potential energy",
   ]:
       response = model.generate(prompt, persona="tutor")
       print(
           f"Prompt: {prompt}\\nResponse: {response.response}\\nKnowledge: {response.knowledge_hits}\\n"
       )
   PY
   ```

   Sample output after training the bundled data:

   ```
   Prompt: How do I improve my public speaking?
   Response: From a balanced tutor perspective, let's look at "How do I improve my public speaking?" This ties closely to the "how_to" intent I detected. Consider journaling about: Public Speaking (Explore), Practice Routine (Practice), Feedback Loops (Reflect). Try to explore Public Speaking, practice the routine, and reflect on Feedback Loops. Knowledge focus: practice short talks on camera. Related concepts worth exploring: collect feedback from trusted listeners, rehearse transitions and openings, track energy and pacing cues.
   Knowledge: ['practice short talks on camera', 'collect feedback from trusted listeners', 'rehearse transitions and openings', 'track energy and pacing cues', 'K_raw=0.832']

   Prompt: Explain matrix multiplication
   Response: From a balanced tutor perspective, let's look at "Explain matrix multiplication." This ties closely to the "definition" intent I detected. Consider journaling about: Matrix Multiplication (Define), Dot Products (Explore), Linear Transformations (Compare). Try to define Matrix Multiplication, explore Dot Products, and compare Linear Transformations with related ideas. Knowledge focus: review the row-by-column rule. Related concepts worth exploring: connect matrix products to linear transformations, practice multiplying 2x2 and 3x3 matrices, interpret column space changes.
   Knowledge: ['review the row-by-column rule', 'connect matrix products to linear transformations', 'practice multiplying 2x2 and 3x3 matrices', 'interpret column space changes', 'K_raw=0.821']

   Prompt: What is machine learning?
   Response: From a balanced tutor perspective, let's look at "What is machine learning?" This ties closely to the "definition" intent I detected. Consider journaling about: Machine Learning (Define), Supervised Learning (Explore), Generalization Error (Compare). Try to define Machine Learning, explore Supervised Learning, and compare Generalization Error with related ideas. Knowledge focus: machine learning. Related concepts worth exploring: unsupervised learning, supervised learning.
   Knowledge: ['machine learning', 'unsupervised learning', 'supervised learning', 'K_raw=0.815']

   Prompt: Tips for staying productive while studying
   Response: From a balanced tutor perspective, let's look at "Tips for staying productive while studying." This ties closely to the "how_to" intent I detected. Consider journaling about: Study Schedule (Plan), Focus Blocks (Practice), Break Strategies (Reflect). Try to plan Study Schedule, practice Focus Blocks, and reflect on Break Strategies. Knowledge focus: design focus blocks with clear targets. Related concepts worth exploring: batch similar study tasks together, schedule renewal breaks, log end-of-day reflections.
   Knowledge: ['design focus blocks with clear targets', 'batch similar study tasks together', 'schedule renewal breaks', 'log end-of-day reflections', 'K_raw=0.829']

   Prompt: Clarify the concept of photosynthesis
   Response: From a balanced tutor perspective, let's look at "Clarify the concept of photosynthesis." This ties closely to the "definition" intent I detected. Consider journaling about: Photosynthesis (Define), Chlorophyll Function (Explore), Energy Conversion (Connect). Try to define Photosynthesis, explore Chlorophyll Function, and connect Energy Conversion to what you already know. Knowledge focus: map light-dependent and light-independent stages. Related concepts worth exploring: highlight the role of chlorophyll, trace energy conversion to glucose, connect photosynthesis to cellular respiration.
   Knowledge: ['map light-dependent and light-independent stages', 'highlight the role of chlorophyll', 'trace energy conversion to glucose', 'connect photosynthesis to cellular respiration', 'K_raw=0.832']

   Prompt: How can I organize my research presentation effectively?
   Response: From a balanced tutor perspective, let's look at "How can I organize my research presentation effectively?" This ties closely to the "how_to" intent I detected. Consider journaling about: Presentation Outline (Plan), Visual Storytelling (Design), Audience Engagement (Practice). Try to plan Presentation Outline, design Visual Storytelling, and practice Audience Engagement. Knowledge focus: draft a clear narrative arc. Related concepts worth exploring: storyboard slides around key findings, practice delivery with timed sections, prepare audience engagement prompts.
   Knowledge: ['draft a clear narrative arc', 'storyboard slides around key findings', 'practice delivery with timed sections', 'prepare audience engagement prompts', 'K_raw=0.829']

   Prompt: Define gravitational potential energy
   Response: From a balanced tutor perspective, let's look at "Define gravitational potential energy." This ties closely to the "definition" intent I detected. Consider journaling about: Potential Energy (Define), Reference Frames (Illustrate), Energy Transfer (Connect). Try to define Potential Energy, illustrate Reference Frames with a quick example, and connect Energy Transfer to what you already know. Knowledge focus: define reference height explicitly. Related concepts worth exploring: illustrate energy transfer scenarios, compare gravitational and elastic potential energy, relate potential changes to work.
   Knowledge: ['define reference height explicitly', 'illustrate energy transfer scenarios', 'compare gravitational and elastic potential energy', 'relate potential changes to work', 'K_raw=0.832']
   ```

  These concise replies highlight the intentionally compact nature of the library's neural components—the toolkit is designed for
  research experiments and diagnostics rather than fluent conversation, yet it showcases how questions can be routed through the
  persona-aware pipeline.

  Running `python examples/quickstart.py` (or `PYTHONPATH=src python examples/quickstart.py` from a checkout) produces a combined
  generation preview and the new intent-selection walkthrough:

  ```
  Sample generation:
    Prompt: Share tips to learn python
    Persona: tutor
    Response: From a balanced tutor perspective, let's look at "Share tips to learn python." This ties closely to the "how_to" intent I detected. Consider journaling about: Study Schedule (Plan), Focus Blocks (Practice), Break Strategies (Reflect). Try to plan Study Schedule, practice Focus Blocks, and reflect on Break Strategies. Knowledge focus: schedule focused practice blocks. Related concepts worth exploring: work through bite-sized python projects, review core syntax and standard library patterns, reflect on debugging takeaways.
    Journaling topics: Study Schedule, Focus Blocks, Break Strategies
    Knowledge concepts: schedule focused practice blocks, work through bite-sized python projects, review core syntax and standard library patterns, reflect on debugging takeaways
    Knowledge scores: relevance=3.956, coverage=0.865, cohesion=0.776, collaboration=0.349, diversity=6.867, K_raw=0.829, gate_mean=0.736

  Calibration report: ECE raw=0.437 -> calibrated=0.027 (reduction=94%)
  Reward weights: [0.2666619 0.2923091 0.075     0.366029 ]

  Intent bandit walkthrough:
  Prompt: Clarify when to use breadth-first search
  Classifier intent: definition (optimal=definition)
  Reward components: correctness=1.00, confidence=1.00, semantic=0.80, feedback=0.92
  Composite reward: 0.96
  Response: use case → shortest path in unweighted graphs; contrasts with → depth-first search

  Prompt: How should I start researching renewable energy?
  Classifier intent: how_to (optimal=how_to)
  Reward components: correctness=1.00, confidence=0.45, semantic=0.80, feedback=0.92
  Composite reward: 0.80
  Response: first step → audit local energy use; research → read government energy outlook

  Prompt: Compare supervised and unsupervised learning
  Classifier intent: comparison (optimal=comparison)
  Reward components: correctness=1.00, confidence=1.00, semantic=0.84, feedback=0.92
  Composite reward: 0.96
  Response: compare with → unsupervised learning; focus → labeled data; focus → pattern discovery

  Prompt: Offer reflective prompts for creative writing
  Classifier intent: exploration (optimal=exploration)
  Reward components: correctness=1.00, confidence=0.42, semantic=0.80, feedback=0.92
  Composite reward: 0.79
  Response: prompt → explore character motivations; prompt → reflect on sensory details
  ```

  The quickstart rewards are simulated using the intent classifier's posterior probabilities so the bandit loop stays in the unit
  interval without external feedback.

  You can opt into saving the calibrated accuracy curve and the empirical-vs-theoretical EXP3 regret comparison that back the
  analysis appendix by setting `SEMANTIC_LEXICON_SAVE_PLOTS=1` (or `true/yes/on`) before running the script. This keeps the
  repository free of bulky PNGs by default while still letting you regenerate them under `docs/assets/` on demand. Refer to the
  generated CSV summaries in `Archive/` for the underlying values if you wish to recreate the plots with your preferred tooling.
  The same behaviour is available through the CLI:

### Fixed-Point Ladders Companion

The research brief that motivated the README examples now has a full mathematical companion in
[`docs/articles/fixed-point-ladders.md`](docs/articles/fixed-point-ladders.md). The article walks through:

- **Parts A–C (Foundations & Logic):** proofs of the lattice background, the Knaster–Tarski theorem, Kleene iteration, and
  µ-calculus semantics, all illustrated with the reachability operator that powers the persona-aware knowledge search.
- **Parts D–H (Shortcuts & Optimisation):** contraction-based accelerations, closure operators for finite-time stabilisation,
  and multi-objective "best layer" selection rules that mirror the reward-shaping heuristics used in the quickstart bandit demo.
- **Parts I (Reflection):** a diagrammatic summary that ties the layer-by-layer iterations back to the automation loops in this
  repository, making it easy to map the abstract ladders onto concrete CLI behaviours.

Each section keeps the ladder visual from the README and annotates it with the corresponding proofs or calculations so the
math-heavy readers can cross-check the guarantees while experimenting with the code.

  For a dedicated, math-forward treatment of the fixed-point ladders referenced above, consult
  [docs/articles/fixed-point-ladders.md](docs/articles/fixed-point-ladders.md).

```bash
semantic-lexicon generate "What is machine learning?" \
  --workspace artifacts \
  --persona tutor \
  --config config.yaml
```

## Cross-domain validation & profiling

Run the bundled validation harness to stress-test the calibrated intent router on
100 prompts that span science, humanities, business, wellness, and personal
development queries:

```bash
PYTHONPATH=src python examples/cross_domain_validation.py
```

The script trains the classifier, evaluates it on the new prompt set, and saves a
report to `Archive/cross_domain_validation_report.json`. We report
\(\mathrm{Last}(\mathcal{R})\) and the corresponding content address \(h_{j^\star}\)
as defined in §4.

Runs are archived in `Archive/topic_pure_retrieval_runs.json`.

### §1 Core objects

```math
\begin{aligned}
&\mathbb{R}^d,\ d\in\mathbb{N}.\\
&\mathcal{C}=\{c_i\}_{i=1}^{N},\ E[c]\in\mathbb{R}^d.\\
&z:\mathcal{Q}\to \mathbb{R}^d.\\
&p\in\mathbb{R}^d\ \text{(use } p=0 \text{ if not applicable)}.\\
&g\in[0,1]^d,\quad M\succeq 0\in\mathbb{R}^{d\times d}.\\
&W=\Sigma^{-1/2}.
\end{aligned}
```

#### Scoring and retrieval

```math
r(q)=\mathrm{diag}(g)\,\big(z(q)+p\big),\qquad
s(q,c)=\big(Wr(q)\big)^{\!\top} M \big(WE[c]\big),\qquad
S_k(q)=\mathop{\mathrm{arg\,topk}}_{c\in\mathcal{C}} s(q,c).
```

### §2 Evaluation archive and identifiers

```math
R_j=\big(\Theta_j,\ \mathcal{D}_j,\ \mathcal{T}_j,\ \mathbf{m}_j,\ t_j\big).
```

```math
h_j=\mathsf{H}\!\big(\Theta_j,\,\mathcal{D}_j,\,\mathcal{T}_j\big),\quad
\text{with } \mathsf{H}:{\{0,1\}^\ast}\to\{0,1\}^{256} \text{ collision-resistant.}
```

### §3 Metrics

```math
\text{Purity@}k(q)=\frac{1}{k}\sum_{c\in S_k(q)}\mathbf{1}\{y(c)=y(q)\}.
```

```math
\mathsf{TVR}=\mathbb{P}\big[s(q,c^+)\le s(q,c^-)\big],\qquad
\mathsf{GS}=\frac{\|g\|_0}{d},\qquad
\kappa(\Sigma)=\frac{\lambda_{\max}(\Sigma)}{\lambda_{\min}(\Sigma)}.
```

```math
\mathbf{m}_j=\big(\ \overline{\text{Purity@}5},\ \overline{\text{Purity@}10},\ \mathsf{TVR},\ \mathsf{GS},\ \kappa(\Sigma)\ \big)_j,\quad
\overline{\cdot}\ \text{averages over } \mathcal{D}_j.
```

### §4 README functionals

```math
\mathrm{Last}(\mathcal{R})=\mathbf{m}_{j^\star},\quad j^\star=\arg\max_j t_j.
```

```math
\mathrm{Best}_{f,w}(\mathcal{R})=\mathbf{m}_{\arg\max_j f(w\odot \mathbf{m}_j)},\quad w\in\mathbb{R}_{\ge 0}^m,\ f:\mathbb{R}^m\to\mathbb{R}\ \text{monotone}.
```

```math
\mathrm{Mean}(\mathcal{R})=\frac{1}{n}\sum_{j=1}^{n}\mathbf{m}_j,\quad n=|\mathcal{R}|.
```

```math
\Delta(\mathcal{R})=\mathbf{m}_{j^\star}-\mathbf{m}_{j^\star-1}\quad (\text{defined if } n\ge 2).
```

```math
\big(h_{j^\star},\,\mathrm{Last}(\mathcal{R})\big)=\Big(\mathtt{845d7c3479535bdc83f7ed403e5b3695f242cc4561c807421f5c70d0c941291b},\ (0.6,0.5,0.0,1.0,371.6768300721485)\Big).
```

### §5 Example prompt I/O

```math
\mathcal{Q}^\star=\{q_0,q_1,q_2,q_3\},\qquad k=2.
```

```math
\Pi_k(q)=\big(S_k(q),\ s(q, S_k(q))\big).
```

```math
\text{Examples}(\mathcal{Q}^\star;\ h)=\Big\{\,\big(q,\ \Pi_k^{(h)}(q)\big)\ :\ q\in \mathcal{Q}^\star \Big\},\quad h=\mathtt{845d7c3479535bdc83f7ed403e5b3695f242cc4561c807421f5c70d0c941291b}.
```

### §6 Guarantees

- Lossless history: \(j\mapsto R_j\) is injective; the README exposes \(\{\mathbf{m}_j\}\) via \((h_{j^\star},\mathrm{Last}(\mathcal{R}))\).
- Determinism: for fixed \(h\) and \(q\), \(\Pi_k^{(h)}(q)\) is unique.
- Stability: \(P(P(M))=P(M),\ M\succeq 0\Rightarrow P(M)=M,\ P(M)\succeq 0\).

A companion benchmark is written to `Archive/intent_performance_profile.json`.
With heuristic fast paths, sparse dot products, and vector caching enabled the
optimised classifier processes repeated prompts **60 % faster** than the baseline
float64 pipeline (1.83 ms → 0.73 ms per request) while keeping the same accuracy.
Caching retains the most recent vectors, so the optimised pipeline uses ~27 KB of
RAM versus the baseline’s 4 KB; the additional footprint is documented alongside
the latency numbers so deployments can choose the appropriate trade-off.

## Streaming feedback API

Real-time user feedback can be folded into the composite reward with the new
HTTP server. Launch the background service by wiring an `IntentClassifier`
through `FeedbackService` and `FeedbackAPI`:

```python
from semantic_lexicon import IntentClassifier, IntentExample
from semantic_lexicon.api import FeedbackAPI, FeedbackService
from semantic_lexicon.utils import read_jsonl

examples = [
    IntentExample(text=str(rec["text"]), intent=str(rec["intent"]), feedback=0.92)
    for rec in read_jsonl("src/semantic_lexicon/data/intent.jsonl")
]
classifier = IntentClassifier()
classifier.fit(examples)
service = FeedbackService(classifier)
api = FeedbackAPI(service, host="127.0.0.1", port=8765)
api.start()
```

Submit streaming feedback with a simple POST request:

```bash
curl -X POST http://127.0.0.1:8765/feedback \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Compare supervised and unsupervised learning", \
        "selected_intent": "comparison", \
        "optimal_intent": "comparison", \
        "feedback": 0.96}'
```

The server replies with the updated composite-reward weights and the component
vector that was logged. Each event is processed under a lock so parallel clients
can stream feedback without clobbering the learned weights, and the new reward
weights remain simplex-projected for EXP3 compatibility.

Key parameters for `semantic-lexicon generate`:

- `--workspace PATH` – directory that contains the trained embeddings and weights (defaults to `artifacts`).
- `--persona NAME` – persona to blend into the response (defaults to the configuration's `default_persona`).
- `--config PATH` – optional configuration file to override model hyperparameters during loading.

## Adversarial Style Selection

Semantic Lexicon now bundles EXP3 helpers for experimenting with
adversarial persona *and* intent selection. The following snippet alternates
between two personas while learning from scalar feedback in ``[0, 1]``:

```python
from semantic_lexicon import AnytimeEXP3, NeuralSemanticModel, SemanticModelConfig
from semantic_lexicon.training import Trainer, TrainerConfig

config = SemanticModelConfig()
model = NeuralSemanticModel(config)
trainer = Trainer(model, TrainerConfig())
trainer.train()

bandit = AnytimeEXP3(num_arms=2)
personas = ["tutor", "researcher"]

for prompt in [
    "Outline matrix factorisation for recommendations",
    "Give journaling prompts about creativity",
    "Explain reinforcement learning trade-offs",
]:
    arm = bandit.select_arm()
    persona = personas[arm]
    response = model.generate(prompt, persona=persona)
    score = min(1.0, len(response.response.split()) / 40.0)
    bandit.update(score)
```

### Intent Selection with EXP3

We can model intent routing as an adversarial bandit problem. Let ``K`` be
the number of intents (e.g. ``{"how_to", "definition", "comparison", "exploration"}``).
At round ``t`` the system receives a prompt ``P_t`` and chooses an intent ``I_t``
using EXP3. After delivering the answer, a reward ``r_t`` in ``[0, 1]`` arrives
from explicit ratings or engagement metrics. The arm-selection probabilities are

$$
p_i(t) = (1 - \gamma) \frac{w_i(t)}{\sum_{j=1}^{K} w_j(t)} + \frac{\gamma}{K},
$$

and the weight for the played intent updates via

$$
w_{I_t}(t+1) = w_{I_t}(t) \exp\left(\frac{\gamma r_t}{K p_{I_t}(t)}\right).
$$

When the horizon ``T`` is unknown, the bundled ``AnytimeEXP3`` class applies the
doubling trick to refresh its parameters so the regret remains ``O(\sqrt{T})``.

The quickstart script demonstrates the pattern by mapping arms to intent labels
and simulating rewards from the classifier's posterior probability:

```python
from semantic_lexicon import AnytimeEXP3, NeuralSemanticModel, SemanticModelConfig
from semantic_lexicon.training import Trainer, TrainerConfig

config = SemanticModelConfig()
model = NeuralSemanticModel(config)
trainer = Trainer(model, TrainerConfig())
trainer.train()

intents = [label for _, label in sorted(model.intent_classifier.index_to_label.items())]
bandit = AnytimeEXP3(num_arms=len(intents))
prompt = "How should I start researching renewable energy?"
arm = bandit.select_arm()
intent = intents[arm]
   reward = model.intent_classifier.predict_proba(prompt)[intent]
   bandit.update(reward)
   ```

## Intent-Bandit Analysis Toolkit

The `semantic_lexicon.analysis` module supplies the maths underpinning the
improved EXP3 workflow:

- `RewardComponents` & `composite_reward` combine correctness, calibration,
  semantic, and feedback signals into the bounded reward required by EXP3.
- `estimate_optimal_weights` fits component weights via simplex-constrained least
  squares on historical interactions.
- `DirichletCalibrator` provides Bayesian confidence calibration with a
  Dirichlet prior, yielding posterior predictive probabilities that minimise
  expected calibration error.
- `simulate_intent_bandit` and `exp3_expected_regret` numerically check the
  \(2.63\sqrt{K T \log K}\) regret guarantee for the composite reward.
- `compute_confusion_correction` and `confusion_correction_residual` extract the
  SVD-based pseudoinverse that reduces systematic routing errors.
- `RobbinsMonroProcess` and `convergence_rate_bound` expose the stochastic
  approximation perspective with an \(O(1/\sqrt{n})\) convergence rate bound.

See [docs/analysis.md](docs/analysis.md) for full derivations and proofs.

### Intent Classification Objective

Ethical deployment requires robust intent understanding. Semantic Lexicon's
``IntentClassifier`` treats intent prediction as a multinomial logistic regression
problem over prompts ``(P_i, I_i)``. Given parameters ``\theta``, the model
minimises the cross-entropy loss

$$
\mathcal{L}(\theta) = -\frac{1}{N} \sum_{i=1}^{N} \log p(I_i \mid P_i; \theta),
$$

which matches the negative log-likelihood optimised during training. Improving
intent accuracy directly translates into higher-quality feedback for the bandit
loop.

## Configuration

Semantic Lexicon reads configuration files in YAML or JSON using the `SemanticModelConfig` dataclass. Example `config.yaml`:

```yaml
embeddings:
  dimension: 50
  max_words: 5000
intent:
  learning_rate: 0.2
  epochs: 5
knowledge:
  max_relations: 4
persona:
  default_persona: tutor
generator:
  temperature: 0.7
```

Load the configuration via CLI (`semantic-lexicon train --config config.yaml`) or programmatically:

```python
from semantic_lexicon import NeuralSemanticModel, load_config

config = load_config("config.yaml")
model = NeuralSemanticModel(config)
```

## Training API

```python
from semantic_lexicon import NeuralSemanticModel, SemanticModelConfig
from semantic_lexicon.training import Trainer, TrainerConfig

config = SemanticModelConfig()
model = NeuralSemanticModel(config)
trainer = Trainer(model, TrainerConfig())
trainer.train()
response = model.generate("How to learn python?", persona="tutor")
print(response.response)
```

## Diagnostics Programmatically

```python
from semantic_lexicon.model import NeuralSemanticModel
from semantic_lexicon.training import Trainer, TrainerConfig

model = NeuralSemanticModel()
trainer = Trainer(model, TrainerConfig())
trainer.train()
report = trainer.run_diagnostics()
print(report.to_dict())
```

## Development Workflow

- **Format & lint**: `ruff check .` and `black .`
- **Type check**: `mypy src`
- **Tests**: `pytest`
- **Docs**: `mkdocs serve`

A `Makefile` (or CI workflow) can orchestrate the tasks:

```bash
make lint
make test
make docs
```

## Contributing

1. Fork the repository and create a feature branch.
2. Install development dependencies: `pip install .[dev]`.
3. Run `make test` to ensure linting, typing, and tests pass.
4. Submit a pull request with detailed notes on new features or fixes.

## Acknowledgments

This work was shaped by the survey "Interpretation of Time-Series Deep Models: A Survey" [(arXiv:2305.14582)](https://arxiv.org/abs/2305.14582) shared by Dr. Zhao after reading our preprint on Calibrated "Counterfactual Conformal Fairness" (C3F) [(arXiv:2509.25295)](https://arxiv.org/abs/2509.25295). His survey offered both the conceptual framing and motivation for exploring this research path. We also thank Hamdi Alakkad and Bugra Kilictas for their pivotal contributions to our related preprints, which laid the groundwork for the developments presented here. We further acknowledge DeepSeek, whose advanced mathematical reasoning and logical inference capabilities substantially enhanced the precision and efficiency of the formal logic analysis, and the collaboration between OpenAI and GitHub on Codex, whose code generation strengths, in concert with DeepSeek’s systems, significantly accelerated and sharpened the overall development and analysis process.

## Author's Note
Hello people, or a system running perfectly, inbetween or broken -- At least working. -- While I am building groups, it is nice to see you behind them. This project represents my core self. We all came from a fixed point and would end up there as well. I am working on making myself “us,” me “our.” The physical world is for receiving and giving feelings, while the symbolic world is the projection of those feelings. Today is October 13, 2025, and I am located in Meckenheim, Germany. My plane landed yesterday from Istanbul—a nice trip, though (p.s. @farukalpayy). So, did you all feel like the energy was broken? It was the point where you get deep enough to realize where it was going. We reached the point where f(x) = x holds, but f(x) = y itself is also a point. And at this point, my request could be clarified. If this project saves you time or money, please consider sponsoring. Most importantly, it helps me keep improving and offering it free for the community. [Visit my Donation Page](https://buymeacoffee.com/farukalpay)

## Contact & Legal

- Semantic Lexicon is a Lightcap® research project distributed as open source under the Apache License 2.0; see [LICENSE](LICENSE) for details on rights and obligations.
- Lightcap® is a registered trademark (EUIPO Reg. No. 019172085).
- For enquiries, contact [alpay@lightcap.ai](mailto:alpay@lightcap.ai).
