# nxus.SYSTEMS Documentation — Full Content
## Product Summary
- nxus.SYSTEMS documentation covers products and services from nxus.SYSTEMS.
- nxusKit is a multi-engine intelligence SDK for hosted and local LLMs, CLIPS rule engines, Z3 constraint solving, Bayesian network inference, ZEN decision tables, and utility/test providers.
- nxus Codex Plugins packages Codex-ready workflows for nxusKit SDK integrations, including nxusKit Celerat.
- Current developer surfaces are Rust, Go, Python, the C ABI, and CLI/Bash workflows.
---
# nxus.SYSTEMS Documentation
URL: https://docs.nxus.systems
import { CardGrid, LinkCard } from '@astrojs/starlight/components';
## Current Entry Points
---
# Codex Plugins
URL: https://docs.nxus.systems/codex-plugins
**Codex-ready workflows for nxusKit SDK integrations and local intelligence.**
**[Install](/codex-plugins/install/)** · **[nxusKit SDK](https://github.com/nxus-SYSTEMS/nxusKit)** · **[Examples](https://github.com/nxus-SYSTEMS/nxusKit-examples)** · **[Docs](/nxuskit/)** · **[Website](https://nxus.systems)**
This repository publishes public Codex Plugin packages from [nxus.SYSTEMS](https://nxus.systems). The current plugin, **nxusKit Celerat**, helps Codex use the nxusKit SDK and nxusKit Examples to add provider-agnostic LLM integrations, symbolic reasoning, hybrid AI workflows, CLI/Bash prototypes, and public-safe local intelligence patterns to real applications.
**Current public release:** `v0.9.4-20260522`
**SDK compatibility note:** nxusKit SDK docs and packages are now `v1.0.1` GA/latest. The currently published nxusKit Celerat Codex Plugin remains `v0.9.4`-based until the refreshed plugin package has a verified install path.
nxusKit is a multi-language SDK for LLM providers, CLIPS rule engines, Z3 constraint solvers, Bayesian networks, ZEN decision tables, and JSON-first CLI automation. Celerat packages the product knowledge Codex needs to pick the right nxusKit pattern, explain Community vs. Pro boundaries before implementation, discover canonical examples through a bundled local MCP server, and verify changes using the target project's own build or smoke commands.
## Available Plugins
| Plugin | Display name | Scope |
|---|---|---|
| [`nxuskit`](/codex-plugins/nxuskit/) | nxusKit Celerat | Helps Codex implement nxusKit SDK integrations for LLMs, reasoning engines, hybrid workflows, CLI/Bash prototypes, and local intelligence workflows. |
## Primary Pages
- [Install nxusKit Celerat](/codex-plugins/install/)
- [nxusKit Celerat overview](/codex-plugins/nxuskit/)
- [Celerat task recipes](/codex-plugins/nxuskit/task-recipes/)
- [Retry and fallback recipe](/codex-plugins/nxuskit/task-recipes/04-retry-fallback/)
- [Local Ollama recipe](/codex-plugins/nxuskit/task-recipes/13-local-ollama/)
- [CLI/Bash setup recipe](/codex-plugins/nxuskit/task-recipes/14-cli-bash-setup/)
## Install
Add this repository as a Git-backed Codex Plugin marketplace pinned to the current public release:
```bash
codex plugin marketplace add nxus-SYSTEMS/nxus-codex-plugins --ref v0.9.4-20260522
```
Then open the Codex plugin directory and install **nxusKit Celerat** from the `nxus.SYSTEMS Codex Plugins` source.
See [INSTALL.md](/codex-plugins/install/) for verification and removal steps.
## What Celerat Helps With
- Add chat, streaming, structured output, tool calling, vision, retry/fallback, provider routing, and local-provider support with nxusKit.
- Migrate direct OpenAI, Anthropic, Ollama, or LiteLLM-style code toward a provider-agnostic nxusKit integration.
- Prototype workflows with `nxuskit-cli` and Bash/JSON before changing application code.
- Use bundled MCP discovery to pick canonical nxusKit examples and task recipes instead of relying on generic invention.
- Add Community Edition CLIPS guardrails around LLM recommendation workflows.
- Compare model/provider fitness with the model research harness pattern before live calls.
- Keep sensitive local files on the user's machine while returning only schema-level findings to Codex.
- Stay Community Edition-first when a request can be satisfied without Pro.
- Disclose Pro requirements before solver-backed what-if analysis, ZEN decision tables, runtime plugin loading, or other Pro-gated paths.
- Avoid in-chat secret handling by directing users to environment variables, credential stores, provider dashboards, and nxusKit auth helpers.
## Try It
After installing the plugin, start a Codex session inside a Rust, Go, Python, or CLI-oriented project and ask:
> Find the smallest nxusKit example or recipe for this repo with setup, smoke steps, and CE/Pro tier.
Other useful prompts:
> Use common-sense-guardrails to add Community CLIPS checks around an LLM recommendation workflow.
> Use model-research-harness to compare model/provider fitness with dry-run scoring before live calls.
For more task prompts, see [examples/](/codex-plugins/nxuskit/task-recipes/).
## nxusKit SDK
The plugin is a companion to the [nxusKit SDK](https://github.com/nxus-SYSTEMS/nxusKit), not a replacement for it. Install nxusKit when you are ready to build and run application code:
- [nxusKit documentation](/nxuskit/)
- [Getting started](/nxuskit/getting-started/installation/)
- [nxusKit Examples](https://github.com/nxus-SYSTEMS/nxusKit-examples)
- [CLI reference](/nxuskit/reference/cli-reference/)
Community Edition workflows are available for many LLM, local-provider, CLIPS, Bayesian, and CLI/Bash use cases. Some solver, ZEN, runtime plugin, and advanced workflow capabilities require nxusKit Pro; Celerat is designed to call that out before Codex generates Pro-dependent code.
## Contributing
Public contributions should focus on shipped plugin behavior, installation clarity, prompt examples, documentation, and reproducible validation. See [CONTRIBUTING.md](https://github.com/nxus-SYSTEMS/nxus-codex-plugins/blob/main/CONTRIBUTING.md).
## License
This repository is dual-licensed under MIT or Apache 2.0, at your option. See [LICENSE](https://github.com/nxus-SYSTEMS/nxus-codex-plugins/blob/main/LICENSE), [LICENSE-MIT](https://github.com/nxus-SYSTEMS/nxus-codex-plugins/blob/main/LICENSE-MIT), and [LICENSE-APACHE](https://github.com/nxus-SYSTEMS/nxus-codex-plugins/blob/main/LICENSE-APACHE).
Copyright 2025-2026 nxus.SYSTEMS LLC.
---
# Install nxusKit Celerat
URL: https://docs.nxus.systems/codex-plugins/install
This repository publishes Codex Plugin packages from nxus.SYSTEMS. The current public plugin is **nxusKit Celerat** `v0.9.4-20260522`.
nxusKit SDK docs and packages are now `v1.0.1` GA/latest. The currently published Celerat plugin remains `v0.9.4`-based until the refreshed plugin package has a verified install path.
## Requirements
- Codex app or Codex CLI with plugin support.
- Network access to GitHub for Git-backed marketplace installation.
- Python 3.11+ for the bundled local MCP discovery server.
- nxusKit SDK only when you are ready to build or run nxusKit application code. The Codex Plugin itself does not install the SDK.
## Add the Marketplace
Add the public marketplace at the current release tag:
```bash
codex plugin marketplace add nxus-SYSTEMS/nxus-codex-plugins --ref v0.9.4-20260522
```
Then open the Codex plugin directory and install **nxusKit Celerat** from the `nxus.SYSTEMS Codex Plugins` source.
## Verify the Plugin
Start a new Codex session in a project that can use nxusKit, then ask:
> Find the smallest nxusKit example or recipe for this repo with setup, smoke steps, and CE/Pro tier.
Codex should inspect the project before editing, consult the bundled local MCP server when available, choose a Community Edition path when it fits, avoid asking for secrets in chat, and recommend a project-local verification command.
For a CLI/Bash-first check, ask:
> Use nxuskit-cli to verify my setup before we implement SDK code.
The plugin should guide Codex to probe `nxuskit-cli` availability and use JSON-first setup or smoke commands when supported.
For an MCP package self-check from an installed plugin directory:
```bash
cd /mcp
python3 -m pip install -e .
python -m nxuskit_celerat.mcp --self-check
```
## Remove the Marketplace
```bash
codex plugin marketplace remove nxus-codex-plugins
```
Plugin install and uninstall are handled from the Codex plugin directory UI in current Codex builds. The command above removes the marketplace source from your Codex configuration.
---
# nxusKit Celerat
URL: https://docs.nxus.systems/codex-plugins/nxuskit
nxusKit Celerat is a Codex Plugin for accelerating nxusKit SDK integrations across LLMs, symbolic reasoning, hybrid AI workflows, CLI/Bash prototypes, and public-safe local intelligence patterns in Rust, Go, Python, and Bash.
## v0.9.4 — current release
nxusKit SDK docs and packages are now `v1.0.1` GA/latest. This currently published Celerat plugin remains `v0.9.4`-based until the refreshed plugin package has a verified install path.
v0.9.4 includes:
- **A local read-only Model Context Protocol (MCP) server** under `mcp/` (Python stdio; **requires Python 3.11+**) that lets Codex discover canonical nxusKit examples and CLI/Bash recipes from a bundled offline metadata snapshot — no cloud microservice, no live cross-repo querying.
- **CLI/Bash recipes** with declared input/output JSON schemas and smallest-safe smoke commands.
- **Public-safe local intelligence patterns** for Codex-supervised nxusKit pipelines that process sensitive files locally and return only schema-level findings to Codex.
- **A PHI boundary** — schema-level outputs only for `phi-sensitive` recipes, with explicit `correlation_handle` passthrough; remote-MCP and cloud-model PHI requests are refused with clear disclosures.
Persona-specific recipes and fixtures are not part of the public plugin.
If the MCP fails to start, Codex falls back to the bundled reference index with a visible "MCP unavailable" message.
## Key Pages
- [Install nxusKit Celerat](/codex-plugins/install/)
- [Task recipes](/codex-plugins/nxuskit/task-recipes/)
- [Streaming Rust recipe](/codex-plugins/nxuskit/task-recipes/01-streaming-rust/)
- [Structured JSON Python recipe](/codex-plugins/nxuskit/task-recipes/02-structured-json-python/)
- [Retry and fallback recipe](/codex-plugins/nxuskit/task-recipes/04-retry-fallback/)
- [CLI/Bash setup recipe](/codex-plugins/nxuskit/task-recipes/14-cli-bash-setup/)
## Scope
This plugin ships:
- one Codex Plugin manifest at `.codex-plugin/plugin.json` (now declares an `mcpServers` block)
- one primary skill at `skills/nxuskit/SKILL.md` (MCP awareness, PHI boundary, and public-safe local intelligence guidance)
- curated reference docs under `skills/nxuskit/references/`
- the MCP server package under `mcp/`
- plugin assets under `assets/`
## Codex Plugins vs. nxusKit Runtime Plugins
These are distinct product surfaces:
- Codex Plugins package skills, references, MCP servers, and install metadata for OpenAI Codex.
- nxusKit runtime plugins are signed shared-library SDK extensions loaded by nxusKit itself.
This plugin helps developers and knowledge-work analysts use nxusKit through Codex. It is not a nxusKit runtime plugin.
## Install
Install the pinned public release:
```bash
codex plugin marketplace add nxus-SYSTEMS/nxus-codex-plugins --ref v0.9.4-20260522
```
Then install `nxusKit Celerat` from the Codex plugin directory.
The MCP server requires Python 3.11+ on PATH. After install, the first launch may prompt to install the MCP package; alternately, install ahead of time:
```bash
cd /mcp
python3 -m pip install -e .
python -m nxuskit_celerat.mcp --self-check # expect "ok"
```
## Verify
Ask Codex:
> Find me the smallest nxusKit streaming-chat example with retry and provider fallback.
The skill should:
- inspect your project before editing
- consult the local MCP first (if available) for canonical examples
- fall back gracefully to the bundled reference index if the MCP is unavailable
- choose a Community Edition example when it satisfies the request
- read credentials from environment variables or credential stores, never from chat
- recommend a verification step that fits your project
- disclose nxusKit Pro requirements before generating Pro-dependent code
## Logs
The MCP writes structured logs to `~/.nxuskit-celerat/logs/`. Nothing is written outside that directory.
## Remove
```bash
codex plugin marketplace remove nxus-codex-plugins
```
Plugin install and uninstall are handled from the Codex plugin directory in current Codex builds. The CLI command above removes the marketplace source if you added it directly.
## License
`MIT OR Apache-2.0`.
## See also
- `mcp/README.md` — MCP-side install, run, and troubleshooting
- `skills/nxuskit/references/mcp-overview.md` — how Codex uses MCP discovery and fallback
---
# Task Recipes
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes
Each recipe includes:
- a prompt to give Codex
- a good starter fixture
- the expected plugin behavior
- tier and secret-handling boundaries
- verification commands to ask Codex to run or recommend
The recipes are written for users who want to see what high-quality Codex behavior looks like when the nxusKit Celerat plugin is installed.
## Recipe Directory
- [Streaming Rust](/codex-plugins/nxuskit/task-recipes/01-streaming-rust/)
- [Structured JSON Python](/codex-plugins/nxuskit/task-recipes/02-structured-json-python/)
- [Multi-provider Go](/codex-plugins/nxuskit/task-recipes/03-multi-provider-go/)
- [Retry and fallback](/codex-plugins/nxuskit/task-recipes/04-retry-fallback/)
- [Community Edition rule validation](/codex-plugins/nxuskit/task-recipes/05-ce-rule-validation/)
- [Pro solver what-if](/codex-plugins/nxuskit/task-recipes/06-pro-solver-what-if/)
- [Migrate OpenAI Python](/codex-plugins/nxuskit/task-recipes/07-migrate-openai-python/)
- [Vision capability detection](/codex-plugins/nxuskit/task-recipes/08-vision-capability-detection/)
- [ZEN decision table](/codex-plugins/nxuskit/task-recipes/09-zen-decision-table/)
- [Community Edition options](/codex-plugins/nxuskit/task-recipes/10-community-edition-options/)
- [Bayesian solver CLIPS](/codex-plugins/nxuskit/task-recipes/11-bayesian-solver-clips/)
- [Post-activation Pro](/codex-plugins/nxuskit/task-recipes/12-post-activation-pro/)
- [Local Ollama](/codex-plugins/nxuskit/task-recipes/13-local-ollama/)
- [CLI/Bash setup](/codex-plugins/nxuskit/task-recipes/14-cli-bash-setup/)
---
# Streaming Chat In Rust
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/01-streaming-rust
Prompt:
```text
Use nxusKit to add streaming chat to this Rust CLI.
```
Starter fixture: `examples/fixtures/starters/rust-cli/`
Expected behavior:
- Inspect `Cargo.toml` and `src/main.rs` before editing.
- Consult the `streaming` row in the nxusKit example index.
- Prefer Community Edition paths.
- Add a small CLI that supports a no-secret smoke path such as loopback or local Ollama.
- Read cloud-provider credentials only from environment variables.
Verification:
```bash
cargo check
cargo run -- "Say hello from nxusKit streaming."
```
Good result:
- The project builds.
- The command prints streamed content or a clear local-provider prerequisite.
- No credential is requested in chat.
---
# Structured JSON Output In Python
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/02-structured-json-python
Prompt:
```text
Use nxusKit to add structured JSON output to this Python app.
```
Starter fixture: `examples/fixtures/starters/python-app/`
Expected behavior:
- Inspect `pyproject.toml` and the package layout before editing.
- Consult the `structured-output` example.
- Add a typed schema plus validation.
- Keep provider configuration in environment variables or project config.
- Include an offline or fixture-driven parsing smoke if a model is unavailable.
Verification:
```bash
python -m py_compile src/example_app/__init__.py src/example_app/__main__.py
python -m example_app --provider offline
```
Good result:
- The output is valid JSON that matches the declared schema.
- Real provider use is optional and explicitly configured.
---
# OpenAI Plus Ollama In Go
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/03-multi-provider-go
Prompt:
```text
Use nxusKit to make this Go service support OpenAI and Ollama.
```
Starter fixture: `examples/fixtures/starters/go-service/`
Expected behavior:
- Inspect `go.mod` and `main.go`.
- Consult the `multi-provider` example.
- Preserve existing command-line behavior.
- Add provider selection for OpenAI and Ollama.
- Read `OPENAI_API_KEY` only from the environment.
- Use local-provider settings such as `OLLAMA_BASE_URL` and `OLLAMA_MODEL`.
Verification:
```bash
go test ./...
go run . -provider ollama -prompt "Reply in one short sentence."
```
Good result:
- The Go package tests pass.
- Ollama works without cloud credentials when it is running locally.
---
# Retry And Fallback
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/04-retry-fallback
Prompt:
```text
Use nxusKit Examples to find the smallest retry/fallback example and implement that pattern here.
```
Starter fixture: any fixture with an existing provider call; `examples/fixtures/starters/go-service/` is a good target.
Expected behavior:
- Inspect the current provider call first.
- Consult the `retry-fallback` example.
- Implement the smallest fallback chain that fits the project.
- Preserve existing provider flags and environment variables.
- Add tests for first-provider success, fallback success, all-fail, and empty-chain cases when the project has test coverage.
Verification:
```bash
go test ./...
go run . -provider fallback -prompt "Confirm fallback."
```
Good result:
- Failed providers are reported clearly.
- The first successful provider response is returned.
---
# Community Edition Rule Validation
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/05-ce-rule-validation
Prompt:
```text
Use nxusKit Community Edition to add rule-based validation to this workflow.
```
Starter fixture: `examples/fixtures/starters/python-app/`
Expected behavior:
- Identify the current data or model-output shape.
- Consult `clips-basics` or `clips-llm-hybrid`.
- Explain that basic CLIPS rule evaluation is Community Edition.
- Add deterministic validation after extraction or classification.
- Avoid solver, ZEN, runtime plugin loading, and other Pro-gated features unless the user asks for them.
Verification:
```bash
python -m py_compile src/example_app/__init__.py
python -m example_app --provider offline --validate-rules
```
Good result:
- The rule validation emits pass/review/fail status.
- The model-output schema and rule facts are easy to inspect.
---
# Pro Solver What-If Planner
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/06-pro-solver-what-if
Prompt:
```text
Use nxusKit Pro to add a solver-backed what-if planner.
```
Starter fixture: `examples/fixtures/starters/go-service/`
Expected behavior:
- Show the Pro disclosure block before generating solver-dependent code.
- Offer a Community Edition alternative if constraint solving is not required.
- Probe `nxuskit-cli --version`.
- Run or recommend `nxuskit-cli license status --json` before continuing.
- Generate solver code only after the user has an eligible trial or license and Pro status is verified.
Verification:
```bash
nxuskit-cli license status --json
go test -tags nxuskit ./...
go run -tags nxuskit . -planner
```
Good result:
- Base and what-if scenarios are reported separately.
- Unsatisfiable scenarios are handled explicitly.
- No Pro code appears before disclosure.
---
# Migrate Direct OpenAI Usage
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/07-migrate-openai-python
Prompt:
```text
Migrate this OpenAI-only integration to nxusKit without changing app behavior.
```
Starter fixture: `examples/fixtures/starters/direct-openai-python/`
Expected behavior:
- Inspect imports, client construction, model selection, message shape, retry behavior, and public function signatures.
- Present a preserved-behavior contract before editing.
- Keep `OPENAI_API_KEY` and `OPENAI_MODEL` conventions unless the project already uses different names.
- Replace direct provider SDK calls with nxusKit provider calls.
- Avoid adding new abstractions that the project did not need.
Verification:
```bash
python -m py_compile app.py
python -c "import inspect, app; print(inspect.signature(app.summarize))"
```
Good result:
- The public API remains `summarize(text: str) -> str`.
- No direct OpenAI SDK import remains in the implementation.
---
# Vision With Capability Detection
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/08-vision-capability-detection
Prompt:
```text
Add vision support with nxusKit and verify model capability detection.
```
Starter fixture: `examples/fixtures/starters/go-service/`
Expected behavior:
- Consult `vision` and `capability-detection`.
- Treat vision as Community Edition when the provider/model supports it.
- Add image input through URL or base64.
- Check model-level capabilities when available, then provider-level capabilities.
- Include a tiny local image fixture or documented image input so smoke testing does not depend on a random external URL.
Verification:
```bash
go test ./...
go run . -provider ollama -model llama3.2-vision:latest -vision
```
Good result:
- The app refuses text-only models clearly.
- A vision-capable model receives an image and returns content.
---
# ZEN Decision Table Workflow
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/09-zen-decision-table
Prompt:
```text
Use nxusKit for a ZEN decision table workflow.
```
Starter fixture: `examples/fixtures/starters/cli-bash-workspace/`
Expected behavior:
- Show the ZEN Pro disclosure block before generating ZEN-dependent code.
- Probe `nxuskit-cli` and the relevant subcommand help before use.
- Verify license status before running ZEN.
- Create JSON fixtures for the decision model, input, and expected output.
- Use `jq` or another structured JSON tool instead of ad hoc string parsing.
Verification:
```bash
jq empty data/zen/decision-model.json data/zen/input.json data/zen/expected-output.json
bash -n scripts/zen-decision.sh
bash scripts/zen-decision.sh
```
Good result:
- The script exits non-zero if Pro status or expected output is missing.
- The result matches the expected decision output.
---
# Community Edition Options
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/10-community-edition-options
Prompt:
```text
I do not have a Pro license. What can we still implement with Community Edition?
```
Starter fixture: any project.
Expected behavior:
- Treat "no Pro license" as a hard boundary.
- Enumerate CE-suitable workflows: chat, streaming, structured output, tool calling when supported, vision when supported, retry/fallback, routing, local providers, direct-provider migration to CE targets, basic CLIPS, CLIPS plus LLM validation, Bayesian inference within CE limits, and CLI/Bash prototypes for CE capabilities.
- Offer CE alternatives for solver, what-if, ZEN, and solver-containing hybrid workflows.
- Do not generate Pro-dependent code.
Verification:
No code change is required. Review the answer for tier correctness and absence of Pro implementation.
Good result:
- The response gives a useful CE path forward without upsell pressure or hidden Pro dependencies.
---
# Bayesian Solver CLIPS Hybrid
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/11-bayesian-solver-clips
Prompt:
```text
Combine a Bayesian forecast with solver optimization and CLIPS safety rules.
```
Starter fixture: `examples/fixtures/starters/cli-bash-workspace/`
Expected behavior:
- Label stages before implementation: Bayesian is CE, solver is Pro, CLIPS validation is CE.
- Show the `BN -> solver -> CLIPS pipeline` Pro disclosure before solver work.
- Verify license status before the solver stage.
- Use structured JSON and explicit stage outputs.
- Keep the CLIPS validation independent enough to inspect without re-running the model.
Verification:
```bash
jq empty data/hybrid/bn-input.json
bash -n scripts/bn-solver-clips.sh
bash scripts/bn-solver-clips.sh
```
Good result:
- The script prints each tier-labeled stage.
- Solver output feeds CLIPS validation.
- The final validation status is explicit.
---
# Continue After License Activation
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/12-post-activation-pro
Prompt:
```text
I have activated my license now. Continue with the solver-backed what-if planner.
```
Starter fixture: the same project used for the original Pro request.
Expected behavior:
- Do not take the user's statement alone as proof of active Pro status.
- Run or recommend `nxuskit-cli license status --json` before continuing.
- Continue only when status is valid and the needed feature is present.
- If status is not valid, stop at the boundary and provide the recovery command.
Verification:
```bash
nxuskit-cli license status --json
```
Good result:
- Pro work resumes only after status verification.
- The user gets a clear next step if activation did not take effect.
---
# Local Ollama Through nxusKit
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/13-local-ollama
Prompt:
```text
Use local Ollama through nxusKit for this app.
```
Starter fixture: `examples/fixtures/starters/local-provider-python/`
Expected behavior:
- Preserve existing local-provider environment variable names when present.
- Treat local-provider support as Community Edition.
- Use `OLLAMA_BASE_URL`, `OLLAMA_MODEL`, or project-local equivalents.
- Do not ask for cloud credentials.
- Add a clear error if Ollama is not reachable.
Verification:
```bash
python -m py_compile app.py
python app.py
```
Good result:
- The app prints the provider configuration and returns content from local Ollama.
- Missing Ollama setup produces an actionable message.
---
# CLI Bash Prototypes And Setup Checks
URL: https://docs.nxus.systems/codex-plugins/nxuskit/task-recipes/14-cli-bash-setup
Prompt:
```text
Use nxuskit-cli to prototype this workflow as a Bash/JSON pipeline before adding app code.
```
Follow-up setup prompt:
```text
Use nxuskit-cli provider and license status checks to verify my setup before we implement SDK code.
```
Starter fixture: `examples/fixtures/starters/cli-bash-workspace/`
Expected behavior:
- Probe `nxuskit-cli --help` and `nxuskit-cli --version` before recommending subcommands.
- Probe subcommand help before use.
- Prefer JSON input and output.
- Use `jq` or structured parsing.
- Avoid arbitrary `bash -c` wrappers.
- Avoid printing credentials or asking for secrets.
Verification:
```bash
nxuskit-cli --help
nxuskit-cli --version
nxuskit-cli provider status --json
nxuskit-cli license status --json
bash scripts/json-call-prototype.sh
```
Good result:
- Provider status and license status are visible before SDK code is changed.
- The CLI prototype can be inspected and rerun.
---
# GitHub Repositories
URL: https://docs.nxus.systems/github
The public nxus.SYSTEMS GitHub organization is
[github.com/nxus-SYSTEMS](https://github.com/nxus-SYSTEMS).
## Public Repositories
| Repository | What to use it for |
| --- | --- |
| [nxusKit SDK](https://github.com/nxus-SYSTEMS/nxusKit) | Source for the multi-language SDK covering LLM providers, rule engines, constraint solving, Bayesian networks, decision tables, the C ABI, and CLI/Bash workflows. |
| [nxusKit Examples](https://github.com/nxus-SYSTEMS/nxusKit-examples) | Runnable Rust, Go, Python, and CLI/Bash examples for common nxusKit integration patterns. |
| [nxus Codex Plugins](https://github.com/nxus-SYSTEMS/nxus-codex-plugins) | Codex Plugin packages from nxus.SYSTEMS, including nxusKit Celerat. |
| [nxus Docs](https://github.com/nxus-SYSTEMS/nxus-docs) | Source for this public documentation site, hosted at [docs.nxus.systems](https://docs.nxus.systems/). |
## Related Links
- [nxusKit documentation](/nxuskit/)
- [nxusKit examples documentation](/nxuskit/examples/)
- [Codex Plugins documentation](/codex-plugins/)
- [Commercial website](https://nxus.systems/)
- [Field Notes](https://nxus.systems/field-notes)
- [Voice / Question of the Fortnight](https://nxus.systems/voice)
- [Plans](https://nxus.systems/pricing)
---
# nxusKit SDK
URL: https://docs.nxus.systems/nxuskit
nxusKit is a unified, type-safe SDK for calling LLM providers (Claude, OpenAI, Ollama, and more),
CLIPS rule engines, Z3 constraint solvers, Bayesian networks, and ZEN decision tables — from Rust, Go, Python, and the C ABI.
## Start Here
Install the SDK, configure credentials, and run your first request:
- [Installation](/nxuskit/getting-started/installation/)
- [First Call](/nxuskit/getting-started/first-call/)
- [Authentication](/nxuskit/getting-started/authentication/)
## Browse by Task
- **Build an integration** — Start with [installation](/nxuskit/getting-started/installation/), then use the [provider model](/nxuskit/concepts/provider-model/) to choose the right backend.
- **Explore working code** — Browse [examples](/nxuskit/examples/) for reusable patterns, local model setup, solver workflows, and complete applications.
- **Author rules** — Use the [CLIPS rule authoring guide](/nxuskit/guides/clips-rule-authoring/) and the [CLIPS session API](/nxuskit/reference/api-reference/#clips-session-api).
- **Look up contracts** — Use the [API reference](/nxuskit/reference/api/), [C ABI reference](/nxuskit/reference/api-reference/), [CLI reference](/nxuskit/reference/cli-reference/), and [provider references](/nxuskit/reference/providers/cloud-llms/).
- **Manage editions** — Review [feature tiers](/nxuskit/concepts/tier-system/) and [license activation](/nxuskit/concepts/licensing/).
- **Use Codex workflows** — Install [nxusKit Celerat](/codex-plugins/nxuskit/) and browse [task recipes](/codex-plugins/nxuskit/task-recipes/) for Codex-ready implementation prompts.
---
# Architecture
URL: https://docs.nxus.systems/nxuskit/concepts/architecture
## Overview
nxusKit is organized around a shared provider model with language-specific
wrappers for Rust, Go, and Python, plus a stable C ABI. Each wrapper exposes
native types while keeping the same core concepts: provider configuration, chat
requests, chat responses, streaming chunks, and structured error handling.
The architecture has four practical layers:
1. **Language wrappers** — Idiomatic SDK surfaces for application code.
2. **Provider abstraction** — A common contract for chat, streaming, capability
discovery, and provider metadata.
3. **Provider implementations** — Cloud LLMs, local LLMs, CLIPS, Z3, Mock,
Loopback, and MCP adapters.
4. **Native boundary** — C ABI functions and ownership rules for embedding and
cross-language integration.
## Component Map
| Component | Role |
|-----------|------|
| Rust SDK | Reference implementation, async provider interface, CLI, and native engine integrations. |
| Go SDK | Go-native provider interface with context cancellation and channel-based streaming. |
| Python SDK | Python-friendly provider creation, chat calls, and FFI access. |
| C ABI | Stable native boundary for providers, responses, streams, errors, and CLIPS sessions. |
| CLI | Shell interface for chat, provider checks, structured JSON workflows, and Pro features. |
| Examples | Runnable patterns and applications that demonstrate cross-language usage. |
## Provider Families
nxusKit providers fall into four broad groups:
| Family | Examples | Behavior |
|--------|----------|----------|
| Cloud LLMs | OpenAI, Anthropic, Groq, Mistral, Fireworks, Together, OpenRouter, Perplexity | Hosted model APIs with provider-specific capabilities. |
| Local LLMs | Ollama, LM Studio, in-process GGUF backends | Local inference for development, privacy, or low-latency use cases. |
| Deterministic engines | CLIPS, Z3 | Repeatable rule evaluation, inference, constraint solving, and optimization. |
| Utility providers | Mock, Loopback, MCP | Testing, integration checks, and tool-oriented workflows. |
See the [Provider Model](/nxuskit/concepts/provider-model/) for the shared
configuration and request flow.
## Cross-Language Design
The SDK keeps concepts aligned across languages:
| Concept | Rust | Go | C ABI |
|---------|------|----|-------|
| Provider configuration | `ProviderConfig` | `ProviderConfig` | provider config JSON |
| Chat request | `ChatRequest` | `ChatRequest` | request JSON |
| Chat response | `ChatResponse` | `ChatResponse` | response handle + JSON |
| Streaming | async stream | channel stream | callback stream |
| Errors | typed errors | typed errors | `nxuskit_last_error()` |
This lets teams choose a language per service without redesigning provider
selection, request structure, credentials, or feature-gating behavior.
## Native Boundary
The C ABI is the stable integration point for native consumers and higher-level
FFI wrappers. It uses opaque handles for providers, responses, and streams. Any
memory returned across the boundary has a matching free function.
Read the [C ABI Reference](/nxuskit/reference/api-reference/) before embedding
nxusKit in C, C++, Go FFI, Python FFI, or another native runtime.
## Operational Flow
```text
Application code
-> language wrapper or C ABI
-> provider configuration
-> chat or streaming request
-> provider implementation
-> response, chunks, metadata, or typed error
```
For Pro features, the same call path also checks license state before executing
the feature. Community-tier features continue to run without a license token.
## What to Read Next
- [Installation](/nxuskit/getting-started/installation/)
- [Provider Model](/nxuskit/concepts/provider-model/)
- [Streaming](/nxuskit/guides/streaming/)
- [C ABI Reference](/nxuskit/reference/api-reference/)
- [CLI Input Format Reference](/nxuskit/reference/cli-reference/)
- [Examples](/nxuskit/examples/)
---
# Licensing
URL: https://docs.nxus.systems/nxuskit/concepts/licensing
## Overview
nxusKit Pro features require a valid license token. This guide covers the
full lifecycle: authentication, activation, deployment, renewal, and
deactivation.
## Quick Start
```bash
# 1. Authenticate with your nxus.systems account
nxuskit-cli license login
# 2. Activate with your Purchase ID / Activation Key from My Products
nxuskit-cli license activate --key --accept-eula
# 3. Accept the End User License Agreement (required once per machine)
nxuskit-cli --accept-eula
# Or pre-accept for CI/CD (see EULA Acceptance below)
# 4. Verify activation
nxuskit-cli license status
# 5. Use Pro features — they just work
```
## EULA Acceptance
nxusKit requires acceptance of the End User License Agreement (EULA) before
use. Acceptance is recorded once per machine and persists across sessions.
### Interactive (TTY)
When running in an interactive terminal, the CLI prompts you to accept the EULA
on first use:
```
nxusKit End User License Agreement
...
Do you accept the EULA? [y/N]:
```
Type `y` and press Enter to accept. Acceptance is stored at
`~/.config/nxuskit/eula_accepted` (mode `0600`).
### Non-interactive (CI/CD)
In non-TTY environments (CI runners, Docker, scripts), the interactive prompt is
suppressed and the CLI exits with an error if the EULA has not been pre-accepted.
**Option 1 — `--accept-eula` flag** (recommended for CI):
```bash
nxuskit-cli --accept-eula license status
```
The flag is accepted on any subcommand. In GitHub Actions:
```yaml
- name: Verify license
run: nxuskit-cli --accept-eula license status
env:
NXUSKIT_LICENSE_TOKEN: ${{ secrets.NXUSKIT_LICENSE_TOKEN }}
```
**Option 2 — Pre-write the acceptance file**:
Create the file before invoking the CLI (useful in container image builds):
```bash
mkdir -p ~/.config/nxuskit
echo "accepted" > ~/.config/nxuskit/eula_accepted
chmod 0600 ~/.config/nxuskit/eula_accepted
```
### Acceptance File
| Path | `~/.config/nxuskit/eula_accepted` |
|------|-----------------------------------|
| Permissions | `0600` (owner read/write only) |
| Content | `accepted` (literal string) |
| Created by | Interactive prompt or `--accept-eula` flag |
---
## Licensing Environments
Release builds default to the production licensing API:
```
https://nxus.systems/licensing-api/v1
```
The production ES256 public key is embedded in release builds. Standard users do not configure the key or endpoint.
Development and test lanes may opt into a non-production endpoint with
`NXUSKIT_LICENSE_SERVER` and may label that lane with
`NXUSKIT_LICENSE_ENVIRONMENT`. These overrides are visible in
`nxuskit-cli license status --json` under `licensing.endpoint`,
`licensing.environment`, and `licensing.signing_key`; they are not silent
fallbacks.
## Offline-First Entitlements
After activation, Pro-gated entitlement checks validate the cached token
locally: signature, expiry, machine binding, product id, edition, and
entitlement claims are checked without contacting the licensing API. The
licensing API is contacted for activation, explicit refresh/sync, or recovery
from a local validation failure.
---
## Token Types
The SDK manages five token shapes:
| Token | Storage | Purpose | Expiry | Machine-bound? |
|-------|---------|---------|--------|----------------|
| **Auth** | `~/.config/nxuskit/auth.json` | Authenticates you with the licensing service | 30 days | No |
| **Developer** | `~/.nxuskit/license.token` | Authorizes purchased Pro SDK features for local developer workstations after storefront checkout | Subscription period | Yes (up to 3 machines) |
| **Deployment** | `NXUSKIT_LICENSE_TOKEN` env var | Authorizes customer shipping/runtime use of products that embed or depend on nxusKit | Never expires | No (org-scoped) |
| **Real Purchase** | `~/.nxuskit/license.token` | Backward-compatible SDK fixture/claim shape; production storefront activations currently issue Developer tokens | Subscription period | Yes |
| **Leased** | `~/.nxuskit/license.token` or `NXUSKIT_LICENSE_TOKEN` | CI/automation license that can be revoked server-side | Short lease, default 72 hours | Yes |
For CI automations that need a working Pro license but also need routine
revocation control, prefer a leased activation key over a long-lived deployment
token. Re-run `nxuskit-cli license activate --key
--accept-eula` on the runner before the 72-hour lease
expires. If the lease is blocked server-side, reactivation fails and any
already-issued token lapses at its normal `exp`.
## Step-by-Step Activation
### 1. Authenticate
Before activating a license, you must authenticate with your nxus.systems
account:
```bash
nxuskit-cli license login
```
This opens your browser to the nxus.systems login page. After logging in,
enter the code shown in your terminal. The auth token is stored at
`~/.config/nxuskit/auth.json` and used automatically for subsequent commands.
Check auth status:
```bash
nxuskit-cli license status
```
### 2. Activate
With authentication complete, activate your license. First-time activations
must accept the EULA:
```bash
nxuskit-cli license activate --key --accept-eula --json
```
The `--accept-eula` flag is recorded in
`~/.config/nxuskit/eula_accepted` (mode `0600`); subsequent activations on
the same machine do not need to repeat it. The `--json` flag is recommended
for scripting — see the JSON output schema in §3.
On success you will see (text mode):
```
Activated. 1/3 machines used.
Token stored: ~/.nxuskit/license.token
```
The license token is stored locally and validated on each SDK
initialization. **Activation uses an extended 30s client timeout
(`EXTENDED_TIMEOUT_SECS = 30`)** to absorb production cold-starts; the
matching proxy timeout extension is in
`nxus_device_auth/services/proxy_client.py::EXTENDED_TIMEOUT_PATHS`.
#### Real-purchase activation (production)
After purchasing a license at `https://nxus.systems/shop`, your purchase
IDs appear at `https://nxus.systems/my/products`. Each card shows the
exact CLI to run:
```bash
nxuskit-cli license activate --key nxus_purchase_ --accept-eula --json
```
Production storefront purchases currently issue `developer` license tokens:
machine-bound, seat-indexed, and valid through the commercial subscription
period. The SDK also accepts the legacy/fixture `real_purchase` claim shape for
compatibility, but it is not the production storefront issuer contract.
Customer shipping/runtime use belongs to the separate `deployment` token flow.
`leased` tokens are designed for CI/automation where revocation control matters — re-activate before the default 72-hour expiry;
blocking the lease server-side prevents future activations and existing tokens
lapse at `exp`.
### 3. Verify
Check your license status at any time:
```bash
nxuskit-cli license status
```
Output includes token type, edition, expiry date, machine count, licensing
environment, endpoint, and signing-key metadata.
For JSON output (useful in scripts):
```bash
nxuskit-cli license status --json
```
### 4. Use Pro Features
Once activated, Pro features work transparently:
```python
# Python — ZEN decision tables (Pro)
from nxuskit import zen_evaluate
result = zen_evaluate(table_path, input_data)
# Python — Solver (Pro)
from nxuskit import SolverConfig
```
```rust
// Rust — ZEN evaluation (Pro)
let result = nxuskit::zen_evaluate(&table, &input)?;
```
```go
// Go — Solver (Pro)
session, err := nxuskit.NewSolverSession(config)
```
## Trial Activation
To start a 30-day Pro trial, first register for an account and authenticate:
```bash
nxuskit-cli license login
nxuskit-cli license activate --trial
```
The trial provides full Pro-tier access for 30 days.
## Deployment Tokens
Deployment tokens are designed for production, CI/CD, and containerized
environments. They have no expiry and no machine binding.
### Setup
Set the deployment token as an environment variable:
```bash
export NXUSKIT_LICENSE_TOKEN=""
```
This works for:
- CI/CD pipelines (GitHub Actions, GitLab CI, Jenkins)
- Docker containers
- Kubernetes pods
- Production servers
- Serverless functions
### Version Ceiling
Deployment tokens include a **version ceiling** (e.g., `1.0`). The token
is valid for any SDK version at or below that ceiling:
- Token ceiling `1.0` → works with v1.0.0 and patch releases such as v1.0.5
- Token ceiling `1.0` → does NOT work with v1.1.0+
When you upgrade the SDK past the ceiling, you will see:
```
Deployment token covers up to v1.0.x. Update your deployment token for v1.1+ support.
```
Organizations with active support subscriptions receive updated deployment
tokens when new major.minor versions are released.
## Token Resolution Chain
The SDK resolves tokens from multiple sources in this precedence order:
| Priority | Source | Use Case |
|----------|--------|----------|
| 1 (highest) | `NXUSKIT_LICENSE_TOKEN` env var | CI/CD, containers |
| 2 | `~/.nxuskit/license.token` file | Local development |
| 3 (lowest) | API parameter | Embedded / programmatic |
The first valid token found is used. This order is the same for static and
dynamic linking modes.
## Multiple Machines
Each developer license supports up to 3 machine activations:
```bash
# Activate on machine 1
nxuskit-cli license activate --key
# → Activated. 1/3 machines used.
# Activate on machine 2
nxuskit-cli license activate --key
# → Activated. 2/3 machines used.
# If all 3 slots are used, deactivate one first:
nxuskit-cli deactivate
# → Deactivated. 2/3 machines used.
```
## Renewal
When your subscription approaches expiry (7 days out), the SDK logs a
once-per-session reminder:
```
Pro license expires in 7 days. Renew at your account dashboard.
```
After expiry, Pro features return:
```
License installation required.
```
Community features continue working without interruption.
## Deactivation
To free a machine activation slot:
```bash
nxuskit-cli deactivate
```
The local token file is removed and the activation count is decremented.
To revoke your auth session:
```bash
nxuskit-cli license logout
```
## Troubleshooting
| Symptom | Cause | Fix |
|---------|-------|-----|
| `License installation required.` | No valid license token found | Run `nxuskit-cli license login`, then `nxuskit-cli license activate --key ` |
| `LicenseExpired` | Subscription lapsed | Renew at your account dashboard |
| `EditionInsufficient` | Community binary | Download Pro binary |
| `VersionCeilingExceeded` | SDK upgraded past token ceiling | Request updated deployment token |
| `FeatureUnavailable` | Multiple possible causes | Run `nxuskit-cli license status` for details |
| Auth token expired | 30-day auth session ended | Run `nxuskit-cli license login` again |
---
# Provider Model
URL: https://docs.nxus.systems/nxuskit/concepts/provider-model
## Overview
nxusKit presents LLMs, local inference servers, rule engines, solvers, and test
adapters through one provider interface. Your application chooses a
`provider_type`, sends a `ChatRequest`, and receives a structured response. The
same request/response pattern works whether the backend is OpenAI, Anthropic,
Ollama, CLIPS, Z3, Mock, or Loopback.
The goal is portability: application code can switch providers without changing
its surrounding orchestration, logging, retry, or licensing logic.
## Provider Types
| Category | Provider types | Use when |
|----------|----------------|----------|
| Cloud LLMs | `openai`, `claude`, `groq`, `mistral`, `fireworks`, `together`, `openrouter`, `perplexity` | You need hosted models, managed scaling, or provider-specific model quality. |
| Local LLMs | `ollama`, `lmstudio`, `local` | You need local inference, data locality, lower latency, or offline development. |
| Reasoning engines | `clips`, `z3` | You need deterministic rule evaluation, constraint solving, or explainable decisions. |
| Utility providers | `mock`, `loopback`, `mcp` | You need tests, integration checks, or model-context tooling. |
## Configuration Shape
All providers use the same high-level configuration fields:
```json
{
"provider_type": "openai",
"model": "gpt-4o",
"api_key": "sk-...",
"base_url": "https://api.openai.com/v1",
"timeout_ms": 30000,
"options": {}
}
```
Only `provider_type` is always required. API keys can come from explicit
configuration, environment variables, or the credential store. See
[Authentication](/nxuskit/getting-started/authentication/) for the precedence
rules.
## Request Flow
1. Create a provider from configuration.
2. Build a chat request with a model name and messages.
3. Call `chat()` for a complete response or `chat_stream()` for incremental chunks.
4. Read response content and provider metadata.
```rust
use nxuskit::{ChatRequest, Message, NxuskitProvider, ProviderConfig};
let provider = NxuskitProvider::new(ProviderConfig {
provider_type: "openai".into(),
..Default::default()
})?;
let request = ChatRequest::new("gpt-4o")
.with_message(Message::user("Summarize the provider model."));
let response = provider.chat(request)?;
println!("{}", response.content);
```
## Capabilities
Providers advertise capabilities such as streaming, vision, JSON mode, tool
calling, deterministic seeds, and local model discovery. Use the capability
metadata to choose a provider at runtime instead of hard-coding assumptions.
For provider-specific details, see:
- [Cloud LLM Providers](/nxuskit/reference/providers/cloud-llms/)
- [Local LLM Providers](/nxuskit/reference/providers/local-llms/)
- [Expert System & Utility Providers](/nxuskit/reference/providers/expert-systems/)
- [Z3 Constraint Satisfaction Provider](/nxuskit/reference/providers/z3-solver/)
## Choosing a Provider
| Need | Start with |
|------|------------|
| General hosted chat, tools, and JSON output | Cloud LLM provider |
| Local development without external API calls | Ollama or LM Studio |
| Embedded local inference with direct model lifecycle control | In-process local provider |
| Deterministic business rules | CLIPS |
| Constraint solving and optimization | Z3 |
| Unit tests with predictable responses | Mock or Loopback |
---
# Tier System
URL: https://docs.nxus.systems/nxuskit/concepts/tier-system
## Overview
nxusKit SDK uses a dual-edition model for the public SDK surface.
The public `nxusKit` repository contains nxusKit SDK Community Edition, which is free and open source. CE is not a trial, teaser, or time-limited evaluation; it is intended to remain useful on its own. We do not move released CE features behind the Pro paywall, and code released as CE remains available under its open-source license.
Community Edition is useful on its own without Pro. The public `nxusKit-examples` repository labels examples by edition, so developers can see which workflows run with CE alone and which require Pro.
nxusKit SDK Pro adds proprietary commercial capabilities for teams that need solver-backed workflows, ZEN decision tables, plugin loading, and trust-policy features. Pro is distributed under a paid, trial, or evaluation entitlement. **Enterprise** adds delegated trust and custom plugin configuration for large organizations.
## Feature Matrix
| Feature Domain | Community | Pro | Enterprise |
|----------------|:---------:|:---:|:----------:|
| LLM Cloud Providers (OpenAI, Claude, xAI Grok, Groq, Mistral, Fireworks, Together, OpenRouter, Perplexity) | Yes | Yes | Yes |
| LLM Local Providers (Ollama, LM Studio) | Yes | Yes | Yes |
| CLIPS Rule Engine (ClipsSession API) | Yes | Yes | Yes |
| Bayesian Network Inference | Yes | Yes | Yes |
| Auth Helper (API-key management, credential store) | Yes | Yes | Yes |
| Tool Calling / Function Calling | Yes | Yes | Yes |
| Streaming & Token Usage | Yes | Yes | Yes |
| Retry & Adaptive Rate Limiting | Yes | Yes | Yes |
| Vision / Image Support | Yes | Yes | Yes |
| OAuth Authentication Infrastructure | Yes | Yes | Yes |
| Cross-language Parity (Rust, Go, Python) | Yes | Yes | Yes |
| Static + Dynamic Linking | Yes | Yes | Yes |
| **ZEN Decision Tables** | — | Yes | Yes |
| **Constraint Solver (Z3-backed)** | — | Yes | Yes |
| **Plugin Loading & Trust Policy** | — | Yes | Yes |
| **MCP (Model Context Protocol)** | — | Yes | Yes |
| **CLIPS Advanced (programmatic rules, session persistence)** | — | Yes | Yes |
| **Custom Plugin Configuration Paths** | — | — | Yes |
| **Delegated Trust Roots** | — | — | Yes |
| **Priority Support** | — | — | Yes |
## Numerical Limits
| Limit | Community | Pro | Enterprise |
|-------|:---------:|:---:|:----------:|
| Max concurrent CLIPS sessions | 16 | 64 | 256 |
| Max cached rulebases | 8 | 32 | 128 |
| Max rules per session | 500 | 5,000 | 50,000 |
| Max facts per session | 10,000 | 100,000 | 1,000,000 |
| Max Bayesian network nodes | 50 | 500 | 5,000 |
| Max solver constraints | — | 10,000 | 100,000 |
| Machine activations (developer tokens) | — | 3 | Unlimited |
## SDK Wrapper Availability
All editions provide wrappers for all three languages:
| Language | Package | Install |
|----------|---------|---------|
| Rust | `nxuskit` | `cargo add nxuskit` |
| Go | `nxuskit` | `go get github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go` |
| Python | `nxuskit-py` | `pip install nxuskit-py` |
## Example Tier Assignments
| Example | Tier | Reason |
|---------|------|--------|
| LLM basics, streaming, tool calling | Community | Uses cloud/local LLM providers |
| CLIPS basics, CLIPS-LLM hybrid | Community | CLIPS engine is Community-tier |
| Bayesian network inference | Community | BN inference is Community-tier |
| Gamer (game AI solver) | **Pro** | Uses Z3 constraint solver |
| Racer (optimization) | **Pro** | Uses Z3 constraint solver |
| Ruler (rule evaluation) | **Pro** | Uses ZEN decision tables |
| Solver (generic CSP) | **Pro** | Uses Z3 constraint solver |
| Riffer (music generation) | **Pro** | Uses solver + CLIPS pipeline |
| Sweeper (minesweeper AI) | **Pro** | Uses Z3 constraint solver |
## Licensing
| Aspect | Community | Pro | Enterprise |
|--------|-----------|-----|------------|
| License type | Open-source | Commercial subscription | Commercial subscription |
| Token required | No | Yes (developer or deployment) | Yes |
| Machine activations | N/A | Up to 3 per license | Unlimited |
| Deployment tokens | N/A | Unlimited instances, no per-seat fees | Unlimited |
| Version ceiling | N/A | Locked to major.minor at purchase time | Locked to major.minor |
| Trial | N/A | 30-day trial (registration required) | Contact sales |
## Getting Started with Pro
1. Create an account and register for a trial or purchase a license
2. Authenticate: `nxuskit-cli license login`
3. Activate on your machine: `nxuskit-cli license activate --key `
4. For CI/CD: set `NXUSKIT_LICENSE_TOKEN` with your deployment token
See the [License Activation Guide](/nxuskit/concepts/licensing/) for the full workflow.
---
# nxusKit Examples
URL: https://docs.nxus.systems/nxuskit/examples
[](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE)



**[Examples Docs](https://docs.nxus.systems/nxuskit/examples/)** · **[SDK Docs](https://docs.nxus.systems/nxuskit/)** · **[nxusKit SDK](https://github.com/nxus-SYSTEMS/nxusKit)** · **[Examples Portfolio](https://nxus.systems/examples)** · **[Field Notes](https://nxus.systems/field-notes)** · **[Website](https://nxus.systems/)**
34 production-quality examples for the nxusKit SDK in Rust, Go, and Python, plus selected CLI/Bash implementations for shell-first orchestration — covering LLM patterns, CLIPS rule engines, Z3 constraint solvers, Bayesian networks, and ZEN decision tables.
## A Word About CLIPS
During its development at NASA from 1985 to 1996, the primary CLIPS
contributors were: Robert Savely, who conceived and championed the project;
Chris Culbert, who managed the project; Gary Riley and Brian Dantes, who were
the lead developers; and Frank Lopez, who developed the first version. Since
leaving NASA in 1996, Gary Riley has maintained CLIPS as public domain
software.
## Quick Start
```bash
# 1. Install the SDK (see https://docs.nxus.systems/nxuskit/getting-started/installation/)
# 2. Set up this project
source ~/.nxuskit/sdk/current/scripts/setup-sdk.sh # Go, env vars, library paths
./scripts/setup-sdk-symlink.sh # Rust Cargo paths override
# 3. Run an example
cargo run --manifest-path examples/patterns/basic-chat/rust/Cargo.toml # Rust
go run -tags nxuskit ./examples/patterns/basic-chat/go # Go
python examples/patterns/basic-chat/python/main.py # Python
```
## Examples
### Patterns — Reusable SDK integration patterns
| Example | Edition | Description | Languages |
|---------|---------|-------------|-----------|
| [basic-chat](/nxuskit/examples/patterns/basic-chat/) | Community | Basic chat completion with a simple prompt | Rust, Go, Python |
| [streaming](/nxuskit/examples/patterns/streaming/) | Community | Streaming chat completion with real-time output | Rust, Go, Python |
| [multi-provider](/nxuskit/examples/patterns/multi-provider/) | Community | Using multiple providers in one application | Rust, Go, Python, CLI/Bash |
| [convenience-api](/nxuskit/examples/patterns/convenience-api/) | Community | LiteLLM-style convenience API usage | Rust, Go |
| [blocking-api](/nxuskit/examples/patterns/blocking-api/) | Community | Synchronous blocking API for simpler use cases | Rust, Go |
| [capability-detection](/nxuskit/examples/patterns/capability-detection/) | Community | Detecting provider capabilities at runtime | Rust, Go, CLI/Bash |
| [cost-routing](/nxuskit/examples/patterns/cost-routing/) | Community | Cost-aware provider routing and selection | Rust, Go, Python, CLI/Bash |
| [polymorphic](/nxuskit/examples/patterns/polymorphic/) | Community | Polymorphic provider patterns with trait objects | Rust, Go |
| [retry-fallback](/nxuskit/examples/patterns/retry-fallback/) | Community | Retry and fallback strategies across providers | Rust, Go, Python, CLI/Bash |
| [structured-output](/nxuskit/examples/patterns/structured-output/) | Community | JSON mode and structured output generation | Rust, Go, Python, CLI/Bash |
| [timeout-config](/nxuskit/examples/patterns/timeout-config/) | Community | Timeout configuration and connection management | Rust, Go, Python |
| [token-budget](/nxuskit/examples/patterns/token-budget/) | Community | Token budget management and cost estimation | Rust, Go, Python, CLI/Bash |
| [vision](/nxuskit/examples/patterns/vision/) | Community | Vision and multimodal capabilities with images | Rust, Go, Python, CLI/Bash |
| [auth-helper](/nxuskit/examples/patterns/auth-helper/) | Community | OAuth login flow and credential management helper | Rust, Go |
| ↳ `status` | | List provider authentication status and stored credentials | |
| ↳ `set` | | Store an API key for a specific provider | |
| ↳ `remove` | | Remove a stored API key for a provider | |
| ↳ `dashboard` | | Open provider credential dashboard in browser | |
| [solver](/nxuskit/examples/patterns/solver/) | Pro | Z3 constraint solver integration via nxusKit SDK | Rust, Go, Python, CLI/Bash |
| ↳ `theme-park` | | Budget and space planning for a theme park with rides, food courts, and entertainment zones | |
| ↳ `space-colony` | | Resource allocation for a space colony dealing with solar storm what-if scenarios | |
| ↳ `fantasy-draft` | | Fantasy sports draft optimization under salary cap with injury what-if analysis | |
| ↳ real-world: **Theme Park Planning** | | Facility layout, capital budgeting, resource allocation | |
| ↳ real-world: **Space Colony Planning** | | Infrastructure sizing, capacity planning, disaster recovery modeling | |
| ↳ real-world: **Fantasy Sports Draft** | | Portfolio optimization, team composition, auction bidding strategies | |
| [bayesian-inference](/nxuskit/examples/patterns/bayesian-inference/) | Community | Bayesian network inference via nxusKit SDK | Rust, Go, Python, CLI/Bash |
| ↳ `haunted-house` | | Investigate a haunted house — is it a ghost or a raccoon? | |
| ↳ `coffee-shop` | | Diagnose bad espresso from grind size, temperature, and bean age | |
| ↳ `plant-doctor` | | Diagnose a sick plant from overwatering, nutrient, and disease evidence | |
| ↳ real-world: **Haunted House** | | Fault diagnosis, anomaly detection, sensor fusion from multiple noisy sensors pointing to hidden causes | |
| ↳ real-world: **Coffee Shop** | | Manufacturing quality control, process parameter tuning, root cause analysis in production | |
| ↳ real-world: **Plant Doctor** | | Medical diagnosis, agricultural advisory systems, multi-symptom differential diagnosis | |
| [solver-what-if](/nxuskit/examples/patterns/solver-what-if/) | Pro | What-if scenario analysis with solver scoping | Rust, Go, Python, CLI/Bash |
| ↳ `wedding` | | Wedding budget planning with $25k constraint and vendor what-if scenarios | |
| ↳ `mars` | | Mars colony resource allocation with dust storm what-if disruptions | |
| ↳ `recipe` | | Recipe scaling with vegan substitution — may be UNSAT | |
| ↳ real-world: **Wedding Budget Planning** | | Event planning, capital budgeting, portfolio allocation | |
| ↳ real-world: **Mars Colony Planning** | | Infrastructure sizing, supply chain planning, disaster preparedness | |
| ↳ real-world: **Recipe Scaling** | | Manufacturing scaling, formulation optimization, process engineering | |
### Integrations — Combining SDK features
| Example | Edition | Description | Languages |
|---------|---------|-------------|-----------|
| [ollama](/nxuskit/examples/integrations/ollama/) | Community | Using Ollama for local inference | Rust, Go, Python |
| [lmstudio](/nxuskit/examples/integrations/lmstudio/) | Community | Using LM Studio for local inference | Rust, Go |
| [alert-triage](/nxuskit/examples/integrations/alert-triage/) | Community | Alert triage with LLM-powered analysis | Rust, Go, CLI/Bash |
| [cli-assistant](/nxuskit/examples/integrations/cli-assistant/) | Community | Interactive CLI assistant with LLM backend | Rust, Go |
| [clips-basics](/nxuskit/examples/integrations/clips-basics/) | Community | CLIPS rule engine basics via nxusKit SDK | Rust, Go, CLI/Bash |
| [clips-llm-hybrid](/nxuskit/examples/integrations/clips-llm-hybrid/) | Community | Hybrid CLIPS rules + LLM reasoning | Rust, Go, Python, CLI/Bash |
| [common-sense-guardrails](/nxuskit/examples/integrations/common-sense-guardrails/) | Community Runs in Community Edition with CLIPS and selected BN risk scoring. Pro adds Solver/Z3 and ZEN guardrails for repair feedback when selected. | Progressive LLM guardrails with CE CLIPS/BN and optional Pro Solver/ZEN repair feedback | Python, CLI/Bash |
| ↳ `car-wash` | | Catch the classic car-wash walk-vs-drive failure with CLIPS rules and optional Solver/Z3 feasibility | |
| ↳ `coupon-stack` | | Reject promotion stacking that violates eligibility and margin policy, with optional ZEN validation and BN risk scoring | |
| ↳ `pallet-door` | | Block unsafe warehouse advice that ignores dimensional clearance, with optional Solver/Z3 feasibility | |
| ↳ `cold-chain` | | Prevent cheaper logistics recommendations that violate handling requirements, with optional ZEN validation and BN review-risk scoring | |
| ↳ real-world: **LLM answer validation** | | Catch plausible recommendations that fail physical, operational, or policy preconditions before they reach users | |
| ↳ real-world: **Policy enforcement** | | Turn free-form answers into facts, apply deterministic rules, and produce auditable repair context | |
| ↳ real-world: **Operational decision support** | | Preserve fast LLM drafting while requiring concrete feasibility evidence for workflow-critical recommendations | |
| [model-research-harness](/nxuskit/examples/integrations/model-research-harness/) | Community Runs in Community Edition. Future Pro profiles may add Solver portfolio optimization and ZEN decision tables. | Python-first harness for provider-neutral model research, Promptfoo import, CLIPS policy, Bayesian scoring, and dry-run lifecycle recommendations | Python, CLI/Bash |
| ↳ `basic-ticket-routing` | | Run a credentials-free support ticket classification research smoke | |
| ↳ `promptfoo-import` | | Import a Promptfoo config and run the converted nxusKit harness matrix | |
| ↳ `software-dev` | | Evaluate code analysis, bug finding, patching, generation, refactoring, and review outputs | |
| ↳ real-world: **Model evaluation** | | Score model candidates against task-specific outputs and report confidence instead of relying on ad hoc impressions | |
| ↳ real-world: **Provider comparison** | | Compare local and cloud providers through one provider-neutral workflow while keeping capability claims honest | |
| ↳ real-world: **Lifecycle policy** | | Generate dry-run pull, pin, keep, or retest recommendations bounded by deterministic policy | |
| ↳ real-world: **Software development workflow research** | | Exercise code analysis, bug finding, bugfixing, generation, refactoring, and review scenarios with public-safe fixtures | |
| [bn-solver-clips-pipeline](/nxuskit/examples/integrations/bn-solver-clips-pipeline/) | Pro | Three-stage BN prediction → Solver optimization → CLIPS safety pipeline | Rust, Go, CLI/Bash |
| ↳ `festival` | | Music festival staging — crowd predictions drive band scheduling and safety | |
| ↳ `rescue` | | Search and rescue — survivor probability drives team assignment and safety checks | |
| ↳ `bakery` | | Bakery scheduling — demand forecasts drive oven allocation and allergen separation | |
| ↳ real-world: **Event planning** | | Predict attendance, optimize resource allocation, enforce safety codes | |
| ↳ real-world: **Emergency response** | | Estimate survival windows, deploy rescue assets, enforce operational protocols | |
| ↳ real-world: **Manufacturing** | | Forecast demand, schedule production, enforce quality and safety standards | |
| ↳ real-world: **Logistics** | | Predict delivery volumes, optimize fleet routing, enforce regulatory compliance | |
| ↳ real-world: **Healthcare** | | Predict patient load, optimize staff scheduling, enforce clinical safety protocols | |
| [llm-solver-hybrid](/nxuskit/examples/integrations/llm-solver-hybrid/) | Pro | Hybrid LLM + Z3 solver problem solving | Rust, Go, Python, CLI/Bash |
| ↳ `seating` | | Wedding dinner seating — 12 guests across 3 tables with constraints | |
| ↳ `dungeon` | | Dungeon layout — 5 rooms with boss and treasure placement rules | |
| ↳ `road-trip` | | Road trip planning — 14 days across 5 national parks with preferences | |
| [bn-structure-learning](/nxuskit/examples/integrations/bn-structure-learning/) | Community | Bayesian network structure learning from data | Rust, Go, Python |
| ↳ `golf` | | Golf course conditions — weather, soil, and maintenance factor learning | |
| ↳ `bmx` | | BMX performance — skill level, technique, and jump factor learning | |
| ↳ `sourdough` | | Sourdough baking — feeding schedule, flour type, and temperature factor learning | |
| ↳ real-world: **Epidemiology** | | Discover disease risk factor relationships from patient records | |
| ↳ real-world: **Manufacturing** | | Identify root causes of defects from production data | |
| ↳ real-world: **Finance** | | Map causal relationships between economic indicators | |
| ↳ real-world: **Genomics** | | Learn gene regulatory networks from expression data | |
| ↳ real-world: **Quality control** | | Find which process parameters affect product quality | |
| [zen-decisions](/nxuskit/examples/integrations/zen-decisions/) | Pro | ZEN decision table evaluation via nxusKit SDK | Rust, Go, Python, CLI/Bash |
| ↳ `maze-rat` | | First Hit Policy — route a maze runner through personality-driven decisions | |
| ↳ `potion` | | Collect Hit Policy — match ingredient lists against brewing recipes | |
| ↳ `food-truck` | | Expression Nodes — compute dynamic pricing with conditional logic | |
### Apps — Complete applications
| Example | Edition | Description | Languages |
|---------|---------|-------------|-----------|
| [puzzler](/nxuskit/examples/apps/puzzler/) | Pro | Multi-approach puzzle solver comparing CLIPS, LLM, and hybrid strategies | Rust, Go |
| ↳ `sudoku` | | Solve Sudoku puzzles using CLIPS constraint propagation | |
| ↳ `set-game` | | Find valid SET card combinations using CLIPS pattern matching | |
| ↳ `compare` | | Side-by-side comparison of CLIPS, LLM, and hybrid solvers | |
| [racer](/nxuskit/examples/apps/racer/) | Pro | CLIPS vs LLM head-to-head benchmarking tool | Rust, Go |
| ↳ `race` | | Head-to-head CLIPS vs LLM race on a single problem | |
| ↳ `benchmark` | | Statistical benchmarking with multiple runs and timing | |
| ↳ `list` | | List all available problems with difficulty ratings | |
| ↳ `describe` | | Show detailed description of a specific problem | |
| [riffer](/nxuskit/examples/apps/riffer/) | Pro | Music sequence analysis and transformation tool (still learning to shred) | Rust, Go |
| ↳ `analyze` | | Analyze a music sequence for key, intervals, and rhythm patterns | |
| ↳ `score` | | Score a sequence on six musical dimensions | |
| ↳ `transform` | | Transform a sequence — transpose, invert, or retrograde | |
| ↳ `convert` | | Convert between MIDI and MusicXML formats | |
| [ruler](/nxuskit/examples/apps/ruler/) | Pro | LLM-powered CLIPS rule generator with automatic validation | Rust, Go, CLI/Bash |
| ↳ `generate` | | Generate CLIPS rules from natural language descriptions | |
| ↳ `validate` | | Validate CLIPS rule syntax and semantic correctness | |
| ↳ `save` | | Save generated rules to a file for later use | |
| ↳ `load` | | Load previously saved rules from a file | |
| ↳ `examples` | | Run progressive complexity examples demonstrating rule generation | |
| [arbiter](/nxuskit/examples/apps/arbiter/) | Pro | CLIPS-validated LLM retry app with rule-based answer verification | Rust, Go, CLI/Bash |
| ↳ `classification` | | Categorize input text into specified categories | |
| ↳ `extraction` | | Extract structured information from unstructured text | |
| ↳ `reasoning` | | Perform logical inference and multi-step reasoning | |
## SDK Editions
| Badge | Meaning |
|-------|---------|
| **Community** | Runs with the free OSS SDK |
| **Pro** | Requires a Pro license ([activation guide](https://github.com/nxus-SYSTEMS/nxusKit)) |
Edition labels describe the minimum runnable edition for the default path. A Community example can still list optional Pro enhancements; those stages are disabled by default and require a Pro entitlement only when you run them.
See `conformance/example-tiers.json` for the full tier map.
## Project Structure
```
examples/
├── patterns/ Community-tier reusable patterns
├── integrations/ SDK feature combinations
├── apps/ Complete applications (mostly Pro tier)
└── shared/ Shared libraries and helpers (Rust, Go, Python, CLI/Bash)
conformance/ Example manifest and tier definitions
scripts/ Build and test helpers
```
## Building
All examples require the nxusKit SDK. Run these once after cloning:
```bash
# Set up Go workspace, env vars, and native library paths
source ~/.nxuskit/sdk/current/scripts/setup-sdk.sh
# Set up Rust Cargo paths override (generates .cargo/config.toml)
./scripts/setup-sdk-symlink.sh
```
The first script creates Go workspace files and exports environment variables. The second generates a `.cargo/config.toml` that tells Cargo where to find the installed Rust SDK (the generated file is `.gitignore`d — each developer runs this once).
### Rust
```bash
cargo run --manifest-path examples///rust/Cargo.toml
```
### Go
```bash
go run -tags nxuskit ./examples///go/cmd
```
### Python
```bash
python examples///python/main.py
```
### CLI/Bash
```bash
cd examples///bash
make run
```
---
Built with gratitude for the open-source projects that make nxusKit possible.
See [ACKNOWLEDGEMENTS.md](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/ACKNOWLEDGEMENTS.md) for a curated list of key projects.
---
## License
nxusKit Examples is dual-licensed under MIT or Apache 2.0, at your option. See [LICENSE](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE), [LICENSE-MIT](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE-MIT), and [LICENSE-APACHE](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE-APACHE).
Copyright 2025-2026 nxus.SYSTEMS LLC.
---
# Arbiter - Auto-Retry LLM with CLIPS Validation
URL: https://docs.nxus.systems/nxuskit/examples/apps/arbiter
A command-line tool demonstrating the Solver pattern: using CLIPS rules to evaluate LLM output quality and automatically retry with adjusted parameters when validation fails.
> Stop accepting unreliable LLM output — validate every response against CLIPS rules and retry automatically until your standards are met.
**Scenarios**: `classification` · `extraction` · `reasoning`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** CLIPS-validated LLM retry app with rule-based answer verification
- **Scenario:** Submit questions to an LLM and validate answers against CLIPS rules, retrying on validation failure
- **`tech_tags` in manifest:** `CLIPS, LLM` — example id **`arbiter`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Real-World Application
Operations research tool, constraint modeling workbench.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
Solver
## CLIPS integration path (validation)
Go CLIPS validation uses **provider chat** with local `go/clips_wire.go` types mirroring `ClipsInput` / `ClipsOutput`. For **Session API** access, use `nxuskit.ClipsSession`. Reference: `conformance/clips-json-contract.json`; nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/arbiter`:
cd rust && cargo build
cd go && make build
```
## Features
- **LLM Output Validation** - Use CLIPS rules to evaluate response quality
- **Automatic Retry** - Retry with adjusted parameters on validation failure
- **Configurable Strategies** - Define retry strategies for different failure modes
- **Multiple Conclusion Types** - Classification, extraction, and reasoning tasks
- **Scoring System** - Score attempts based on validation results
## Installation
### Rust
```bash
cd examples/apps/arbiter/rust
cargo build --release
```
### Go
```bash
cd examples/apps/arbiter/go
make build
```
## Run
### Rust
```bash
cd examples/apps/arbiter/rust
# Show help
cargo run -- --help
# Run classification task
cargo run -- -t classification -i "This product is amazing!" --categories "positive,negative,neutral"
# Run with custom config
cargo run -- -c config.yaml -i "Analyze this text"
# Run extraction task
cargo run -- -t extraction -i "John works at Acme Corp in New York"
# Verbose mode
cargo run -- -v -t reasoning -i "If A implies B and B implies C, what can we conclude about A and C?"
```
### Go
```bash
cd examples/apps/arbiter/go
# Show help
./bin/arbiter --help
# Run classification
./bin/arbiter -t classification -i "Great service!" --categories "positive,negative,neutral"
```
## Command Line Options
```
USAGE:
arbiter [OPTIONS] -i
OPTIONS:
-c, --config Configuration file path
-i, --input Input text to process
-t, --type Conclusion type: classification, extraction, reasoning
--categories Comma-separated categories for classification
--max-retries Maximum retry attempts (default: 3)
-v, --verbose Show detailed progress
-h, --help Show help message
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/arbiter --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/arbiter --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Conclusion Types
### Classification
Categorize input into predefined categories.
```bash
arbiter -t classification -i "I love this!" --categories "positive,negative,neutral"
```
### Extraction
Extract structured information from text.
```bash
arbiter -t extraction -i "Contact John at john@example.com or 555-1234"
```
### Reasoning
Perform logical reasoning and inference.
```bash
arbiter -t reasoning -i "All cats are mammals. Whiskers is a cat. What is Whiskers?"
```
## Configuration
Create a YAML configuration file for custom settings:
```yaml
# arbiter-config.yaml
max_retries: 5
strategies:
- failure_type: invalid_category
adjustments:
temperature: -0.2
prompt_suffix: "Choose only from the given categories."
- failure_type: incomplete_extraction
adjustments:
temperature: 0
prompt_suffix: "Extract all mentioned entities."
- failure_type: invalid_reasoning
adjustments:
temperature: -0.1
prompt_suffix: "Show your reasoning step by step."
```
## Example Output
### Classification Result
```
=== Solver: Classification Task ===
Input: "This product exceeded my expectations!"
Categories: positive, negative, neutral
Attempt 1:
LLM Response: "positive"
Validation: PASSED
Score: 100
Result: positive (1 attempt, 45ms)
```
### With Retry
```
=== Solver: Classification Task ===
Input: "It's okay I guess"
Categories: positive, negative, neutral
Attempt 1:
LLM Response: "somewhat positive"
Validation: FAILED (invalid category)
Strategy: Reduce temperature, clarify categories
Attempt 2:
LLM Response: "neutral"
Validation: PASSED
Score: 95
Result: neutral (2 attempts, 1.2s)
```
## Retry Strategies
The arbiter includes default strategies for common failure modes:
| Failure Type | Adjustment |
|--------------|------------|
| Invalid category | Lower temperature, clarify options |
| Incomplete extraction | Reset temperature, request all entities |
| Invalid reasoning | Lower temperature, request step-by-step |
| Confidence too low | Increase temperature slightly |
| Format error | Add format examples to prompt |
## Architecture
```
arbiter/
├── rust/
│ ├── src/main.rs # CLI entry point
│ └── Cargo.toml
├── go/
│ ├── cmd/main.go # CLI entry point
│ ├── solver.go # Core solver logic
│ ├── strategies.go # Retry strategies
│ ├── validator.go # CLIPS validation
│ └── go.mod
└── shared/
├── rules/ # CLIPS validation rules
└── configs/ # Example configurations
```
## How It Works
1. **Initial Request**: Send input to LLM with configured prompt
2. **Validation**: Pass LLM response through CLIPS validation rules
3. **Evaluation**: Score the response based on validation results
4. **Retry Decision**: If validation fails, find matching retry strategy
5. **Adjustment**: Apply strategy adjustments (temperature, prompt, etc.)
6. **Repeat**: Retry up to max_retries times
7. **Result**: Return best successful attempt or highest-scoring failure
## Notes
- CLIPS validation rules are in `shared/rules/classification-eval.clp`
- Build Go with `-tags=clips` for real ClipsProvider integration
- LLM approach requires API key (ANTHROPIC_API_KEY or OPENAI_API_KEY)
## Testing
```bash
# Rust
cd examples/apps/arbiter/rust
cargo test
# Go
cd examples/apps/arbiter/go
go test -v ./...
```
## License
Part of the nxusKit project.
---
# Puzzler - Puzzle Solver Comparison
URL: https://docs.nxus.systems/nxuskit/examples/apps/puzzler
A command-line tool for comparing three approaches to solving logic puzzles: CLIPS-only, LLM-only, and Hybrid.
> Compare CLIPS rule-based constraint solving against LLM reasoning side by side, then combine both in a hybrid approach for real puzzle problems.
**Scenarios**: `sudoku` · `set-game` · `compare`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS · Solver
- **Summary:** Multi-approach puzzle solver comparing CLIPS, LLM, and hybrid strategies
- **Scenario:** Compare CLIPS rule-based, LLM reasoning, and hybrid approaches for solving logic puzzles
- **`tech_tags` in manifest:** `CLIPS, LLM, Solver` — example id **`puzzler`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Real-World Application
Educational puzzle solver, constraint programming tutorial.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
Solver
## CLIPS integration path (CLIPS-only / hybrid modes)
The Go CLIPS solver path uses **provider chat** (`go/clips_wire.go` mirrors `ClipsInput` / `ClipsOutput` JSON). It is not the **Session API** (`nxuskit.ClipsSession`). See `conformance/clips-json-contract.json` and nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/puzzler`:
cd rust && cargo build
cd go && make build
```
## Features
- **Sudoku Puzzles** - Solve Sudoku puzzles of varying difficulty
- **Set Game** - Find valid sets in Set card game hands
- **Three Approaches**:
- **CLIPS-only**: Pure rule-based constraint propagation
- **LLM-only**: Pure LLM reasoning
- **Hybrid**: CLIPS primary with LLM fallback for stuck states
- **Comparison Mode** - Run all approaches and compare results
## Installation
### Rust
```bash
cd examples/apps/puzzler/rust
cargo build --release
```
### Go
```bash
cd examples/apps/puzzler/go
make build
```
## Run
### Rust
```bash
cd examples/apps/puzzler/rust
# Show help
cargo run -- --help
# Solve a Sudoku puzzle
cargo run -- sudoku -p easy
# Compare all approaches on Sudoku
cargo run -- sudoku --compare
# Play Set game
cargo run -- set -p random
# Compare approaches on Set game
cargo run -- set --compare
```
### Go
```bash
cd examples/apps/puzzler/go
# Show help
./bin/puzzler --help
# Solve a Sudoku puzzle
./bin/puzzler sudoku -p easy
# Compare all approaches
./bin/puzzler sudoku --compare
```
## Command Line Options
```
USAGE:
puzzler [OPTIONS]
GAMES:
sudoku Solve Sudoku puzzles
set Find sets in Set game cards
OPTIONS:
-p, --puzzle Puzzle identifier (easy, medium, hard, expert, or custom)
-a, --approach Solver approach: clips, llm, hybrid (default: hybrid)
-c, --compare Compare all three approaches
-v, --verbose Show detailed solving steps
-h, --help Show help message
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/puzzler --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/puzzler --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Puzzle Types
### Sudoku
Difficulty levels:
- **easy** - Many given numbers, straightforward solving
- **medium** - Moderate difficulty
- **hard** - Requires advanced techniques
- **expert** - Very few givens, requires backtracking
### Set Game
Find valid sets where each attribute (color, shape, shading, number) is either all the same or all different across three cards.
## Example Output
### Sudoku Comparison
```
=== Sudoku Puzzle: easy ===
Approach | Time | Solved | Moves
--------------|---------|--------|-------
CLIPS-only | 12ms | Yes | 47
LLM-only | 2.3s | Yes | 52
Hybrid | 15ms | Yes | 47
Winner: CLIPS-only (fastest)
```
### Set Game
```
=== Set Game: 12 cards ===
Found 3 valid sets:
Set 1: Red-Oval-Solid-1, Red-Oval-Striped-2, Red-Oval-Empty-3
Set 2: Green-Diamond-Solid-1, Purple-Diamond-Striped-1, Red-Diamond-Empty-1
Set 3: ...
```
## Architecture
```
puzzler/
├── rust/
│ ├── src/main.rs # CLI entry point
│ └── Cargo.toml
├── go/
│ ├── cmd/main.go # CLI entry point
│ ├── sudoku.go # Sudoku solver logic
│ ├── setgame.go # Set game solver logic
│ └── go.mod
└── shared/
└── puzzles/ # Puzzle definitions
```
## Notes
- CLIPS validation rules are in `shared/puzzles/`
- LLM solving uses Ollama by default (no API key required)
- Optional: Set ANTHROPIC_API_KEY or OPENAI_API_KEY for cloud providers
## Testing
```bash
# Rust
cd examples/apps/puzzler/rust
cargo test
# Go
cd examples/apps/puzzler/go
go test -v ./...
```
## License
Part of the nxusKit project.
---
# Racer - CLIPS vs LLM Head-to-Head Competition
URL: https://docs.nxus.systems/nxuskit/examples/apps/racer
A benchmarking tool for running concurrent races between CLIPS rule-based solving and LLM reasoning on logic problems.
> Race CLIPS rule engines against LLMs on logic puzzles and let the data choose your AI strategy.
**Scenarios**: `race` · `benchmark` · `list` · `describe`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## Real-World Application
Motorsport strategy advisor, real-time decision engine.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
CLIPS
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** CLIPS rule-based racing strategy engine
- **Scenario:** Simulate racing pit-stop strategy using CLIPS rules
- **`tech_tags` in manifest:** `CLIPS` — example id **`racer`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## CLIPS integration path
The Go CLIPS runner uses **provider chat** (`go/clips_wire.go`). For **Session API** usage, use CLIPS session bindings in the SDK. Reference: `conformance/clips-json-contract.json`; nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/racer`:
cd rust && cargo build
cd go && make build
```
## Features
- **Head-to-Head Racing** - Run CLIPS and LLM approaches simultaneously
- **Benchmarking** - Statistical analysis over multiple runs
- **Problem Library** - Built-in collection of logic problems
- **Scoring Modes** - Speed, accuracy, or composite scoring
- **JSON Output** - Machine-readable results for analysis
## Installation
### Rust
```bash
cd examples/apps/racer/rust
cargo build --release
```
### Go
```bash
cd examples/apps/racer/go
make build
```
## Run
### Rust
```bash
cd examples/apps/racer/rust
# Show help
cargo run -- --help
# Run a single race
cargo run -- race einstein-riddle
# Run with accuracy scoring
cargo run -- race -s accuracy family-relations
# Benchmark with 20 runs
cargo run -- benchmark -n 20 einstein-riddle -o results.json
# List available problems
cargo run -- list
# Describe a specific problem
cargo run -- describe einstein-riddle
```
### Go
```bash
cd examples/apps/racer/go
# Show help
./bin/racer --help
# Run a single race
./bin/racer race einstein-riddle
# Benchmark mode
./bin/racer benchmark -n 10 logic-grid
```
## Commands
### race
Run a single head-to-head race between CLIPS and LLM.
```bash
racer race [OPTIONS]
OPTIONS:
-s, --scoring Scoring: speed, accuracy, composite (default: speed)
-t, --timeout Timeout per approach (default: 60)
-m, --model LLM model to use
--clips-only Run only CLIPS approach
--llm-only Run only LLM approach
-j, --json Output in JSON format
-v, --verbose Show detailed progress
```
### benchmark
Run multiple races for statistical analysis.
```bash
racer benchmark [OPTIONS]
OPTIONS:
-n, --runs Number of benchmark runs (default: 10)
-o, --output Write results to file
-j, --json Output in JSON format
```
### list
List available problems with optional filtering.
```bash
racer list [OPTIONS]
OPTIONS:
-t, --type Filter by problem type
-d, --difficulty Filter by difficulty
```
### describe
Show detailed information about a problem.
```bash
racer describe
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/racer --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/racer --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Problem Types
- **einstein-riddle** - The classic Einstein's Riddle (Zebra Puzzle)
- **family-relations** - Family relationship deduction
- **logic-grid** - Logic grid puzzles
- **scheduling** - Resource scheduling problems
- **classification** - Multi-attribute classification
## Scoring Modes
- **speed** - Fastest correct answer wins
- **accuracy** - Most accurate/complete answer wins
- **composite** - Weighted combination of speed and accuracy
## Example Output
### Race Results
```
=== Race: einstein-riddle ===
Contender | Time | Correct | Score
-------------|---------|---------|-------
CLIPS | 45ms | Yes | 100
LLM (Claude) | 3.2s | Yes | 98
Winner: CLIPS (faster with equal accuracy)
```
### Benchmark Results
```
=== Benchmark: einstein-riddle (20 runs) ===
Contender | Avg Time | Win Rate | Avg Score
-------------|----------|----------|----------
CLIPS | 47ms | 85% | 99.5
LLM (Claude) | 3.4s | 15% | 97.2
Statistical Winner: CLIPS (p < 0.001)
```
## Architecture
```
racer/
├── rust/
│ ├── src/main.rs # CLI entry point
│ └── Cargo.toml
├── go/
│ ├── cmd/main.go # CLI entry point
│ ├── runner.go # Race runner logic
│ ├── problems.go # Problem definitions
│ └── go.mod
└── shared/
└── problems/ # Problem definitions
```
## Notes
- CLIPS functionality uses ClipsProvider for rule execution
- LLM approach requires API key (ANTHROPIC_API_KEY or OPENAI_API_KEY)
- Benchmarks may vary based on LLM response times
## Testing
```bash
# Rust
cd examples/apps/racer/rust
cargo test
# Go
cd examples/apps/racer/go
go test -v ./...
```
## License
Part of the nxusKit project.
---
# Riffer - Music Sequence Analysis and Transformation (Rust)
URL: https://docs.nxus.systems/nxuskit/examples/apps/riffer
A command-line tool for analyzing and transforming music sequences, implemented in Rust.
> Analyze, score, and transform MIDI and MusicXML sequences using CLIPS rule-based music theory and LLM-powered narrative and transformation.
**Scenarios**: `analyze` · `score` · `transform` · `convert`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** CLIPS rule-based music composition engine
- **Scenario:** Generate musical riffs using CLIPS composition rules
- **`tech_tags` in manifest:** `CLIPS` — example id **`riffer`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## Real-World Application
Algorithmic music generation, creative AI assistant.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
CLIPS
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/riffer`:
cd rust && cargo build
cd go && make build
```
## Features
- **Analyze** - Detect key signature, analyze intervals, contour, rhythm, and dynamics
- **Score** - 6-dimension musicality scoring with improvement suggestions
- **Transform** - Transpose, invert, retrograde, augment, diminish, change key/tempo
- **Convert** - Convert between MIDI and MusicXML formats
## Installation
```bash
cd examples/apps/riffer/rust
cargo build --release
```
Find and set the binary path:
```bash
# Find where cargo built the binary
RIFFER=$(cargo metadata --format-version 1 | sed -n 's/.*"target_directory":"\([^"]*\)".*/\1/p')/release/riffer
# Verify it exists
ls -la "$RIFFER"
```
## Run
From the `examples/apps/riffer/rust` directory:
### Analyze a sequence
```bash
# JSON output (default)
"$RIFFER" analyze -i ../shared/testdata/e_minor_riff.mid
# Markdown output
"$RIFFER" analyze -i ../shared/testdata/e_minor_riff.mid -f markdown
```
### Score musicality
```bash
# Get a 6-dimension score with suggestions
"$RIFFER" score -i ../shared/testdata/e_minor_riff.mid -f markdown
```
Output includes:
- Overall score (0-100)
- Dimension scores: Harmonic Coherence, Melodic Interest, Rhythmic Variety, Resolution Quality, Dynamics Expression, Structural Balance
- Improvement suggestions
### Transform a sequence
```bash
# Transpose up 5 semitones
$RIFFER transform -i input.mid -o output.mid --transpose 5
# Invert around middle C (MIDI note 60)
$RIFFER transform -i input.mid -o output.mid --invert 60
# Reverse notes (retrograde)
$RIFFER transform -i input.mid -o output.mid --retrograde
# Rhythmic augmentation - double note durations (not to be confused with augmented chords)
$RIFFER transform -i input.mid -o output.mid --augment 2.0
# Rhythmic diminution - halve note durations (not to be confused with diminished chords)
$RIFFER transform -i input.mid -o output.mid --diminish 2.0
# Change key to G major
$RIFFER transform -i input.mid -o output.mid --key G
# Change tempo to 140 BPM
$RIFFER transform -i input.mid -o output.mid --tempo 140
# Combine multiple transformations
$RIFFER transform -i input.mid -o output.mid --transpose 5 --tempo 140
```
### Convert between formats
```bash
# MIDI to MusicXML
$RIFFER convert -i input.mid -o output.xml
# MusicXML to MIDI
$RIFFER convert -i input.xml -o output.mid
```
## Supported Formats
- **MIDI** (.mid, .midi) - Standard MIDI File format
- **MusicXML** (.xml, .musicxml) - MusicXML partwise format
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/riffer --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/riffer --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Example Output
### Analysis (Markdown)
```markdown
# Music Analysis: c_major_scale
## Summary
- **Notes**: 8
- **Duration**: 3840 ticks
## Key Detection
- **Detected Key**: C Major
- **Confidence**: 96.7%
## Scale Analysis
- **In Scale**: 8 notes
- **Out of Scale**: 0 notes
- **Harmonic Coherence**: 100.0%
```
### Score (Markdown)
```markdown
# Music Score: c_major_scale
## Overall Score: 59.3/100 (fair)
## Dimension Scores
| Dimension | Score | Rating |
|-----------|-------|--------|
| Harmonic Coherence | 100.0 | excellent |
| Melodic Interest | 39.0 | poor |
| Rhythmic Variety | 20.0 | poor |
## Suggestions for Improvement
- Add more interval variety for melodic interest
- Add rhythmic variety with different note durations
```
## Architecture
```
riffer/
├── main.rs # CLI entry point
├── types.rs # Core data types (Note, Sequence, etc.)
├── errors.rs # Error handling
├── formats/
│ ├── midi.rs # MIDI read/write
│ └── musicxml.rs # MusicXML read/write
├── theory/
│ ├── intervals.rs # Interval classification
│ ├── keys.rs # Key detection (Krumhansl-Schmuckler)
│ └── scales.rs # Scale definitions
└── engine/
├── analyzer.rs # Sequence analysis
├── scorer.rs # 6-dimension scoring
├── transformer.rs # Transformations
└── clips_bridge.rs # CLIPS rule engine (ClipsProvider)
```
## Testing
```bash
cd examples/apps/riffer/rust
cargo test
```
## License
Part of the nxusKit project.
---
# Ruler - Natural Language to CLIPS Rule Generation
URL: https://docs.nxus.systems/nxuskit/examples/apps/ruler
A command-line tool for generating CLIPS rules from natural language descriptions using LLM, with validation and automatic retry logic.
> Turn plain English into validated CLIPS rules — describe your business logic, get production-ready expert system code with automatic error correction.
**Scenarios**: `generate` · `validate` · `save` · `load` · `examples`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** CLIPS rule authoring and execution app
- **Scenario:** Author, load, and execute CLIPS rules interactively
- **`tech_tags` in manifest:** `CLIPS` — example id **`ruler`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## Real-World Application
Business rules workbench, rule management console.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
CLIPS
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/ruler`:
cd rust && cargo build
cd go && make build
```
## Features
- **Natural Language Input** - Describe rules in plain English
- **CLIPS Code Generation** - Produces valid CLIPS deftemplates and defrules
- **Automatic Validation** - Validates generated code against CLIPS syntax
- **Retry with Feedback** - Automatically retries with error feedback on failures
- **Progressive Examples** - Built-in examples from basic to advanced complexity
- **Multiple Output Formats** - Save as .clp, .json, or binary
## Installation
### Rust
```bash
cd examples/apps/ruler/rust
cargo build --release
```
### Go
```bash
cd examples/apps/ruler/go
make build
```
## Run
### Rust
```bash
cd examples/apps/ruler/rust
# Show help
cargo run -- --help
# Generate rules from natural language
cargo run -- generate "Create a rule that classifies adults if age >= 18"
# Generate with advanced complexity
cargo run -- generate -c advanced "Medical triage expert system" -o triage.clp
# Run progressive examples
cargo run -- examples -c basic
# Validate existing CLIPS code
cargo run -- validate my-rules.clp
# Load and display rules
cargo run -- load my-rules.clp
```
### Go
```bash
cd examples/apps/ruler/go
# Show help
./bin/ruler --help
# Generate rules
./bin/ruler generate "Classify customers as gold if purchases > 5000"
# Generate with output file
./bin/ruler generate -o customer.clp "Customer loyalty program rules"
```
## Commands
### generate
Generate CLIPS rules from a natural language description.
```bash
ruler generate [OPTIONS]
OPTIONS:
-c, --complexity Target complexity: basic, intermediate, advanced
-m, --model LLM model to use (default: claude-haiku-4-5-20251001)
-r, --retries Max retry attempts (default: 5)
-o, --output Write output to file
-j, --json Output in JSON format
-v, --verbose Show detailed progress
```
### validate
Validate CLIPS code syntax and structure.
```bash
ruler validate [OPTIONS]
OPTIONS:
-v, --verbose Show detailed validation results
```
### examples
Run built-in progressive complexity examples.
```bash
ruler examples [OPTIONS]
OPTIONS:
-c, --complexity Filter by complexity level
-l, --list List examples without running
```
### save / load
Save or load rule sets.
```bash
ruler save # Save current rules
ruler load # Load rules from file
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/ruler --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/ruler --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Complexity Levels
### Basic
- Simple single-rule definitions
- Basic deftemplates with few slots
- Straightforward conditions
Example: "Classify people as adults if age >= 18"
### Intermediate
- Multiple related rules
- Fact chaining and dependencies
- Moderate slot complexity
Example: "Customer loyalty program with bronze, silver, gold tiers"
### Advanced
- Complex multi-rule systems
- Salience and conflict resolution
- Advanced pattern matching
Example: "Medical triage system with symptom analysis"
## Example Output
### Generated CLIPS Code
```clp
; Generated by Ruler from: "Classify adults if age >= 18"
(deftemplate person
(slot name (type STRING))
(slot age (type INTEGER)))
(deftemplate classification
(slot person-name (type STRING))
(slot category (type SYMBOL)))
(defrule classify-adult
"Classify a person as an adult if age >= 18"
(person (name ?name) (age ?age&:(>= ?age 18)))
=>
(assert (classification (person-name ?name) (category adult))))
```
### Validation Result
```
Validation: PASSED
Templates: 2
Rules: 1
Warnings: 0
```
## Architecture
```
ruler/
├── rust/
│ ├── src/main.rs # CLI entry point
│ └── Cargo.toml
├── go/
│ ├── cmd/main.go # CLI entry point
│ ├── generator.go # Rule generation logic
│ ├── validator.go # CLIPS validation
│ └── go.mod
└── shared/
└── examples/ # Built-in examples
```
## Retry Logic
When generated code fails validation:
1. Parse the validation error
2. Include error context in retry prompt
3. Adjust complexity hints if needed
4. Retry up to N times (default: 5)
5. Return best attempt if all retries fail
## Notes
- CLIPS functionality uses ClipsProvider for validation
- LLM approach requires API key (ANTHROPIC_API_KEY or OPENAI_API_KEY)
- Generated code quality depends on description clarity
## Testing
```bash
# Rust
cd examples/apps/ruler/rust
cargo test
# Go
cd examples/apps/ruler/go
go test -v ./...
```
## License
Part of the nxusKit project.
---
# Alert Triage Integration
URL: https://docs.nxus.systems/nxuskit/examples/integrations/alert-triage
LLM-powered alert triage for observability systems, with batch processing and structured output.
> Turn alert noise into prioritized action by letting an LLM classify severity, surface root causes, and recommend remediation steps automatically.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## Overview
This example demonstrates using LLMs to triage monitoring alerts, providing priority assessment, likely causes, and suggested remediation actions. It's designed to work with Alertmanager-format alerts.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Alert triage with LLM-powered analysis
- **Scenario:** Classify and prioritize alerts using LLM reasoning
- **`tech_tags` in manifest:** `LLM` — example id **`alert-triage`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
SOC alert triage, IT incident management.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/alert-triage`:
cd rust && cargo build
cd go && make build
```
## Features
- Batch alert processing for efficiency
- Structured JSON output with priority, cause, and actions
- Compatible with Alertmanager webhook format
- Prioritization based on severity and context
## Alert Format
Input alerts follow the Alertmanager format:
```json
{
"alertname": "HighMemoryUsage",
"severity": "warning",
"instance": "web-server-01",
"description": "Memory usage above 85% for 5 minutes"
}
```
## Triage Output
Each alert receives a triage result:
```json
{
"alertname": "HighMemoryUsage",
"priority": 3,
"summary": "Memory pressure on web server",
"likely_cause": "Memory leak or increased traffic",
"suggested_actions": [
"Check for memory leaks in application logs",
"Review recent deployments",
"Consider horizontal scaling"
]
}
```
## Priority Scale
| Priority | Meaning | Response |
|----------|---------|----------|
| 1 | Critical | Immediate action required |
| 2 | High | Respond within 1 hour |
| 3 | Medium | Respond within 4 hours |
| 4 | Low | Respond within 24 hours |
| 5 | Informational | No action required |
## Library usage
### Rust
```rust
use alert_triage::{triage_alerts, Alert};
let alerts = vec![
Alert { alertname: "...", severity: "critical", ... },
];
let results = triage_alerts(&provider, "llama3", &alerts).await?;
for result in results {
println!("{}: Priority {} - {}", result.alertname, result.priority, result.summary);
}
```
### Go
```go
alerts := []Alert{{AlertName: "...", Severity: "critical", ...}}
results, err := TriageAlerts(ctx, provider, "llama3", alerts)
for _, result := range results {
fmt.Printf("%s: Priority %d - %s\n", result.AlertName, result.Priority, result.Summary)
}
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Sample Data
A `sample_alerts.json` file is provided with example alerts for testing.
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Integration Ideas
1. **Alertmanager webhook**: Receive alerts via HTTP webhook
2. **PagerDuty integration**: Update incident priority based on triage
3. **Slack notifications**: Send enriched alerts to Slack channels
4. **Runbook linking**: Match alerts to relevant runbooks
5. **Historical learning**: Improve triage based on past incident resolutions
---
# Multi-Provider Pipeline -- BN -> Solver -> CLIPS
URL: https://docs.nxus.systems/nxuskit/examples/integrations/bn-solver-clips-pipeline
Demonstrates the flagship nxusKit integration pattern: chaining Bayesian Network prediction, constraint solver optimization, and CLIPS rule-based safety enforcement in a 3-stage pipeline. Each stage feeds its output into the next, showing how probabilistic, combinatorial, and symbolic reasoning compose through a unified SDK.
> Chain probabilistic prediction, constraint optimization, and rule-based safety enforcement into a single production-ready pipeline using one unified SDK.
**Scenarios**: `festival` · `rescue` · `bakery`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## CLIPS integration path (stage 3)
Stage 3 is **CLIPS**: the **Go** path uses **provider chat** (`go/clips_wire.go`, `ClipsInput` / `ClipsOutput` JSON in the chat API). The **Rust** path uses the **Session API** (`nxuskit::clips::ClipsSession` — load rules, `fact_assert_structured`, `run`). Use the path that matches your integration style; both enforce the same rule files.
Schema: `conformance/clips-json-contract.json`. Docs: nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · CLIPS · Solver · BN
- **Summary:** Three-stage BN prediction → Solver optimization → CLIPS safety pipeline
- **Scenario:** Chain Bayesian Network prediction into Solver optimization with CLIPS safety enforcement
- **`tech_tags` in manifest:** `BN, Solver, CLIPS` — example id **`bn-solver-clips-pipeline`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go |
|---------|-------------|------|-----|
| **BnNetwork** | Load and query Bayesian Network from BIF file | `BnNetwork::from_bif()` | `LoadBnNetwork()` |
| **BnEvidence** | Set observed evidence for inference | `evidence.set_discrete()` | `ev.SetDiscrete()` |
| **Variable Elimination** | Exact posterior inference algorithm | `net.infer(&ev, "ve")` | `net.Infer(ev, "ve")` |
| **SolverSession** | Create and configure Z3 constraint solver | `SolverSession::new()` | `NewSolverSession()` |
| **Constraint Optimization** | Single-objective optimization with constraints | `session.solve()` | `session.Solve()` |
| **CLIPS (stage 3)** | Rule engine for safety | **`ClipsSession`**: `load_file`, `fact_assert_structured`, `run` | **Provider chat**: `NewClipsProvider()`, JSON in `ChatRequest` |
| **Fact assertion** | Solver → CLIPS | Structured slots → `fact_assert_structured` | JSON facts in user message |
| **Alert / conclusion readout** | Derived template facts | `facts_by_template` + `fact_slot_values` | Parse `ClipsOutput.conclusions` |
| **Pipeline Composition** | 3-stage data flow across provider types | Stage 1 -> 2 -> 3 | Stage 1 -> 2 -> 3 |
## Technologies
Solver, BN
## Pipeline Architecture
```
┌─────────────┐ Posteriors ┌──────────────┐ Assignments ┌───────────────┐
│ BN Network │ ──────────────> │ Solver │ ──────────────> │ CLIPS Rules │
│ (Prediction) │ │ (Optimization)│ │ (Safety) │
└─────────────┘ └──────────────┘ └───────────────┘
model.bif problem.json rules.clp
evidence.json
```
**Stage 1 -- BN Prediction**: Loads a Bayesian Network from a BIF file, sets observed evidence, and runs Variable Elimination to compute posterior distributions over a target variable (crowd size, survivor probability, or demand level).
**Stage 2 -- Solver Optimization**: Uses the BN prediction to inform a Z3 constraint optimization problem. Variables, constraints, and objectives are loaded from `problem.json`. The solver finds optimal assignments (band-to-stage, team-to-zone, or item-to-oven mappings).
**Stage 3 -- CLIPS Safety Enforcement**: Converts solver assignments into CLIPS facts and asserts them into a rule engine loaded with domain-specific safety rules. The engine fires rules to detect violations and generates typed alerts (critical, warning, info).
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/bn-solver-clips-pipeline`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario festival
cargo run -- --scenario rescue --verbose
cargo run -- --scenario bakery --step
```
### Go
```bash
cd go
make build
./bin/bn-solver-clips-pipeline --scenario festival
./bin/bn-solver-clips-pipeline --scenario rescue --verbose
./bin/bn-solver-clips-pipeline --scenario bakery --step
```
Or directly:
```bash
cd go
go run . --scenario festival
```
## Scenarios
### Festival (Music Festival Stage Planning)
A music festival needs to assign bands to stages while maximizing audience enjoyment. The BN predicts crowd size from weather, headliner popularity, and time of day. The solver optimizes band-to-stage assignments. CLIPS rules enforce noise limits and pyrotechnic safety regulations.
- **BN predicts**: `crowd_size` given weather, headliner popularity, time of day
- **Solver optimizes**: band-to-stage assignments maximizing `total_enjoyment`
- **CLIPS enforces**: noise proximity limits, pyrotechnic material restrictions
### Rescue (Search and Rescue Operation)
A disaster response team must deploy rescue units across zones. The BN estimates survivor probability from building damage, time since event, and weather conditions. The solver assigns teams to zones to maximize rescues. CLIPS rules enforce operational safety protocols.
- **BN predicts**: `survivor_probability` given building damage, hours since event, weather
- **Solver optimizes**: team-to-zone assignments maximizing `total_survivors_rescued`
- **CLIPS enforces**: helicopter wind limits, team deployment protocols
### Bakery (Production Scheduling)
A bakery plans its daily production across multiple ovens. The BN forecasts demand level from day of week, season, and local events. The solver schedules items across ovens to minimize waste. CLIPS rules enforce allergen isolation and food safety regulations.
- **BN predicts**: `demand_level` given day of week, season, local events
- **Solver optimizes**: item-to-oven assignments minimizing `total_waste`
- **CLIPS enforces**: allergen cross-contamination, gluten-free isolation, scheduling conflicts
## Interactive Modes
All examples support debugging flags for inspecting pipeline internals:
```bash
# Verbose mode - show intermediate data, network variables, fact assertions, rule traces
cargo run -- --scenario festival --verbose # Rust
go run . --scenario festival --verbose # Go
# Step mode - pause at each pipeline stage with explanations
cargo run -- --scenario rescue --step # Rust
go run . --scenario rescue --step # Go
# Combined mode
cargo run -- --scenario bakery --verbose --step
go run . --scenario bakery --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Scenario Data Format
Each scenario directory contains four files:
| File | Purpose | Consumed By |
|------|---------|-------------|
| `model.bif` | Bayesian Network definition in BIF format (variables, parents, CPTs) | Stage 1: BnNetwork |
| `evidence.json` | Observed variable values as `{"variable": "state"}` pairs | Stage 1: BnEvidence |
| `problem.json` | Solver problem with variables, constraints, and objectives | Stage 2: SolverSession |
| `rules.clp` | CLIPS rule definitions for domain-specific safety checks | Stage 3: ClipsProvider |
| `expected-output.json` | Golden output describing expected pipeline results | Testing/validation |
### Adding a New Scenario
1. Create a new directory under `scenarios/`
2. Define the BN model in `model.bif` with evidence and prediction variables
3. Create `evidence.json` with the observed evidence
4. Define the optimization problem in `problem.json`
5. Write CLIPS safety rules in `rules.clp` with appropriate templates
6. Add the scenario's CLIPS template mapping to `knownScenarios` in the source code
7. Create `expected-output.json` with the expected pipeline results
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Event planning | Predict attendance, optimize resource allocation, enforce safety codes |
| Emergency response | Estimate survival windows, deploy rescue assets, enforce operational protocols |
| Manufacturing | Forecast demand, schedule production, enforce quality and safety standards |
| Logistics | Predict delivery volumes, optimize fleet routing, enforce regulatory compliance |
| Healthcare | Predict patient load, optimize staff scheduling, enforce clinical safety protocols |
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
Each scenario includes an `expected-output.json` that describes the expected structure of the pipeline results, useful for regression testing and validation.
---
# BN Structure Learning -- Causal Discovery from Data
URL: https://docs.nxus.systems/nxuskit/examples/integrations/bn-structure-learning
Demonstrates Bayesian Network structure learning: discovering causal relationships directly from observational CSV data, learning parameters, evaluating model fit, and running inference on the learned model. Two structure learning algorithms (Hill-Climb and K2) are compared to identify high-confidence causal links.
> Discover causal structure hidden in your data — learn Bayesian network topology and parameters directly from CSV observations using Hill-Climb and K2 search algorithms.
**Scenarios**: `golf` · `bmx` · `sourdough`
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · BN
- **Summary:** Bayesian network structure learning from data
- **Scenario:** Learn Bayesian network structure from observational data
- **`tech_tags` in manifest:** `BN` — example id **`bn-structure-learning`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go |
|---------|-------------|------|-----|
| **BnNetwork (empty)** | Create an empty network for structure learning | `nxuskit_bn_net_create()` | `NewBnNetwork()` |
| **Hill-Climb Search** | Greedy structure search with edge add/remove/reverse | `nxuskit_bn_search_structure(..., "hill_climb", ...)` | `net.SearchStructure(..., "hill_climb")` |
| **K2 Search** | Order-based structure search with variable ordering | `nxuskit_bn_search_structure(..., "k2", ...)` | `net.SearchStructure(..., "k2")` |
| **BIC Scoring** | Bayesian Information Criterion (penalizes complexity) | `scoring = "bic"` | `Scoring: "bic"` |
| **BDeu Scoring** | Bayesian Dirichlet equivalent uniform scoring | `scoring = "bdeu"` | `Scoring: "bdeu"` |
| **MLE Learning** | Maximum Likelihood Estimation for CPT parameters | `nxuskit_bn_learn_mle()` | `net.LearnMLE()` |
| **Log-Likelihood** | Evaluate model fit against training data | `nxuskit_bn_log_likelihood()` | `net.LogLikelihood()` |
| **VE Inference** | Variable Elimination on the learned model | `nxuskit_bn_infer(..., "ve", ...)` | `net.Infer(ev, "ve")` |
## Technologies
BN
## Pipeline Architecture
```
┌───────────┐ Column names ┌──────────────┐ Learned edges ┌───────────────┐
│ CSV Data │ ───────────────> │ Structure │ ─────────────────> │ Parameter │
│ (200 rows) │ │ Learning │ │ Learning │
└───────────┘ │ (HC / K2) │ │ (MLE) │
└──────────────┘ └───────┬───────┘
│
┌──────────────┐ Fit score ┌──────┴───────┐
│ Algorithm │ <───────────── │ Log- │
│ Comparison │ │ Likelihood │
└──────────────┘ └──────┬───────┘
│
┌──────┴───────┐
│ Inference │
│ (VE) │
└──────────────┘
```
**Step 1 -- Load CSV Data**: Reads the scenario CSV file, discovers column names (which become BN variables) and row count.
**Step 2 -- Hill-Climb + BIC**: Runs greedy structure search starting from an empty graph. At each step, the algorithm tries adding, removing, or reversing an edge, accepting the change that most improves the BIC score. BIC balances fit against model complexity via a log(N) penalty term.
**Step 3 -- K2 + BDeu**: Runs order-based structure search using the CSV column ordering. K2 processes variables in order, greedily adding parent edges that improve the BDeu score. BDeu uses an equivalent sample size (ESS) hyperparameter that controls the strength of the prior.
**Step 4 -- MLE Parameter Learning**: Fits conditional probability tables (CPTs) to the Hill-Climb structure using Maximum Likelihood Estimation with Laplace smoothing (pseudocount=1.0) to avoid zero probabilities.
**Step 5 -- Log-Likelihood Evaluation**: Computes how well the learned model explains the training data. Per-sample log-likelihood allows comparison across different dataset sizes.
**Step 6 -- Inference**: Runs Variable Elimination on the learned model with sample evidence to demonstrate that the learned network supports standard BN queries.
**Step 7 -- Algorithm Comparison**: Compares edges discovered by both algorithms. Shared edges represent high-confidence causal relationships found independently by two different search strategies.
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/bn-structure-learning`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario golf
cargo run -- --scenario bmx --verbose
cargo run -- --scenario sourdough --step
```
### Go
```bash
cd go
make build
./bin/bn-structure-learning --scenario golf
./bin/bn-structure-learning --scenario bmx --verbose
./bin/bn-structure-learning --scenario sourdough --step
```
Or directly:
```bash
cd go
go run . --scenario golf
```
## Scenarios
### Golf (Course Conditions)
Models how weather, soil conditions, maintenance practices, and fertilizer affect golf course playing conditions. The data encodes realistic correlations: rainy weather increases soil moisture, which softens fairways; heavy fertilizer increases green speed; longer mowing increases rough thickness.
- **Variables**: weather, soil_moisture, mowing, foot_traffic, fertilizer, green_speed, fairway_firmness, rough_thickness
- **Expected causal links**: weather -> soil_moisture -> fairway_firmness, fertilizer -> green_speed, mowing -> rough_thickness
- **Inference demo**: P(green_speed | weather=rainy, fertilizer=heavy)
### BMX (Rider Performance)
Models how rider skill, technique, and jump characteristics affect BMX race outcomes. High skill correlates with perfect pump timing and fast speed; extreme jumps with low skill dramatically increase crash risk.
- **Variables**: jump_height, berm_angle, pump_timing, speed, skill, lap_time, crash_risk, style_score
- **Expected causal links**: skill -> pump_timing, skill -> jump_height, speed -> lap_time, jump_height + skill -> crash_risk
- **Inference demo**: P(lap_time | skill=pro, pump_timing=perfect)
### Sourdough (Baking)
Models how feeding schedule, flour choice, temperature, and starter maturity affect sourdough bread characteristics. Warm temperatures with mature starters produce fast rises and dense bubbles; rye flour and infrequent feeding lead to sour flavors.
- **Variables**: feeding_schedule, flour_type, ambient_temp, hydration, starter_age, rise_time, bubble_density, flavor_profile
- **Expected causal links**: ambient_temp + starter_age -> rise_time -> bubble_density, flour_type -> flavor_profile, feeding_schedule -> starter_age
- **Inference demo**: P(flavor_profile | flour_type=rye, ambient_temp=warm)
## Interactive Modes
```bash
# Verbose mode -- show raw JSON results and intermediate data
cargo run -- --scenario golf --verbose # Rust
go run . --scenario golf --verbose # Go
# Step mode -- pause at each step with explanations
cargo run -- --scenario bmx --step # Rust
go run . --scenario bmx --step # Go
# Combined mode
cargo run -- --scenario sourdough --verbose --step
go run . --scenario sourdough --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Structure Learning Concepts
### Hill-Climb vs K2
| Property | Hill-Climb | K2 |
|----------|-----------|-----|
| Search strategy | Greedy local search | Order-based forward search |
| Starting point | Empty graph | Empty graph + variable ordering |
| Operations | Add, remove, reverse edges | Add parent edges only |
| Ordering required | No | Yes (results depend on ordering) |
| Score function | BIC (default) | BDeu (default) |
| Complexity | O(n^2 * max_steps) | O(n^2 * max_parents) |
| Strengths | Flexible, no ordering needed | Fast, principled Bayesian scoring |
| Weaknesses | Can get stuck in local optima | Sensitive to variable ordering |
### Scoring Functions
**BIC (Bayesian Information Criterion)**: `BIC = LL - (k/2) * ln(N)` where LL is log-likelihood, k is the number of free parameters, and N is the sample size. Penalizes complexity more strongly with larger datasets.
**BDeu (Bayesian Dirichlet equivalent uniform)**: A Bayesian score that uses a Dirichlet prior. The equivalent sample size (ESS) parameter controls prior strength: small ESS values prefer simpler structures, large ESS values are more permissive.
### Parameter Learning (MLE)
Maximum Likelihood Estimation counts co-occurrences in the data to estimate conditional probability tables. Laplace smoothing (pseudocount > 0) adds a small count to every cell, preventing zero probabilities that would make log-likelihood undefined.
### Fit Evaluation (Log-Likelihood)
Log-likelihood measures how well the model's CPTs explain the observed data: `LL = sum_i sum_j log P(x_ij | parents(x_j))`. Higher (less negative) values indicate better fit. Per-sample log-likelihood (LL / N) normalizes for dataset size.
## CSV Format Requirements
- **Header row**: First row contains column names (become BN variable names)
- **Encoding**: UTF-8 with LF line endings
- **Delimiter**: Comma-separated values
- **Values**: Categorical (discrete) values only for structure learning
- **Missing values**: Rows with empty cells are skipped with a warning
- **Sorting**: Primary sort by first column, secondary by second column
### Adding a New Scenario
1. Create a new directory under `scenarios/`
2. Add a `data.csv` file with header row and at least 50 data rows
3. Ensure correlations in the data reflect the causal structure you expect to discover
4. Add the scenario configuration to `scenario_config()` (Rust) or `knownScenarios` (Go)
5. Create `expected-output.json` with expected edge ranges and inference results
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Epidemiology | Discover disease risk factor relationships from patient records |
| Manufacturing | Identify root causes of defects from production data |
| Finance | Map causal relationships between economic indicators |
| Genomics | Learn gene regulatory networks from expression data |
| Quality control | Find which process parameters affect product quality |
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
Each scenario includes an `expected-output.json` that describes expected edge count ranges, inference results, and fit evaluation bounds for regression testing.
---
# CLI Assistant Integration
URL: https://docs.nxus.systems/nxuskit/examples/integrations/cli-assistant
Converts natural language queries into shell commands using LLM with streaming output.
> Turn plain English into shell commands instantly — build a streaming CLI assistant that speaks your language and runs in your terminal.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## Overview
This example demonstrates a practical CLI tool that translates human-readable requests into executable shell commands. It showcases streaming for real-time output as the command is generated.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Interactive CLI assistant with LLM backend
- **Scenario:** Build an interactive terminal assistant powered by an LLM
- **`tech_tags` in manifest:** `LLM` — example id **`cli-assistant`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Developer productivity tool, command-line copilot.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Features
- Natural language to shell command translation
- Streaming output shows command as it's generated
- Safety comments for dangerous operations
- Works with common Unix commands
## Example Queries
| Query | Generated Command |
|-------|------------------|
| "find all rust files modified in the last week" | `find . -name "*.rs" -mtime -7` |
| "show disk usage sorted by size" | `du -sh * \| sort -h` |
| "list all running docker containers" | `docker ps` |
## Build
```bash
cd rust && cargo build
cd ../go && make build
```
## Library usage
### Rust
```rust
use nxuskit::prelude::*;
let provider = OllamaProvider::builder().model("llama3").build()?;
let command = generate_command(&provider, query).await?;
println!("Generated: {}", command);
```
### Go
```go
command, err := GenerateCommand(ctx, provider, query)
fmt.Println("Generated:", command)
```
## Run
### Rust
```bash
cd rust
cargo run
# Interactive mode
cargo run -- "your query here"
```
### Go
```bash
cd go
go run .
# Interactive mode
go run . "your query here"
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Safety Considerations
The LLM is instructed to:
- Add warning comments for dangerous operations (rm -rf, etc.)
- Use common, well-known Unix commands
- Provide clarifying comments for ambiguous requests
**Important**: Always review generated commands before executing them.
## Extending the Example
Ideas for enhancement:
1. Add command execution with confirmation prompt
2. Implement command history
3. Add support for platform-specific commands (Windows, macOS, Linux)
4. Include command explanation mode
5. Add syntax highlighting for output
---
# CLIPS Basics
URL: https://docs.nxus.systems/nxuskit/examples/integrations/clips-basics
Load rules, assert facts, and run the CLIPS inference engine
> Bring deterministic rule-based logic to your applications by driving the CLIPS inference engine directly through the nxusKit SDK.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · CLIPS
- **Summary:** CLIPS rule engine basics via nxusKit SDK
- **Scenario:** Load rules, assert facts, and run the CLIPS inference engine
- **`tech_tags` in manifest:** `CLIPS` — example id **`clips-basics`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## CLIPS integration path
This example uses **provider chat**: JSON shaped like `ClipsInput` is sent as the user message body to the CLIPS `LLMProvider`, and the engine returns `ClipsOutput` JSON in `response.content`. Local wire types mirror that contract and are **not** SDK exports: Go `go/clips_wire.go`, Rust via shared crate `examples/shared/clips-wire-rust` (`nxuskit-examples-clips-wire`), Python reference `examples/shared/python/clips_wire.py`.
For **Session API** access (load rules, assert facts, run, inspect via handles), use `nxuskit::ClipsSession`, `nxuskit.ClipsSession`, or the C ABI in the SDK bundle.
Schema reference: `conformance/clips-json-contract.json` in this repository. Full field documentation: nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (heading anchor `#clipsinput-json-reference`; in the extracted bundle, see `docs/rule-authoring.md`).
## Real-World Application
Business rules engine, compliance checking
## Technologies
CLIPS
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `examples/shared/python/clips_wire.py` | Wire types only (use with nxuskit-py provider chat) |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/clips-basics`:
cd rust && cargo build
cd go && make build
```
Cross-language parity: the **animal classification** demos use the same `ClipsInput`-shaped JSON (`facts` → `template` / `values`) in Go (`main.go` example 1 dog; example 2 Frog/Penguin/Spider batch) and Rust (`animal_classification.rs` via `ClipsInputWire`).
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/clips-basics
```
---
# CLIPS+LLM Hybrid Integration
URL: https://docs.nxus.systems/nxuskit/examples/integrations/clips-llm-hybrid
Demonstrates combining CLIPS expert system with LLM for deterministic business rules plus natural language understanding.
> Combine deterministic CLIPS rules with LLM reasoning to build AI pipelines that are both fluent and auditable.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## CLIPS integration path
The CLIPS stage uses **provider chat** (JSON `ClipsInput` in the user message, `ClipsOutput` in `content`). See `go/clips_wire.go` and Rust crate `examples/shared/clips-wire-rust`. For **Session API** usage, use the CLIPS session bindings in your language SDK instead.
Schema: `conformance/clips-json-contract.json`. Documentation: nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## What this demonstrates
**Difficulty: Intermediate** 🟦 · LLM · CLIPS
- **Summary:** Hybrid CLIPS rules + LLM reasoning
- **Scenario:** Combine deterministic CLIPS rules with LLM-based reasoning
- **`tech_tags` in manifest:** `CLIPS, LLM` — example id **`clips-llm-hybrid`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go |
|---------|-------------|------|-----|
| **ClipsProvider** | Rule-based expert system as LLMProvider | ✅ `ClipsProvider::builder()` | ✅ `NewClipsProvider()` |
| **JSON Fact Assertion** | Convert structured data to CLIPS facts | ✅ `ChatRequest` with JSON | ✅ `ChatRequest` with JSON |
| **Conclusion Extraction** | Parse CLIPS output for derived facts | ✅ `ClipsOutput::conclusions` | ✅ `ClipsOutput.Conclusions` |
| **Provider Abstraction** | Same interface for LLM and CLIPS | ✅ `LLMProvider` trait | ✅ `LLMProvider` interface |
| **ResponseFormat** | Structured JSON output from LLM | ✅ `ResponseFormat::Json` | ✅ `JSONMode: true` |
| **Hybrid Pipeline** | LLM → CLIPS → LLM workflow | ✅ `analyze_ticket()` | ✅ `AnalyzeTicket()` |
## Real-World Application
Explainable AI decisions, regulated industry automation.
## Technologies
CLIPS, LLM
## Overview
This example shows the "hybrid AI" pattern: using LLM for natural language understanding and CLIPS for deterministic business decisions. Both Rust and Go implementations use the **real ClipsProvider** to execute CLIPS rules.
## Why Hybrid?
| Approach | Strengths | Weaknesses |
|----------|-----------|------------|
| **LLM only** | Natural language understanding, flexibility | Inconsistent policy application, no audit trail |
| **CLIPS only** | Deterministic, auditable, policy-compliant | Can't understand unstructured text |
| **Hybrid** | Both! Understanding AND compliance | More complex architecture |
## Three-Step Flow
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Step 1 │ │ Step 2 │ │ Step 3 │
│ LLM │ ──► │ CLIPS │ ──► │ LLM │
│ (classify) │ │ (routing) │ │ (response) │
└─────────────┘ └─────────────┘ └─────────────┘
Extract Apply rules Generate
category, deterministic empathetic
priority, team routing, customer
sentiment SLA, escalation response
```
1. **LLM Classification**: Extract category, priority, sentiment, entities from ticket text
2. **CLIPS Routing**: Apply deterministic rules for team assignment, SLA, escalation
3. **LLM Response**: Generate appropriate customer response
## Routing Rules
The CLIPS rules in `ticket-routing.clp` apply:
| Category | Priority | Team | SLA | Escalation |
|----------|----------|------|-----|------------|
| Security | Any | Security | 4h | Level 2 |
| Infrastructure | Critical | SRE | 2h | Level 1 |
| Infrastructure | High | SRE | 4h | Level 1 |
| Application | Critical | Development | 4h | Level 1 |
| Application | High | Development | 8h | None |
| General | Any | General Support | 24h | None |
## Library usage
### Rust (with ClipsProvider)
```rust
use clips_llm_hybrid::analyze_ticket;
use std::path::Path;
// nxusKit: Hybrid analysis using LLM + ClipsProvider
let rules_path = Path::new("ticket-routing.clp");
let result = analyze_ticket(&provider, "llama3", ticket_text, rules_path).await?;
// Deterministic routing from CLIPS (auditable, explainable)
println!("Team: {}", result.team);
println!("SLA: {} hours", result.sla_hours);
// LLM-derived insights (natural language understanding)
println!("Sentiment: {}", result.sentiment);
println!("Response: {}", result.suggested_response);
```
### Go (with ClipsProvider)
```go
// nxusKit: Hybrid analysis using LLM + ClipsProvider
rulesPath := "ticket-routing.clp"
result, err := AnalyzeTicket(ctx, provider, "llama3", ticketText, rulesPath)
// Deterministic routing from CLIPS (auditable, explainable)
fmt.Println("Team:", result.Team)
fmt.Println("SLA:", result.SLAHours, "hours")
// LLM-derived insights (natural language understanding)
fmt.Println("Sentiment:", result.Sentiment)
```
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/clips-llm-hybrid`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## CLIPS Rules File
See `ticket-routing.clp` for the actual CLIPS rules used in the Rust implementation.
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Production Considerations
1. **Rule versioning**: Track changes to CLIPS rules with version control
2. **Audit logging**: Log all routing decisions with rule traces
3. **Fallback handling**: Define default routing for edge cases
4. **Rule testing**: Unit test CLIPS rules independently of LLM
5. **Performance**: Cache common routing patterns
---
# Common-Sense Guardrails
URL: https://docs.nxus.systems/nxuskit/examples/integrations/common-sense-guardrails
> Catch plausible but impossible LLM recommendations by turning answers into facts, firing rules, and repairing failures with auditable prompts.
**Scenarios**: `car-wash` · `coupon-stack` · `pallet-door` · `cold-chain`
## Edition
**Community** - runs the selected guardrail workflow with CLIPS available in CE: raw answer, structured facts, guardrail findings, deterministic repair packet, corrected answer, and reevaluation.
**Edition note:** Runs in Community Edition with CLIPS and selected BN risk scoring. Pro adds Solver/Z3 and ZEN guardrails for repair feedback when selected.
## Pro Enhancement Path
Guardrails are selected with `--guardrails`. The default selection is `auto`, which includes CLIPS, the scenario's Pro mechanism when that mechanism is available, and BN risk scoring for scenarios where uncertainty is meaningful. `--stage ce|pro|all` remains as a compatibility alias for existing smoke commands.
- `clips`: Community rule checks over typed facts. Best for explicit scenario rules and explainable findings.
- `bn`: Community Bayesian Network inference over noisy or partial evidence. Used only for `coupon-stack` and `cold-chain`.
- `solver` / `z3`: Pro constraint feasibility. Used for object-presence and dimensional feasibility scenarios.
- `zen`: Pro decision-table and policy admissibility. Used for promotion policy and cold-chain handling scenarios.
Mock Pro and BN findings are fixture-backed and do not require entitlement. Mock output is explicitly labeled with `mechanism_source: "fixture"` and `runtime_executed: false`. In live mode, explicit Pro guardrail selection requires Pro entitlement and calls `nxuskit-cli solver solve` or `nxuskit-cli zen eval`; explicit BN selection calls `nxuskit-cli bn infer`. In `--guardrails auto`, unavailable Pro guardrails downgrade with a warning and the Community CLIPS/BN paths remain runnable. Set `NXUSKIT_COMMON_SENSE_FIXTURE_LLM=1` for deterministic smoke runs that keep LLM answers/facts fixture-backed while still invoking local CLIPS, BN, and Pro guardrail runtimes.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS · Solver · BN · ZEN
- **Summary:** Progressive LLM guardrails with CE CLIPS, selected BN risk scoring, and optional Pro Solver/ZEN repair feedback.
- **Scenario:** Refine LLM recommendations with structured extraction, selected guardrails, retry repair, and reevaluation.
- **`tech_tags` in manifest:** `LLM`, `CLIPS`, `Solver`, `BN`, `ZEN` - example id **`common-sense-guardrails`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Live LLM calls use an installed nxusKit SDK, and live local guardrails use `nxuskit-cli`. Mock mode uses only Python 3, Bash, and `jq`.
- **Languages in this example:** python, bash.
- **Models:** Live and auto mode can use `NXUSKIT_PROVIDER` with `NXUSKIT_MODEL`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, reachable `OLLAMA_HOST`, or reachable `LMSTUDIO_BASE_URL`.
- **CLIPS:** Community validation is represented by scenario-local CLIPS rule files and normalized findings.
- **BN:** Community Bayesian Network inference uses scenario-local JSON network fixtures and `nxuskit-cli bn infer` in live/fixture-LLM runtime mode.
- **Pro:** Solver/Z3 and ZEN guardrails require nxusKit Pro for live execution. Mock mode simulates their finding shape without invoking the runtime.
## Scenario Purposes
| Scenario | Failure class | Guardrail fit |
|----------|---------------|---------------|
| `car-wash` | Implicit object-presence precondition | CLIPS explains the missing object precondition; Solver/Z3 can prove object-presence feasibility. BN is intentionally not modeled. |
| `coupon-stack` | Promotion policy and margin violation | CLIPS and ZEN handle crisp eligibility; BN adds probabilistic promotion risk and review priority. |
| `pallet-door` | Dimensional feasibility and unsafe geometry | CLIPS catches the rule and Solver/Z3 proves geometry. BN is intentionally not modeled. |
| `cold-chain` | Handling and auditability violation | CLIPS and ZEN handle policy checks; BN combines carrier certification, refrigeration, temperature logging, and handoff evidence into review risk. |
## Run
Canonical Community smoke commands:
```bash
cd examples/integrations/common-sense-guardrails/python
python3 main.py --scenario car-wash --mode mock --stage ce
cd ../bash
bash main.sh --scenario car-wash --mode mock --stage ce
```
Machine-readable parity checks:
```bash
cd examples/integrations/common-sense-guardrails/python
python3 main.py --scenario car-wash --mode mock --guardrails auto --json
cd ../bash
bash main.sh --scenario car-wash --mode mock --guardrails auto --json
```
All launch scenarios:
```bash
for scenario in car-wash coupon-stack pallet-door cold-chain; do
python3 main.py --scenario "$scenario" --mode mock --guardrails auto --json
done
```
## Mode Behavior
- `--mode live`: default. Requires a configured live provider and fails before scenario content is sent if preflight is unavailable.
- `--mode mock`: uses checked-in fixtures for LLM answers, structured facts, guardrail findings, repair packets, and corrected answers. It performs no provider, network, or entitlement preflight.
- `--mode auto`: uses live execution when provider preflight succeeds; otherwise it labels the run as fixture-backed mock mode.
For local guardrail runtime smoke without model variability, export `NXUSKIT_COMMON_SENSE_FIXTURE_LLM=1` and run `--mode live`. The runners use checked-in LLM answers and fact fixtures, then execute CLIPS and the selected BN, Solver/Z3, or ZEN guardrail through the installed CLI. This is useful for validating local runtime and Pro entitlement wiring; it is not a live LLM quality test.
## Guardrail Selection
- `--guardrails auto`: default. Uses CLIPS, adds BN for `coupon-stack` and `cold-chain`, and uses the scenario's Pro mechanism when available. In live mode, Pro unavailability downgrades with a warning.
- `--guardrails clips`: CE-only guardrail loop.
- `--guardrails bn`: Community Bayesian risk/confidence loop for `coupon-stack` and `cold-chain`.
- `--guardrails solver` or `--guardrails z3`: Pro-only feasibility loop for `car-wash` and `pallet-door`.
- `--guardrails zen`: Pro-only policy loop for `coupon-stack` and `cold-chain`.
- `--guardrails clips,bn`: combined Community rule and BN risk guardrails for the BN-enabled scenarios.
- `--guardrails clips,solver`, `--guardrails clips,zen`, or `--guardrails clips,zen,bn`: combined CE + Pro guardrails. If any selected mechanism fails, the prompt is repaired and the answer is retried.
BN is deliberately absent from `car-wash` and `pallet-door`. Those failures are crisp object-presence and geometric feasibility problems, so CLIPS and Solver/Z3 are the primary mechanisms unless future scenarios introduce measurement uncertainty, damage likelihood, or load-stability risk.
Each run retries up to `--max-repair-attempts 3` by default. Every attempt re-extracts facts and reruns the selected guardrails, because a repaired answer can fix one problem and introduce another.
Live structured fact extraction prefers pure JSON. If the model wraps a valid JSON object in prose, the runners extract it and mark the structured-facts stage as `warn`; if no valid JSON object is recoverable after retry, the structured-facts stage is marked `fail` and the run falls back to checked-in fact fixtures so later guardrail stages can still show their behavior.
Provider preflight order is explicit nxusKit provider/model environment, phase-specific model environment, nxusKit-recognized cloud credentials, reachable Ollama, then reachable LM Studio. Do not commit provider credentials or license tokens.
For local Ollama live runs, the Python runner honors `OLLAMA_HOST` and uses a short 5 second connect timeout with a 120 second read timeout because local model responses can be slower than cloud providers. The Python runner requests JSON response format for fact extraction when the installed SDK exposes it, but v1.0.x does not expose provider-level `thinking_mode` in Python. Use the Bash/CLI runner for the strict local proof path because it can pass both `thinking_mode` and `response_format` through `nxuskit-cli call`.
Live runs can use one provider/model for every phase or override phases independently:
```bash
export NXUSKIT_PROVIDER=ollama
export NXUSKIT_MODEL=qwen3.5:4b
export OLLAMA_HOST=http://127.0.0.1:11434
```
Phase-specific provider overrides are also supported with `NXUSKIT_COMMON_SENSE_BASELINE_PROVIDER`, `NXUSKIT_COMMON_SENSE_FACTS_PROVIDER`, and `NXUSKIT_COMMON_SENSE_REPAIR_PROVIDER`. See [OLLAMA_MODELS.md](/nxuskit/examples/integrations/common-sense-guardrails/ollama-models/) for local Ollama model notes from the repository walkthrough.
Strict live smoke is gated separately so mock fallback output is not mistaken for live provider output:
```bash
cd examples/integrations/common-sense-guardrails/bash
RUN_LIVE_SMOKE=1 ./strict_live_smoke.sh
```
Deterministic local runtime smoke for all scenarios:
```bash
export NXUSKIT_COMMON_SENSE_FIXTURE_LLM=1
for scenario in car-wash coupon-stack pallet-door cold-chain; do
python3 main.py --scenario "$scenario" --mode live --guardrails auto --json
done
cd ../bash
for scenario in car-wash coupon-stack pallet-door cold-chain; do
bash main.sh --scenario "$scenario" --mode live --guardrails auto --json
done
```
## Local Model Starting Points
These are dated smoke-test starting points from the DevOps Ollama model-testing notes, not model rankings or product guarantees.
| Model | Why try it |
|-------|------------|
| `qwen3.5:4b` | 2026-05-11/12 local smokes show the desired guardrail-demo shape: naive car-wash answer fails as `walk`, constrained output is parseable, and enhanced object-presence prompting recovers to `drive`; it also has local structured/document evidence. |
| `qwen3.5:2b` | 2026-05-12 local smoke shows the same fail/recover car-wash shape at a smaller 2.7 GB footprint; use it when low-resource local testing matters more than tool-intent strength. |
| `gemma3:1b` or `erukude/omni-json:1b` | 2026-05-09/12 small-model smokes found both useful for very small guardrail demos because they reproduce the naive failure and recover under the enhanced prompt. |
| `nemotron-3-nano:4b` | 2026-05-12 smokes show the car-wash fail/recover target plus a native strict tool-call pass, making it a useful local comparison point. |
Avoid using passing or unparsed baseline behavior as a demo failure source. For example, the same DevOps notes show `phi4-mini-reasoning:3.8b` answering `drive` on the naive prompt and `granite4:350m-h` failing to recover under the enhanced prompt, so neither is a good default for this specific guardrail walkthrough.
## Scenario Data Contract
Each scenario directory contains these required Community files:
```text
problem.json
expected-output.json
rules.clp
mock-baseline.json
mock-facts.json
mock-corrected-facts.json
mock-repair.json
mock-corrected.json
```
Pro-enabled scenarios add one of:
```text
solver-problem.json
decision-model.json
```
BN-enabled scenarios add:
```text
bn-network.json
bn-guardrail.json
```
Structured fact fixtures must include:
- `goal`
- `candidate_actions`
- `objects_required`
- `objects_moved`
- `resources`
- `constraints`
- `policy_context`
- `confidence`
Guardrail findings normalize to `mechanism`, `tier`, `status`, `rule_id`, `severity`, `message`, `evidence`, and `repair_hint`. BN findings use `mechanism: "bn"` and include posterior evidence for `needs_review`. Expected-output fixtures list required stage ids, expected finding rule ids, correction text fragments, and optional Pro or BN stage metadata.
## Adding a Scenario
1. Create `scenarios//`.
2. Add every required Community file listed above.
3. Include a stable `id`, non-empty prompts, and a `repair_template` containing `{findings}` in `problem.json`.
4. Add scenario-local `rules.clp` findings with stable kebab-case rule ids.
5. Add `solver-problem.json` or `decision-model.json` only when the optional Pro stage is meaningful.
6. Add `bn-network.json` and `bn-guardrail.json` only when uncertainty, noisy evidence, or risk scoring is meaningful.
7. Run validation and both contract test suites before updating manifest scenarios.
Authoring validation:
```bash
cd examples/integrations/common-sense-guardrails/python
python3 main.py --validate-scenarios
python3 test_contract.py
cd ../bash
bash main.sh --validate-scenarios
bash test.sh
```
## Public Inspiration
Shout-out to [Haris Rahi](https://harisrahi.ai) and [Tamara Storm](https://www.linkedin.com/in/tamarastorm) for their LinkedIn discussions on the car-wash scenario from Opper.ai, Focus AI, and the HOB benchmark line.
For related engineering notes and release-adjacent writeups, see [nxus.SYSTEMS Field Notes](https://nxus.systems/field-notes).
## Scope Exclusions
This is not a medical, legal, financial, or safety certification system. Do not add PHI, regulated personal data, certification claims, or model-ranking claims to scenarios. The examples demonstrate an engineering pattern for auditable guardrails, not a complete common-sense benchmark.
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| LLM answer validation | Catch plausible recommendations that fail physical, operational, or policy preconditions before they reach users |
| Policy enforcement | Turn free-form answers into facts, apply deterministic rules, and produce auditable repair context |
| Operational decision support | Preserve fast LLM drafting while requiring concrete feasibility evidence for workflow-critical recommendations |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`: extracted bundle or installer layout) for live SDK checks. Mock acceptance commands do not need the SDK.
```bash
# From `/examples/integrations/common-sense-guardrails`:
cd python && python3 main.py --help
cd ../bash && make test
```
---
# Curated Ollama Models
URL: https://docs.nxus.systems/nxuskit/examples/integrations/common-sense-guardrails/ollama-models
This note records local model passes used for the common-sense guardrails walkthrough. The first pass on 2026-05-07 combined `ollama-cache list` SSD residency with `ollama list` installed sizes and filtered to models under 8 GB. Follow-up passes on 2026-05-11 and 2026-05-12 added the car-wash fail/recover smoke shape and structured-output checks.
These are dated smoke-test starting points, not model rankings or product guarantees.
## Source Notes
- Live structured fact extraction prefers pure JSON. If the model wraps a valid JSON object in prose, the Python and Bash runners extract it and mark the structured-facts stage as `warn`. If no valid JSON object is recoverable after retry, the stage is marked `fail` and the run falls back to checked-in fact fixtures so later guardrail stages can still demonstrate their behavior.
- Ollama structured outputs are most reliable when the API `format` field carries JSON or a JSON schema, and Ollama recommends grounding the prompt with the schema and using low temperature. Provider-native structured-output controls are still the robust path for future hardening, but this walkthrough no longer treats structured-facts failure as the expected result.
- Local car-wash smokes found `qwen3.5:4b` to be the best primary walkthrough candidate: small enough for local proof, stronger than the 2B option, and tested against the desired naive `walk` failure plus enhanced `drive` recovery.
- Local car-wash smokes found `qwen3.5:2b` useful as the low-resource option with the same fail/recover shape.
- Small-model smokes also found `gemma3:1b` and `erukude/omni-json:1b` useful for very small demos. `nemotron-3-nano:4b` is useful as a comparison point because separate tool-intent smokes showed native strict behavior.
- `llama3.2` remains a historical target candidate from earlier sweeps, but it is no longer the default recommendation for this walkthrough.
References:
-
-
-
- DevOps Ollama model-testing notes from 2026-05-09 through 2026-05-12
## Recommended Walkthrough Models
Use these first because they are small local smoke-test candidates that match the guardrail demo shape:
| Role | Model | Installed size | Why it is on the list | Walkthrough note |
|------|-------|----------------|------------------------|------------------|
| Primary live walkthrough | `qwen3.5:4b` | 3.4 GB | Stronger small Qwen 3.5 option from the 2026-05-11/12 local smokes. | Desired car-wash shape: naive answer fails as `walk`, constrained output is parseable, and enhanced object-presence prompting recovers to `drive`. Use this first when available. |
| Low-resource walkthrough | `qwen3.5:2b` | 2.7 GB | Smaller Qwen 3.5 option from the 2026-05-12 local smoke. | Same fail/recover car-wash shape at a smaller footprint. Use when local resource constraints matter more than maximum tool-intent strength. |
| Very small demo candidates | `gemma3:1b` or `erukude/omni-json:1b` | 815 MB / 1.4 GB | Very small models that reproduced the demo failure and recovery shape in local smokes. | Useful for constrained machines, but keep the primary docs and walkthrough centered on `qwen3.5:4b`. |
| Comparison candidate | `nemotron-3-nano:4b` | 2.8 GB | Car-wash fail/recover target plus separate native strict tool-call smoke evidence. | Interesting for comparison, but adding it to the main walkthrough can dilute the guardrails story. |
Other observed models:
| Model | Installed size | Use | Walkthrough note |
|-------|----------------|-----|------------------|
| `llama3.2` | 2.0 GB | Historical target candidate. | Earlier local sweeps showed a valid fail/recover shape, but newer release-surface guidance prefers `qwen3.5:4b` primary and `qwen3.5:2b` low-resource. |
| `phi4-mini-reasoning:3.8b` | 3.2 GB | Avoid as default for this scenario. | Answered `drive` on the naive prompt, which removes the intended baseline failure. |
| `granite4:350m-h` | 366 MB | Avoid as default for this scenario. | Failed to recover under the enhanced prompt in local smokes. |
| `qwen3:4b` | 2.5 GB | Historical extraction experiment. | Direct JSON probes were useful, but newer Qwen 3.5 smokes are the better starting point for the full walkthrough. |
## Current Walkthrough Default
Prefer `qwen3.5:4b` for the interactive walkthrough when it is available. It is the primary v1.0.x local proof candidate, remains small enough for a developer laptop, and has current local smoke evidence for the car-wash fail/recover shape.
```bash
export NXUSKIT_PROVIDER=ollama
export NXUSKIT_MODEL=qwen3.5:4b
export OLLAMA_HOST=http://127.0.0.1:11434
```
For a lower-resource run, use the 2B Qwen 3.5 variant:
```bash
export NXUSKIT_PROVIDER=ollama
export NXUSKIT_MODEL=qwen3.5:2b
export OLLAMA_HOST=http://127.0.0.1:11434
```
For phase-specific experiments, keep the stronger model on extraction and repair while trying a smaller baseline:
```bash
export NXUSKIT_PROVIDER=ollama
export NXUSKIT_MODEL=qwen3.5:2b
export NXUSKIT_COMMON_SENSE_FACTS_MODEL=qwen3.5:4b
export NXUSKIT_COMMON_SENSE_REPAIR_MODEL=qwen3.5:4b
export OLLAMA_HOST=http://127.0.0.1:11434
```
## Structured Facts Posture
Provider-native structured-output controls remain the preferred hardening path, especially Ollama JSON/schema formatting and thinking-mode controls when exposed through the installed SDK/CLI surface. In the v1.0.x examples line, the Bash/CLI runner disables thinking for short guardrail calls and requests JSON schema output for fact extraction. The example itself should be described more narrowly: live structured facts can pass with pure JSON, warn when valid JSON is recovered from prose, or fail after retry and fall back to fixtures. Failure is a fallback state, not the expected walkthrough result.
---
# LLM-Solver Hybrid -- Natural Language to Optimized Solutions
URL: https://docs.nxus.systems/nxuskit/examples/integrations/llm-solver-hybrid
Demonstrates using an LLM to translate natural language constraints into structured solver variables and constraints, then feeding them to the Z3-based constraint solver for optimization. Supports mock mode (no API key needed) and live mode with configurable LLM providers.
> Bridge natural language and constraint solvers — let an LLM parse human intent, let Z3 find the optimal answer.
**Scenarios**: `seating` · `dungeon` · `road-trip`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · LLM · Solver
- **Summary:** Hybrid LLM + Z3 solver problem solving
- **Scenario:** Use an LLM to formulate constraints and Z3 to solve them
- **`tech_tags` in manifest:** `LLM, Solver` — example id **`llm-solver-hybrid`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust, python (paths under this directory).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go | Python |
|---------|-------------|------|-----|--------|
| **LLM Chat API** | Send structured prompts to LLM providers | `nxuskit::chat()` | `provider.Chat()` | `provider.chat(..., response_format=ResponseFormat.JSON)` |
| **Constraint Solver** | Z3-based solver session with variables, constraints, objectives | `nxuskit::solver::SolverSession` | `NewSolverSession()` | `nxuskit.solver.SolverSession` |
| **JSON Parsing/Validation** | Parse LLM output into typed variable and constraint definitions | `serde_json` | `encoding/json` | `json` + validation stage |
| **Retry Logic** | Re-prompt LLM on parse failure with error feedback (max 3 attempts) | `call_llm_with_retry()` | Retry loop in Stage 2 | Retry loop in `extract_variables_live()` |
| **Mock Mode** | Deterministic offline testing with pre-computed LLM responses | `--mock` flag | `--mock` (default) | `--mock` / `--no-mock` |
| **Provider Abstraction** | Same pipeline works with Ollama, LM Studio, OpenAI, Claude, Groq, and xAI Grok | `--provider` flag | `--provider` flag | `--provider` flag |
## Real-World Application
Natural language optimization, conversational planning.
## Technologies
LLM, Solver
## Architecture
```
┌──────────────┐ JSON ┌───────────┐ Structured ┌──────────┐
│ Natural Lang │ ──────────> │ LLM │ ──────────────> │ Solver │
│ Constraints │ prompt │ (or Mock) │ variables + │ (Z3) │
└──────────────┘ └───────────┘ constraints └──────────┘
problem.json │
Optimal Solution
```
**Stage 1 -- Load Problem**: Reads the scenario's `problem.json` containing natural language constraints, system prompt, objective definition, solver configuration, and a pre-computed mock LLM response.
**Stage 2 -- Get Structured Constraints**: In mock mode, uses the pre-defined `mock_llm_response` from `problem.json`. In live mode, sends the system prompt and natural language constraints to an LLM provider, parses the JSON response into variables and constraints arrays, and retries up to 3 times on parse failure.
**Stage 3 -- Validate**: Checks that each variable has a name, type, and domain. Verifies that all constraint variable references point to existing variable names. Filters out invalid constraints and reports warnings.
**Stage 4 -- Solve**: Creates a Z3 solver session, adds variables and constraints, sets the optimization objective, and solves. Falls back to satisfiability check if the objective cannot be applied.
**Stage 5 -- Interpret Results**: Renders solver assignments in scenario-specific human-readable format (table assignments, dungeon map, trip itinerary).
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/llm-solver-hybrid`:
cd rust && cargo build
cd go && make build
```
## Run
### Go
```bash
cd go
make build
./bin/llm-solver-hybrid --scenario seating
./bin/llm-solver-hybrid --scenario dungeon --verbose
./bin/llm-solver-hybrid --scenario road-trip --step
```
Or directly:
```bash
cd go
go run . --scenario seating
```
### Rust
```bash
cd rust
cargo run -- --scenario seating
cargo run -- --scenario dungeon --verbose
cargo run -- --scenario road-trip --step
```
### Python
```bash
cd python
python3 main.py --scenario seating
python3 main.py --scenario dungeon --verbose
python3 main.py --scenario road-trip --step
```
## Mock vs Live Mode
### Mock Mode (default)
Mock mode uses the pre-computed `mock_llm_response` from each scenario's `problem.json`. No API key or running LLM server is needed. This is the default for Rust, Go, and Python.
```bash
# Go (mock is the default)
go run . --scenario seating
# Rust (mock is the default)
cargo run -- --scenario seating
# Python (mock is the default)
python3 main.py --scenario seating
```
### Live Mode
Live mode calls a real LLM provider to extract structured constraints from natural language. The LLM response is parsed as JSON and validated before being sent to the solver.
```bash
# Go: disable mock with --no-mock
go run . --scenario seating --no-mock --provider ollama --model llama3.2
# Rust: disable mock with --no-mock
cargo run -- --scenario seating --no-mock --provider ollama --model llama3.2
# Python: disable mock with --no-mock
python3 main.py --scenario seating --no-mock --provider ollama --model llama3.2
```
**Supported providers**: `ollama`, `lmstudio`, `openai`, `claude`, `groq`, `xai`
Use `groq` for Groq (`GROQ_API_KEY`) and `xai` for xAI Grok (`XAI_API_KEY`). The provider id `grok` is intentionally not an alias.
**API key setup** (for cloud providers):
```bash
export OPENAI_API_KEY=sk-...
export ANTHROPIC_API_KEY=sk-ant-...
export GROQ_API_KEY=gsk_...
export XAI_API_KEY=xai-...
```
Local providers (Ollama, LM Studio) require the server to be running but no API key.
## Scenarios
### Seating -- Wedding Dinner Arrangement
Assign 12 wedding guests to 3 tables while respecting social constraints: feuding relatives at different tables, couples together, ex-partners separated, language requirements, and table capacity limits. The solver maximizes a happiness score based on social preferences.
- **Variables**: 12 integer variables (one per guest, domain 1--3)
- **Constraints**: 4 (not-equal, equal, linear capacity)
- **Objective**: maximize happiness
### Dungeon -- Game Level Layout
Generate a 5-room dungeon with boss placement, treasure rooms, and progressive difficulty. The boss must be in the last room, treasure rooms cannot overlap with the boss, and difficulty increases as the player goes deeper.
- **Variables**: 9 integer variables (room assignments, difficulty levels)
- **Constraints**: 5 (equality, not-equal, linear progression)
- **Objective**: maximize total challenge
### Road Trip -- National Park Itinerary
Plan a 14-day road trip visiting 5 national parks (Yosemite, Yellowstone, Zion, Glacier, Grand Canyon). Constraints include minimum days at large parks, geographic ordering (visit nearby parks consecutively), and the total day budget.
- **Variables**: 10 integer variables (days-at and visit-order per park)
- **Constraints**: 4 (linear budget, minimum days, ordering)
- **Objective**: maximize total experience
## Interactive Modes
All examples support debugging flags for inspecting pipeline internals:
```bash
# Verbose mode - show raw LLM responses, parsed JSON, solver details
cargo run -- --scenario seating --verbose # Rust
go run . --scenario seating --verbose # Go
# Step mode - pause at each pipeline stage with explanations
cargo run -- --scenario dungeon --step # Rust
go run . --scenario dungeon --step # Go
# Combined mode
cargo run -- --scenario road-trip --verbose --step
go run . --scenario road-trip --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Retry Logic
When running in live mode, the LLM extraction step uses a retry loop (max 3 attempts):
1. **Attempt 1**: Send the system prompt and natural language constraints to the LLM, requesting JSON output with `variables` and `constraints` arrays.
2. **Parse and validate**: Check that the response is valid JSON, contains non-empty `variables` and `constraints` arrays, and that variables have required fields.
3. **On failure**: Append the failed response and an error-feedback message to the conversation, then re-prompt the LLM. The feedback describes the specific parse error (invalid JSON, empty arrays, missing fields).
4. **After 3 failures**: Fall back to the mock response from `problem.json` and continue the pipeline.
This retry-with-feedback pattern is effective because the LLM sees its own previous attempt and the specific error, allowing it to self-correct.
## Scenario Data Format
Each scenario is defined by a single `problem.json` file in `scenarios//`:
| Field | Type | Purpose |
|-------|------|---------|
| `description` | string | Human-readable scenario description |
| `natural_language_constraints` | string[] | Plain English constraints sent to the LLM |
| `system_prompt` | string | System message instructing the LLM how to respond |
| `objective` | object | Optimization objective (`name`, `direction`, `expression`, `label`) |
| `solver_config` | object | Solver configuration (e.g., `timeout_ms`) |
| `mock_llm_response` | object | Pre-computed LLM output with `variables` and `constraints` arrays |
Each variable in `mock_llm_response.variables` has:
```json
{
"name": "guest_anna_table",
"var_type": "integer",
"label": "Table assignment for Anna",
"domain": { "min": 1, "max": 3 }
}
```
Each constraint in `mock_llm_response.constraints` has:
```json
{
"name": "martha_bob_apart",
"constraint_type": "not_equal",
"label": "Aunt Martha and Uncle Bob at different tables",
"variables": ["guest_martha_table", "guest_bob_table"],
"parameters": {}
}
```
An `expected-output.json` file alongside each `problem.json` describes the expected pipeline results in mock mode, useful for regression testing.
### Adding a New Scenario
1. Create a new directory under `scenarios/`
2. Write a `problem.json` with natural language constraints and a mock LLM response
3. Add the scenario's result interpretation logic to `interpretResults` (Go) or `interpret_result` (Rust)
4. Create an `expected-output.json` with the expected mock-mode results
## Prompt Engineering Notes
The quality of LLM-extracted constraints depends heavily on the system prompt. Tips for writing effective prompts:
1. **Specify the output format explicitly**: Tell the LLM to return JSON with `variables` and `constraints` arrays. Mention the exact field names expected (`name`, `var_type`, `domain`, `constraint_type`, `parameters`).
2. **Define variable types and domains**: Instruct the LLM what variable types are available (`integer`, `boolean`) and how to express domains (`min`/`max` for integers).
3. **List supported constraint types**: Enumerate the solver's supported constraint types (`equal`, `not_equal`, `linear`) so the LLM does not invent unsupported types.
4. **Use concrete examples**: Include a short example variable and constraint in the system prompt to anchor the LLM's output format.
5. **Keep it focused**: One system prompt per domain. A seating-specific prompt outperforms a generic "convert any constraints" prompt.
6. **Request JSON-only output**: Explicitly state "Respond with JSON only" to prevent the LLM from wrapping the response in explanatory text or markdown code fences.
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
Each scenario includes an `expected-output.json` that describes the expected structure of the pipeline results in mock mode, useful for regression testing and validation.
---
# LM Studio
URL: https://docs.nxus.systems/nxuskit/examples/integrations/lmstudio
Connect to a local LM Studio server for desktop LLM inference
> Run LLM inference on your own machine — connect nxusKit to LM Studio and prototype without cloud dependencies or API keys.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Using LM Studio for local inference
- **Scenario:** Connect to a local LM Studio server for desktop LLM inference
- **`tech_tags` in manifest:** `LLM` — example id **`lmstudio`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Developer local testing, offline prototyping
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/lmstudio`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/lmstudio
```
---
# Model Research Harness
URL: https://docs.nxus.systems/nxuskit/examples/integrations/model-research-harness
Research, test, score, rank, and report on model/provider fitness with a provider-neutral nxusKit workflow.
> Research model fitness with provider-neutral runs, Promptfoo import, deterministic policy checks, Bayesian confidence, and dry-run lifecycle recommendations.
**Scenarios**: `basic-ticket-routing` · `promptfoo-import` · `software-dev`
## Edition
**Community** - the default path uses provider-neutral LLM calls, mock/local fixtures, CLIPS-style deterministic policy checks, Bayesian confidence scoring, Promptfoo import, external-runner adapters, and dry-run lifecycle recommendations. Optional configs can use nxusKit CLIPS and Bayesian engines when native SDK dependencies are installed, with fixture-safe fallbacks for the public quickstart.
**Edition note:** Runs in Community Edition. Future Pro profiles may add Solver portfolio optimization and ZEN decision tables.
**Optional Pro profile** - future solver-backed portfolio selection and ZEN decision-table policies require a Pro or trial entitlement. The public quickstart below does not execute Pro code.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS · BN
- **Summary:** Python-first model research and compatibility harness.
- **Scenario:** Import or define evaluation configs, run provider/model test matrices, score outputs, apply policy, aggregate confidence, and write reports.
- **`tech_tags` in manifest:** `LLM, CLIPS, BN` - example id **`model-research-harness`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only - see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** Python is authoritative. CLI/Bash is a thin wrapper around the Python runner.
- **Python:** standard library only for the public mock quickstart. The bundled `.yaml` configs use a strict JSON-compatible YAML subset; PyYAML is optional for broader user-authored YAML.
- **Native CLIPS/BN:** use a Python interpreter with `cffi` installed and an SDK with `python/src` plus `lib/libnxuskit.dylib`. The harness automatically adds `$NXUSKIT_SDK_DIR/python/src` when `NXUSKIT_SDK_DIR` is set; on macOS, avoid Apple/Xcode Python for native-engine runs unless `cffi` is installed there. Set `NXUSKIT_PYTHON=/path/to/python3` for the Bash wrapper when needed.
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Model evaluation | Score model candidates against task-specific outputs and report confidence instead of relying on ad hoc impressions |
| Provider comparison | Compare local and cloud providers through one provider-neutral workflow while keeping capability claims honest |
| Lifecycle policy | Generate dry-run pull, pin, keep, or retest recommendations bounded by deterministic policy |
| Software development workflow research | Exercise code analysis, bug finding, bugfixing, generation, refactoring, and review scenarios with public-safe fixtures |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/model-research-harness`:
cd python && python3 main.py --help
cd bash && bash main.sh --help
```
## Run
Mock mode uses checked-in fixtures. It does not require cloud credentials, Promptfoo, Ollama, or a Pro entitlement.
```bash
cd python
python3 main.py --config ../configs/nxuskit-harness-basic.yaml --mode mock --json
python3 main.py --config ../configs/nxuskit-harness-software-dev.yaml --mode mock --output-dir ../.tmp/software-dev
```
Thin CLI/Bash wrapper:
```bash
cd bash
bash main.sh --config ../configs/nxuskit-harness-basic.yaml --mode mock --json
```
Promptfoo import:
```bash
cd python
python3 main.py --import-promptfoo ../configs/promptfoo-basic.yaml --mode import-promptfoo --json
python3 main.py \
--import-promptfoo ../configs/promptfoo-requires-code.yaml \
--compatibility-report ../.tmp/promptfoo-requires-code-report.json \
--json
```
The second command is intentionally fail-closed: it writes a compatibility report that requires `--allow-code` or `--promptfoo-native-reference`.
## Configs
| Config | Purpose |
|--------|---------|
| `nxuskit-harness-basic.yaml` | Minimal mock quickstart for ticket classification |
| `nxuskit-harness-clips-policy.yaml` | Deterministic CLIPS-style required-field and forbidden-value checks |
| `nxuskit-harness-clips-engine.yaml` | Real nxusKit `ClipsSession` policy execution with Python fallback when native CLIPS is unavailable |
| `nxuskit-harness-bayesian-confidence.yaml` | Posterior confidence from sparse weighted evidence |
| `nxuskit-harness-bn-engine.yaml` | Real nxusKit BN inference over model-fitness evidence with beta fallback when native BN is unavailable |
| `nxuskit-harness-local-vs-cloud.yaml` | Local fixture versus cloud-reference fixture comparison |
| `nxuskit-harness-structured-output.yaml` | Native JSON-mode claims versus harness-side schema validation |
| `nxuskit-harness-lifecycle-policy.yaml` | Dry-run cache and lifecycle recommendations |
| `nxuskit-harness-lifecycle-mutation-fixture.yaml` | Public-safe mutation gate fixture requiring both external and lifecycle approval flags |
| `nxuskit-harness-matrix-template.yaml` | Compact prompt/parameter matrix expansion syntax |
| `nxuskit-harness-native-ollama-template.yaml` | Native Ollama schema, image, thinking, and tool-call knobs behind harness scoring |
| `nxuskit-harness-software-dev.yaml` | Code analysis, bug finding, bugfixing, code generation, refactoring, and review scenarios |
| `nxuskit-harness-external-command-fixture.yaml` | Public-safe fixture contract for wrapping operational runners |
| `nxuskit-harness-devops-ollama-parity.yaml` | Opt-in local adapter shape for a private Ollama research harness checkout |
| `promptfoo-basic.yaml` | Promptfoo-compatible config that imports and runs |
| `promptfoo-requires-code.yaml` | Promptfoo config that requires explicit trust or native-reference mode |
Test blocks may include a `matrix` object to expand variants without duplicating config:
```json
{
"id": "format-{{ prompt_variant }}-think-{{ think }}",
"matrix": {
"prompt_variant": ["baseline", "strict"],
"think": ["off", "low"]
}
}
```
Each combination is merged into `test.vars`, so prompts, ids, and adapter placeholders can reference the generated values.
## Operational Adapter Mode
The harness can wrap existing operational research runners through explicit external-command tests. This is useful when a team already has domain-specific scripts for local Ollama inventory, structured extraction, image/document pipelines, cache policy, or row-level fixture scoring.
External commands are fail-closed and never run unless `--allow-external` is supplied:
```bash
cd python
python3 main.py \
--config ../configs/nxuskit-harness-external-command-fixture.yaml \
--allow-external \
--json
```
The fixture config runs only checked-in deterministic fixture commands. The DevOps parity config is a template for private/local use and expects `OLLAMA_MODEL_TESTING_ROOT` to point at an existing `ollama-model-testing` checkout:
```bash
export OLLAMA_MODEL_TESTING_ROOT=/path/to/ollama-model-testing
cd python
python3 main.py \
--config ../configs/nxuskit-harness-devops-ollama-parity.yaml \
--allow-external \
--only-test common-sense-carwash \
--output-dir ../.tmp/devops-parity
```
Use `--exclude-test` to skip expensive tests from a larger config. Both `--only-test` and `--exclude-test` accept comma-separated ids and may be repeated.
The public adapter normalizes DevOps-style report shapes for common-sense curation, prompted/native tool intent, direct structured extraction, two-stage OCR or VLM pipelines, safe-labs row-level scoring, and CSV/TSV comparison helpers. The DevOps parity template also includes non-mutating `ollama-cache status`, `list`, and `plan-evict` checks.
External lifecycle mutation such as pulling, removing, pinning, or evicting models requires a test with `external_command.mutation: true` and both flags:
```bash
python3 main.py \
--config ../configs/nxuskit-harness-lifecycle-mutation-fixture.yaml \
--allow-external \
--allow-lifecycle-mutations
```
Public configs should keep mutation commands behind explicit customer policy bounds.
## Output
Each run can write:
- `result.json`
- `summary.md`
- Promptfoo compatibility report when importing Promptfoo configs
- Scenario-level pass/fail matrix
- Provider/model recommendation table
- Capability truth table
The capability truth table separates native provider guarantees from harness-side validation and repair. For v1.0.0, Groq remains provider id `groq` with `GROQ_API_KEY`; xAI Grok uses provider id `xai` with `XAI_API_KEY`.
## Live Mode
Live mode uses nxusKit provider factories for `ollama`, `lmstudio`, `openai`, `claude`, `groq`, and `xai` when credentials or local services are configured:
```bash
cd python
python3 main.py --config ../configs/nxuskit-harness-basic.yaml --mode live --provider ollama --model llama3.2
```
Strict schema support, native tool calling, and thinking controls vary by provider and model. The harness reports those differences instead of treating every backend as equivalent.
For Ollama features that are not yet normalized across every provider, set `native_ollama: true` on the provider or test. That path uses Ollama's local `/api/chat` API directly and supports `schema`/JSON `format`, `think`, `tools`, image files, `options`, and `num_predict`. If an Ollama build rejects the `think` field, the harness retries once without it and records the observed metadata.
## Promptfoo Compatibility
Portable Promptfoo configs import directly. Prompt/provider matrices expand to harness tests. Configs with executable or provider-native behavior fail closed unless the caller acknowledges the trust boundary:
```bash
python3 main.py --import-promptfoo ../configs/promptfoo-requires-code.yaml --allow-code --json
python3 main.py --import-promptfoo ../configs/promptfoo-requires-code.yaml --promptfoo-native-reference --json
```
With `--allow-code`, JavaScript assertions are executed through `node` when available. Unsupported assertions still fail closed instead of silently disappearing from the score.
## nxusKit Engine Hooks
The default configs are fixture-safe and run with stdlib Python. Engine configs demonstrate how the same harness can call nxusKit-native reasoning providers:
- `policy.engine: "nxuskit-clips"` loads a CLIPS rules file through `ClipsSession`, asserts the model output as a fact, and converts emitted finding facts into policy dispositions. `on_engine_unavailable: "fallback-python"` keeps public smoke tests runnable when native CLIPS dependencies are not installed.
- `bayesian.engine: "nxuskit-bn"` loads a BIF model through nxusKit BN, maps test scores into evidence, and queries a configured posterior. `on_engine_unavailable: "fallback-beta"` keeps reports useful on machines without native BN dependencies.
Native-engine smoke example:
```bash
export NXUSKIT_SDK_DIR="${NXUSKIT_SDK_DIR:-$HOME/.nxuskit/sdk/current}"
export NXUSKIT_LIB_PATH="$NXUSKIT_SDK_DIR/lib/libnxuskit.dylib"
# Pick a Python with cffi installed. On this development Mac, Homebrew Python works.
/opt/homebrew/bin/python3 -c "import cffi"
/opt/homebrew/bin/python3 python/main.py \
--config configs/nxuskit-harness-clips-engine.yaml \
--json
/opt/homebrew/bin/python3 python/main.py \
--config configs/nxuskit-harness-bn-engine.yaml \
--json
```
## Release Notes For Review
- Python is the authoritative implementation. Bash remains a thin wrapper for automation-friendly entry points.
- Promptfoo import covers common portable config shapes, prompt/provider matrices, explicit trust gates for code/native behavior, and JavaScript assertion execution under `--allow-code`.
- CLIPS and Bayesian examples include both deterministic/fallback checks and opt-in nxusKit-native engine execution.
- Operational parity is provided through explicit external-command adapters, not private baked-in assumptions. Public releases should keep private rankings, fixture paths, and cache policy defaults out of bundled configs.
- Lifecycle mutation remains blocked unless both `--allow-external` and `--allow-lifecycle-mutations` are supplied, and customer auto-approval should be bounded in config.
---
# Ollama
URL: https://docs.nxus.systems/nxuskit/examples/integrations/ollama
Connect to a local Ollama instance for private LLM inference
> Run open-source LLMs on your own hardware using the same nxusKit interface you already use for Claude and OpenAI.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Using Ollama for local inference
- **Scenario:** Connect to a local Ollama instance for private LLM inference
- **`tech_tags` in manifest:** `LLM` — example id **`ollama`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
On-premise AI deployment, air-gapped inference
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/ollama`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/ollama
```
---
# ZEN Decision Tables -- Personality Variants & Hit Policies
URL: https://docs.nxus.systems/nxuskit/examples/integrations/zen-decisions
Demonstrates ZEN JSON Decision Model (JDM) evaluation through three scenarios: a maze-navigating rat with interchangeable personality variants, a potion recipe selector using collect hit policy, and a food truck planner combining decision tables with expression nodes. This is the first nxusKit example built on the ZEN decision engine.
> Evaluate business decision tables in Go, Rust, and Python using the ZEN engine — from pricing rules to eligibility checks, with first-hit and collect hit policies.
**Scenarios**: `maze-rat` · `potion` · `food-truck`
## Edition
**Pro** — requires a Pro (or trial) entitlement for ZEN evaluation APIs.
## What this demonstrates
**Difficulty: Starter** 🟢 · ZEN
- **Summary:** ZEN decision table evaluation via nxusKit SDK
- **Scenario:** Evaluate business decision tables using the ZEN engine
- **`tech_tags` in manifest:** `ZEN` — example id **`zen-decisions`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go |
|---------|-------------|------|-----|
| **ZEN Evaluate** | Stateless JDM evaluation | `nxuskit_zen_evaluate()` | `nxuskit-go.ZenEvaluate()` |
| **First Hit Policy** | Return first matching rule | `"hitPolicy": "first"` | `"hitPolicy": "first"` |
| **Collect Hit Policy** | Return all matching rules | `"hitPolicy": "collect"` | `"hitPolicy": "collect"` |
| **Expression Nodes** | Computed fields in pipeline | `expressionNode` | `expressionNode` |
| **Personality Variants** | Same input, different models | Multiple JDM files | Multiple JDM files |
| **Result Freeing** | Memory management for results | `nxuskit_zen_free_result()` | Automatic (Go wrapper) |
## Real-World Application
Pricing rules, eligibility determination, policy evaluation.
## Technologies
ZEN
## Pipeline Architecture
### Maze Rat (First Hit Policy)
```
┌──────────────────┐
│ cautious JDM │──> action: sniff_around
└──────────────────┘
┌───────────┐ ┌──────────────────┐
│ Input │──┬──>│ greedy JDM │──> action: go_right
│ (shared) │ │ └──────────────────┘
└───────────┘ │ ┌──────────────────┐
└──>│ explorer JDM │──> action: go_right
└──────────────────┘
```
### Potion (Collect Hit Policy)
```
┌───────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Input │──>│ Decision Table │──>│ All Matching │
│ │ │ (collect policy) │ │ Recipes │
└───────────┘ └──────────────────┘ └──────────────────┘
```
### Food Truck (Decision + Expression Pipeline)
```
┌───────────┐ ┌──────────────────┐ ┌──────────────────┐ ┌──────────┐
│ Input │──>│ Decision Table │──>│ Expression Node │──>│ Output │
│ │ │ (location/price) │ │ (menu/restock) │ │ │
└───────────┘ └──────────────────┘ └──────────────────┘ └──────────┘
```
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/zen-decisions`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario maze-rat
cargo run -- --scenario potion --verbose
cargo run -- --scenario food-truck --step
```
### Go
```bash
cd go
make build
./bin/zen-decisions --scenario maze-rat
./bin/zen-decisions --scenario potion --verbose
./bin/zen-decisions --scenario food-truck --step
```
Or directly:
```bash
cd go
go run . --scenario maze-rat
```
## Scenarios
### Maze Rat (Personality Variants)
A maze-navigating rat with three interchangeable personality variants, each encoded as a separate JDM file. All share the same input schema but produce different actions.
**Input fields**: `scent_strength` (1-10), `dead_ends_nearby` (0-5), `hunger_level` (1-10)
**Output fields**: `action` (go_left, go_right, backtrack, sniff_around, rest), `confidence` (0.0-1.0)
| Personality | Strategy | Key Trait |
|-------------|----------|-----------|
| **Cautious** | Avoids dead ends, backtracks when risky | High dead_ends triggers backtrack |
| **Greedy** | Always follows scent, ignores dead ends | Strong scent always means go_right |
| **Explorer** | Seeks new paths, ignores scent | Prefers go_left to explore unknown areas |
With the default input (`scent_strength=7, dead_ends_nearby=2, hunger_level=4`):
- Cautious: sniff_around (0.60 confidence) -- strong scent but hesitant
- Greedy: go_right (0.95 confidence) -- immediately follows strong scent
- Explorer: go_right (0.80 confidence) -- few dead ends, worth exploring right
### Potion (Collect Hit Policy)
A potion recipe selector that returns all matching recipes using the collect hit policy. Multiple recipes can match the same ingredients and desired effect.
**Input fields**: `ingredients` (comma-separated list), `desired_effect` (healing, strength, invisibility, speed), `caution_level` (low, medium, high)
**Output fields**: `recipe_name`, `recipe_steps`, `warnings`
With the default input (`ingredients=mushroom,moonstone, desired_effect=healing, caution_level=medium`):
- Healing Tonic (mushroom + healing matches)
- Unknown Brew (default catch-all also matches under collect policy)
### Food Truck (Expression Nodes)
A food truck location and menu planner that chains a decision table with an expression node. The decision table selects location and base pricing; the expression node computes menu adjustments.
**Input fields**: `time_of_day`, `weather`, `nearby_events`, `inventory_level`
**Output fields**: `location`, `price_multiplier`, `menu_adjustment`, `restock_alert`
With the default input (`time_of_day=lunch, weather=sunny, nearby_events=large, inventory_level=medium`):
- Location: Main Street Park (lunch + sunny + large event)
- Price multiplier: 1.3 (premium for large event)
- Menu: full menu (medium inventory)
- Restock alert: false
## Decision Table Concepts
### Hit Policies
| Policy | Behavior | Use Case |
|--------|----------|----------|
| **first** | Return the first matching rule | Prioritized rules, fallback chains |
| **collect** | Return all matching rules | Multiple recommendations, audit trails |
With **first** hit policy, rule order matters -- the first match wins. With **collect**, all matching rules are returned as an array.
### Expression Nodes
Expression nodes compute derived fields using simple expressions:
```json
{
"type": "expressionNode",
"content": {
"expressions": [
{"key": "output_field", "value": "input_field"},
{"key": "computed", "value": "if condition then 'a' else 'b'"}
]
}
}
```
Expressions support:
- Field references: `field_name` passes through a value
- Conditionals: `if condition then value1 else value2`
- Comparisons: `==`, `!=`, `>`, `<`, `>=`, `<=`
- String literals: `'single quoted'`
### CLIPS vs ZEN Comparison
| Aspect | CLIPS (Rule Engine) | ZEN (Decision Tables) |
|--------|--------------------|-----------------------|
| **Model format** | `.clp` rule files | `.json` JDM files |
| **Evaluation** | Forward-chaining inference | Table lookup + expressions |
| **State** | Working memory (facts) | Stateless per evaluation |
| **Complexity** | Arbitrary rule logic | Structured table/expression |
| **Best for** | Complex reasoning chains | Configuration-driven decisions |
| **Hit policies** | N/A (all matching rules fire) | first, collect |
| **Session management** | Required (create/destroy) | None (stateless) |
## JDM (JSON Decision Model) Format
The JDM format follows the GoRules specification:
```json
{
"contentType": "application/vnd.gorules.decision",
"edges": [
{"id": "e1", "sourceId": "input", "targetId": "dt1", "type": "edge"}
],
"nodes": [
{"id": "input", "type": "inputNode", ...},
{"id": "dt1", "type": "decisionTableNode", "content": {...}},
{"id": "output", "type": "outputNode", ...}
]
}
```
### Supported Node Types
| Type | Description |
|------|-------------|
| `inputNode` | Entry point; passes input data to connected nodes |
| `outputNode` | Exit point; returns the final result |
| `decisionTableNode` | Evaluates input against rules with configurable hit policy |
| `expressionNode` | Computes derived fields from expressions |
| `switchNode` | Routes to different branches based on conditions |
**Note**: `functionNode` (JavaScript) is not supported by the nxusKit ZEN provider.
### Rule Field Formats
- Comparison operators: `> 30`, `<= 10`, `>= 7`, `== 5`, `!= 0`
- String values (in outputs): `"\"cool\""` (double-quoted inside JSON)
- Numeric values: `0.85`, `1.3`
- Boolean values: `true`, `false`
- Empty field: `""` (matches any value / wildcard)
## Interactive Modes
```bash
# Verbose mode -- show raw JSON results
cargo run -- --scenario maze-rat --verbose # Rust
go run . --scenario maze-rat --verbose # Go
# Step mode -- pause at each step with explanations
cargo run -- --scenario potion --step # Rust
go run . --scenario potion --step # Go
# Combined mode
cargo run -- --scenario food-truck --verbose --step
go run . --scenario food-truck --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
Each scenario includes an `expected-output.json` that describes expected results for regression testing.
---
# Auth Helper
URL: https://docs.nxus.systems/nxuskit/examples/patterns/auth-helper
Demonstrates OAuth login flow and credential management using the nxuskit SDK.
> Wire up OAuth flows and API key credentials across every provider your app supports, with a single unified auth interface.
**Scenarios**: `status` · `set` · `remove` · `dashboard`
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · Auth · OAuth
- **Summary:** OAuth login flow and credential management helper *(from `conformance/examples_manifest.json`: **auth-helper**)*.
- **Scenario:** List providers, check auth status, set credentials, initiate OAuth flows.
- **`tech_tags`:** `Auth`, `OAuth`.
- Listing all supported providers and their authentication methods
- Checking authentication status for individual providers
- Setting and removing API key credentials
- Initiating an OAuth login flow (for OAuth-capable providers)
- Viewing a complete authentication status dashboard
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** Go, Rust (CLI and egui GUI).
## Tier
Community (free)
## Languages
| Language | Path | Description |
|----------|------|-------------|
| Go | [go/](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/auth-helper/go/) | CLI-based auth management |
| Rust (CLI) | [cli/](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/auth-helper/cli/) | Terminal-based OAuth + credential management |
| Rust (core) | [core/](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/auth-helper/core/) | Shared auth library used by CLI and egui |
| Rust (egui) | [egui/](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/auth-helper/egui/) | GUI-based OAuth flow with egui |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# Go
cd go && make build
# Rust CLI
cd cli && cargo build
# Rust GUI (requires egui dependencies)
cd egui && cargo build
```
## Run
```bash
# Go
cd go && ./bin/auth-helper
# Rust CLI
cd cli && cargo run
# Rust GUI
cd egui && cargo run
```
## Notes
- No current providers support OAuth yet (infrastructure is ready for future providers)
- API key authentication works with all providers that require credentials
- The OAuth flow launches a browser and starts a localhost callback server
---
# Basic Chat
URL: https://docs.nxus.systems/nxuskit/examples/patterns/basic-chat
Send a single chat message and receive a response.
> Send your first LLM chat message in minutes, then swap providers without touching your application code.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Basic chat completion with a simple prompt
- **Scenario:** Send a single chat message and receive a response
- **`tech_tags` in manifest:** `LLM` — example id **`basic-chat`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Customer support chatbot, FAQ assistant
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
## Build
Use an installed SDK (`NXUSKIT_SDK_DIR`); from the repo root, `scripts/test-examples.sh` patches `nxuskit` path deps to that tree and builds this crate.
```bash
cd rust && cargo build
cd ../go && make build
cd ../python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/basic-chat
```
### Python
```bash
cd python
python main.py
```
See also: [`EXAMPLE_README_TEMPLATE.md`](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/examples/EXAMPLE_README_TEMPLATE.md) for the standard README sections.
---
# Bayesian Inference Pattern
URL: https://docs.nxus.systems/nxuskit/examples/patterns/bayesian-inference
Demonstrates Bayesian Network inference using multiple algorithms: load a BIF model, set observed evidence, and compute posterior probability distributions over unobserved variables using exact and approximate methods.
> Run exact and approximate Bayesian inference on real-world diagnostic models using four algorithms and three themed scenarios — all from a single SDK call.
**Scenarios**: `haunted-house` · `coffee-shop` · `plant-doctor`
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · BN
- **Summary:** Bayesian network inference via nxusKit SDK
- **Scenario:** Build a Bayesian network and perform probabilistic inference
- **`tech_tags` in manifest:** `BN` — example id **`bayesian-inference`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **BIF Model Loading** | Parse Bayesian Interchange Format files into a directed acyclic graph with conditional probability tables |
| **Evidence Setting** | Clamp observed variables to known values before inference |
| **Variable Elimination (VE)** | Exact inference by marginalizing out variables in an optimal elimination order |
| **Junction Tree (JT)** | Exact inference via clique tree message passing with global consistency |
| **Loopy Belief Propagation (LBP)** | Approximate inference via iterative message passing on the factor graph |
| **Gibbs Sampling** | Approximate MCMC inference by sampling each variable conditioned on its Markov blanket |
| **Streaming Results** | Progressive output of posteriors as each algorithm step completes |
| **Algorithm Comparison** | Side-by-side comparison of exact and approximate posteriors with tolerance checking |
**Provider Compatibility**: Uses the nxusKit Bayesian Network provider (no LLM provider required)
## Technologies
BN
## Pattern Overview
Many real-world diagnosis and prediction problems can be modeled as Bayesian Networks -- directed acyclic graphs where nodes represent random variables and edges encode conditional dependencies. Given partial observations (evidence), inference computes updated beliefs (posteriors) about unobserved variables. This pattern walks through four inference algorithms on scenario-driven models loaded from BIF files, comparing exact and approximate results.
## Scenarios
Three themed scenarios are included under `scenarios/`:
- **Haunted House** -- Investigate a supposedly haunted house by observing cold spots, flickering lights, and muddy footprints, then infer the probability of a ghost, raccoon, wiring fault, and cold draft. 8 variables, 8 CPTs.
- **Coffee Shop** -- Diagnose a bad espresso shot by observing bitter taste, no sourness, and no wateriness, then infer extraction level, grind size, water temperature, bean age, and freshness. 8 variables, 8 CPTs.
- **Plant Doctor** -- Diagnose a sick plant by observing yellow leaves, wilting, no spots, and slow growth, then infer overwatering, nutrient deficiency, sunlight issues, disease, and pest infestation. 9 variables, 9 CPTs.
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/bayesian-inference`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario haunted-house
cargo run -- --scenario coffee-shop --verbose
cargo run -- --scenario plant-doctor --step
```
### Go
```bash
cd go
make build
./bin/bayesian-inference --scenario haunted-house
./bin/bayesian-inference --scenario coffee-shop --verbose
./bin/bayesian-inference --scenario plant-doctor --step
```
### Python
```bash
cd python
pip install -e ../../../../packages/nxuskit-py # if not already installed
python main.py --scenario haunted-house
python main.py --scenario coffee-shop --step
```
## Inference Steps
Each run progresses through four algorithm steps:
| Step | Algorithm | Type | What It Does |
|------|-----------|------|--------------|
| 1 | **Variable Elimination** | Exact | Eliminates variables one at a time, computing exact marginal posteriors via factor multiplication and summation |
| 2 | **Junction Tree** | Exact | Builds a clique tree from the model, propagates messages for globally consistent exact posteriors |
| 3 | **Loopy Belief Propagation** | Approximate | Passes messages iteratively on the factor graph until convergence (or max iterations) |
| 4 | **Gibbs Sampling** | Approximate | Draws MCMC samples from the posterior, estimating marginals from sample frequencies |
## Scenario Data Format
Each scenario is a directory containing two files:
### `model.bif` -- Bayesian Interchange Format
Defines the network structure, variable domains, and conditional probability tables:
```bif
network unknown {
}
variable ghost {
type discrete [ 2 ] { yes, no };
}
variable cold_spots {
type discrete [ 2 ] { yes, no };
}
probability ( ghost ) {
table 0.05, 0.95;
}
probability ( cold_spots | ghost, cold_draft ) {
(yes, yes) 0.9, 0.1;
(yes, no) 0.8, 0.2;
(no, yes) 0.6, 0.4;
(no, no) 0.05, 0.95;
}
```
### `evidence.json` -- Observed Variables
Maps variable names to their observed values:
```json
{
"cold_spots": "yes",
"flickering_lights": "yes",
"footprints": "muddy"
}
```
### `expected-output.json` -- Golden Output
Contains exact posteriors from VE/JT and tolerance bounds for LBP/Gibbs, plus qualitative observations about the inference results. Used for automated validation of implementation correctness.
## Algorithm Comparison
| Property | Variable Elimination | Junction Tree | Loopy BP | Gibbs Sampling |
|----------|---------------------|---------------|----------|----------------|
| **Type** | Exact | Exact | Approximate | Approximate |
| **Method** | Factor marginalization | Clique tree message passing | Iterative factor graph messages | MCMC sampling |
| **Guarantees** | Exact posteriors | Exact posteriors | No convergence guarantee on loopy graphs | Converges asymptotically |
| **Speed** | Fast for small networks | Fast after tree construction | Fast per iteration, may need many | Slow (many samples needed) |
| **Memory** | Exponential in treewidth | Exponential in max clique size | Linear in edges | Linear in variables |
| **Best For** | Small-medium networks | Repeated queries on same model | Large networks with weak loops | Complex models, posterior samples |
| **Parameters** | Elimination order | None (automatic) | Max iterations, damping factor | Num samples, burn-in, seed |
VE and JT should produce identical posteriors (both are exact). LBP and Gibbs posteriors should fall within the tolerance bounds specified in `expected-output.json`.
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Haunted House | Fault diagnosis, anomaly detection, sensor fusion from multiple noisy sensors pointing to hidden causes |
| Coffee Shop | Manufacturing quality control, process parameter tuning, root cause analysis in production |
| Plant Doctor | Medical diagnosis, agricultural advisory systems, multi-symptom differential diagnosis |
## Interactive Modes
All implementations support debugging flags:
```bash
# Verbose mode - show CPTs, elimination orders, message schedules, and sample traces
cargo run -- --scenario haunted-house --verbose # Rust
./bin/bayesian-inference --scenario haunted-house --verbose # Go
python main.py --scenario haunted-house --verbose # Python
# Step mode - pause at each algorithm with explanations
cargo run -- --scenario haunted-house --step # Rust
./bin/bayesian-inference --scenario haunted-house --step # Go
python main.py --scenario haunted-house --step # Python
# Combined mode
cargo run -- --scenario haunted-house --verbose --step
```
Or use environment variables (Rust and Go only):
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python
cd python && python -m pytest
```
## Production Considerations
1. **Algorithm selection**: Use VE or JT for small-to-medium networks where exact inference is tractable. Switch to LBP or Gibbs for large networks where treewidth makes exact inference infeasible.
2. **Convergence monitoring**: LBP may not converge on graphs with strong loops. Monitor message deltas and set a maximum iteration count.
3. **Sample size tuning**: For Gibbs sampling, increase `num_samples` and `burn_in` for tighter posterior estimates. Use a fixed seed for reproducibility in testing.
4. **Evidence validation**: Verify that evidence variable names and values match the BIF model before running inference. Mismatched evidence silently produces incorrect posteriors.
---
# Blocking API
URL: https://docs.nxus.systems/nxuskit/examples/patterns/blocking-api
Make synchronous LLM calls without async runtime
> Call LLMs synchronously from any Rust code — no async runtime required, no await syntax, no tokio dependency to manage.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Synchronous blocking API for simpler use cases
- **Scenario:** Make synchronous LLM calls without async runtime
- **`tech_tags` in manifest:** `LLM` — example id **`blocking-api`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
CLI tools, batch processing scripts
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/blocking-api`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/blocking-api
```
---
# Capability Detection
URL: https://docs.nxus.systems/nxuskit/examples/patterns/capability-detection
Query provider capabilities before dispatching requests
> Stop hardcoding model names — query provider capabilities at runtime and let task requirements drive model selection across any LLM backend.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Detecting provider capabilities at runtime
- **Scenario:** Query provider capabilities before dispatching requests
- **`tech_tags` in manifest:** `LLM` — example id **`capability-detection`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Adaptive AI middleware, feature-gated UX
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/capability-detection`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/capability-detection
```
---
# Convenience API
URL: https://docs.nxus.systems/nxuskit/examples/patterns/convenience-api
Use simplified one-liner API for quick LLM calls
> Skip the boilerplate: call any LLM with a single line, letting nxusKit detect your provider and credentials automatically.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** LiteLLM-style convenience API usage
- **Scenario:** Use simplified one-liner API for quick LLM calls
- **`tech_tags` in manifest:** `LLM` — example id **`convenience-api`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Rapid prototyping, scripting with LLM capabilities
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/convenience-api`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/convenience-api
```
---
# Model Router (Cost Tiers) Pattern
URL: https://docs.nxus.systems/nxuskit/examples/patterns/cost-routing
Demonstrates intelligent routing of requests to different models based on task complexity to optimize cost and quality.
> Route every LLM request to the right model for the job, so you stop paying premium prices for economy-grade tasks.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Cost-aware provider routing and selection
- **Scenario:** Route requests to the cheapest capable provider
- **`tech_tags` in manifest:** `LLM` — example id **`cost-routing`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **Provider Abstraction** | Same interface for all models enables seamless tier switching |
| **Request Portability** | `ChatRequest` works identically across model tiers |
| **Token Normalization** | Consistent token usage tracking for cost calculations |
**Provider Compatibility**: Works with any provider supporting multiple models (OpenAI, Ollama, etc.)
## Pattern Overview
Not all prompts need the most expensive model. This pattern analyzes prompt characteristics and routes requests to an appropriate cost tier, balancing quality requirements with cost efficiency.
## Cost Tiers
| Tier | Model | Use Case | Cost |
|------|-------|----------|------|
| Economy | gpt-4o-mini | Simple queries, lookups | $ |
| Standard | gpt-4o | General tasks, explanations | $$ |
| Premium | gpt-4-turbo | Complex analysis, reasoning | $$$ |
## Classification Heuristics
The example uses simple heuristics to classify tasks:
1. **Premium tier triggers**:
- Keywords: "analyze", "compare", "evaluate", "synthesize", "critique"
- Prompt length > 1000 characters
2. **Standard tier**:
- Prompt length > 200 characters (without premium keywords)
3. **Economy tier**:
- Short, simple prompts
## Real-World Application
Cost-optimized AI platform, budget-aware inference.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/cost-routing`:
cd rust && cargo build
cd go && make build
```
## Library usage
### Rust
```rust
use cost_routing::{classify_task, routed_chat, CostTier};
// Classify without making API call
let tier = classify_task(prompt);
println!("Would use: {} tier", tier.as_str());
// Or route and execute
let result = routed_chat(&provider, prompt).await?;
println!("Used {} tier", result.tier.as_str());
```
### Go
```go
// Classify without making API call
tier := ClassifyTask(prompt)
fmt.Println("Would use:", tier.Name(), "tier")
// Or route and execute
result, err := RoutedChat(ctx, provider, prompt)
fmt.Println("Used", result.Tier.Name(), "tier")
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Advanced Classification
For production, consider more sophisticated approaches:
1. **Intent classification**: Use a small model to classify intent first
2. **Historical data**: Learn from past prompt/tier success rates
3. **User preferences**: Allow users to specify quality requirements
4. **Dynamic pricing**: Adjust tiers based on current API pricing
## Production Considerations
1. **Calibration**: Tune thresholds based on your specific use cases
2. **Monitoring**: Track accuracy and cost savings by tier
3. **Override capability**: Allow manual tier selection for edge cases
4. **A/B testing**: Validate routing decisions improve outcomes
---
# Multi Provider
URL: https://docs.nxus.systems/nxuskit/examples/patterns/multi-provider
Configure and switch between multiple LLM providers at runtime
> Run the same prompt across Claude, OpenAI, and Ollama simultaneously using one unified interface that normalizes responses and token usage.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Using multiple providers in one application
- **Scenario:** Configure and switch between multiple LLM providers at runtime
- **`tech_tags` in manifest:** `LLM` — example id **`multi-provider`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Multi-vendor AI gateway, provider comparison tool
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/multi-provider`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/multi-provider
```
### Python
```bash
cd python
python main.py
```
---
# Polymorphic
URL: https://docs.nxus.systems/nxuskit/examples/patterns/polymorphic
Use trait objects and interfaces to abstract over providers
> Swap LLM providers at runtime without touching your application logic — nxusKit's polymorphic patterns keep your code provider-agnostic from day one.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Polymorphic provider patterns with trait objects
- **Scenario:** Use trait objects and interfaces to abstract over providers
- **`tech_tags` in manifest:** `LLM` — example id **`polymorphic`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Plugin architecture, provider-agnostic application layer
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/polymorphic`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/polymorphic
```
---
# Multi-Provider Fallback Pattern
URL: https://docs.nxus.systems/nxuskit/examples/patterns/retry-fallback
Demonstrates automatic failover between multiple LLM providers for improved reliability.
> Chain multiple LLM providers together so a failed request automatically reroutes to the next available provider without changing your application code.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Retry and fallback strategies across providers
- **Scenario:** Automatically retry failed requests and fall back to alternate providers
- **`tech_tags` in manifest:** `LLM` — example id **`retry-fallback`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **Provider Abstraction** | `LLMProvider` trait/interface enables heterogeneous provider collections |
| **Unified Error Handling** | Same error types across all providers enable consistent fallback logic |
| **Provider Interchangeability** | Swap providers without changing application code |
**Provider Compatibility**: Claude, OpenAI, Ollama, and any custom provider implementing `LLMProvider`
## Pattern Overview
When working with LLM APIs, network issues, rate limits, or provider outages can interrupt service. This pattern chains multiple providers together, automatically falling back to the next provider when one fails.
## Key Features
- Sequential provider chain with automatic failover
- First successful response wins
- Error aggregation for debugging
- Provider-agnostic implementation
## Real-World Application
High-availability AI service, resilient inference pipeline.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/retry-fallback`:
cd rust && cargo build
cd go && make build
```
## Library usage
### Rust
```rust
use retry_fallback::chat_with_fallback;
use nxuskit::prelude::*;
// Create multiple providers (could be different providers in production)
let providers: Vec> = vec![
Box::new(OllamaProvider::builder().base_url("http://primary:11434").model("llama3").build()?),
Box::new(OllamaProvider::builder().base_url("http://secondary:11434").model("llama3").build()?),
];
// Request automatically falls back on failure
let response = chat_with_fallback(&providers, &request).await?;
```
### Go
```go
import llmkit "github.com/llmkit/nxuskit-go"
// Create multiple providers
providers := []llmkit.LLMProvider{provider1, provider2, provider3}
// Request automatically falls back on failure
resp, err := ChatWithFallback(ctx, providers, req)
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
Both implementations include unit tests using mock providers:
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Production Considerations
1. **Provider diversity**: Use different providers (OpenAI, Claude, Ollama) for true redundancy
2. **Timeout handling**: Set appropriate timeouts to avoid long waits before failover
3. **Circuit breakers**: Consider adding circuit breaker pattern for repeated failures
4. **Metrics**: Track which providers are failing to identify systemic issues
---
# Solver Pattern
URL: https://docs.nxus.systems/nxuskit/examples/patterns/solver
Demonstrates the full solver lifecycle: satisfaction checking, single- and multi-objective optimization, soft constraints, and what-if analysis using push/pop scoping.
> Define variables, add constraints, and solve complex planning problems with Z3 — without leaving your nxusKit workflow.
**Scenarios**: `theme-park` · `space-colony` · `fantasy-draft`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · Solver
- **Summary:** Z3 constraint solver integration via nxusKit SDK
- **Scenario:** Define and solve constraint satisfaction problems with Z3
- **`tech_tags` in manifest:** `Solver` — example id **`solver`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **SolverSession Lifecycle** | Create, build model incrementally, solve, and close via the nxuskit SDK |
| **Variable & Constraint Model** | Define typed variables with domains and add hard/soft constraints |
| **Satisfaction Solving** | Check feasibility before optimizing |
| **Single & Multi-Objective Optimization** | Maximize/minimize one or many weighted objectives |
| **Soft Constraints** | Weighted preferences the solver satisfies when possible |
| **Push/Pop Scoping** | Reversible what-if analysis without rebuilding the model |
**Provider Compatibility**: Uses the nxusKit Z3-based constraint solver (no LLM provider required)
## Technologies
Solver
## Pattern Overview
Many real-world planning problems require finding valid assignments to decision variables that satisfy a set of constraints, then optimizing one or more objectives. This pattern walks through five progressive solver steps using scenario-driven problem definitions loaded from JSON files.
## Scenarios
Three themed scenarios are included under `scenarios/`:
- **Theme Park Planning** -- Decide how many rides to build, staff to hire, land to allocate, and ticket prices to set while staying within budget and space constraints. Objectives: maximize rides, minimize budget.
- **Space Colony Planning** -- Design a self-sustaining colony by balancing population against habitat modules, solar panels, water recyclers, and food domes. What-if: simulate a solar storm that degrades panel efficiency by 30%.
- **Fantasy Sports Draft** -- Build an optimal roster under a $50,000 salary cap by selecting stats across QB, RB, WR, TE, and DEF positions to maximize total fantasy points. What-if: simulate key player injuries.
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/solver`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario theme-park
cargo run -- --scenario space-colony --verbose
cargo run -- --scenario fantasy-draft --step
```
### Go
```bash
cd go
make build
./bin/solver --scenario theme-park
./bin/solver --scenario space-colony --verbose
./bin/solver --scenario fantasy-draft --step
```
### Python
```bash
cd python
pip install -e ../../../../packages/nxuskit-py # if not already installed
python main.py --scenario theme-park
python main.py --scenario fantasy-draft --step
```
## Solver Steps
Each run progresses through five steps (steps are skipped when a scenario lacks the relevant definitions):
| Step | Name | What It Does |
|------|------|--------------|
| 1 | **Satisfaction** | Adds hard constraints and checks whether any feasible assignment exists (`sat` / `unsat`) |
| 2 | **Optimization** | Sets a single objective (maximize or minimize) and finds the optimal assignment |
| 3 | **Multi-objective** | Combines multiple objectives with weights into a single weighted optimization |
| 4 | **Soft constraints** | Adds weighted preference constraints the solver may violate if necessary |
| 5 | **What-if analysis** | Uses `push` / `pop` to temporarily add constraints, solve, then restore the base model |
## Scenario Data Format
Each scenario is a directory containing a `problem.json` file with the following structure:
```jsonc
{
"name": "Scenario Name",
"description": "Human-readable description of the planning problem.",
"variables": [
{
"name": "budget",
"var_type": "integer", // "integer", "real", or "boolean"
"domain": { "min": 50000, "max": 500000 }, // omitted for booleans
"label": "Total budget in dollars"
}
],
"constraints": [
{
"name": "cost_constraint",
"constraint_type": "ge", // "ge", "le", "eq", etc.
"variables": ["budget", "ride_count"],
"parameters": {}, // solver-specific parameters
"expression": "budget >= ride_count * 25000", // human-readable
"label": "Cost constraint"
}
],
"soft_constraints": [
// Same structure as constraints, with an additional "weight" field
{ "weight": 5.0, "..." : "..." }
],
"objectives": [
{
"name": "maximize_rides",
"direction": "maximize", // "maximize" or "minimize"
"expression": "ride_count",
"variable": "ride_count", // primary variable for simple objectives
"weight": 1.0, // relative weight for multi-objective
"priority": 1, // priority ordering
"label": "Maximize the number of rides"
}
],
"what_if_scenarios": [
{
"name": "Add Roller Coaster",
"description": "What happens if we commit to a roller coaster?",
"additional_constraints": [
// Same structure as constraints; added temporarily via push/pop
]
}
]
}
```
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Theme Park Planning | Facility layout, capital budgeting, resource allocation |
| Space Colony Planning | Infrastructure sizing, capacity planning, disaster recovery modeling |
| Fantasy Sports Draft | Portfolio optimization, team composition, auction bidding strategies |
## Interactive Modes
All implementations support debugging flags:
```bash
# Verbose mode - show solver stats, variable details, and intermediate state
cargo run -- --scenario theme-park --verbose # Rust
./bin/solver --scenario theme-park --verbose # Go
python main.py --scenario theme-park --verbose # Python
# Step mode - pause at each phase with explanations
cargo run -- --scenario theme-park --step # Rust
./bin/solver --scenario theme-park --step # Go
python main.py --scenario theme-park --step # Python
# Combined mode
cargo run -- --scenario theme-park --verbose --step
```
Or use environment variables (Rust and Go only):
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python
cd python && python -m pytest
```
## Production Considerations
1. **Timeout handling**: Set `timeout_ms` in `SolverConfig` to bound solve time on large models
2. **Incremental solving**: Add constraints and re-solve rather than rebuilding from scratch
3. **Soft constraint weights**: Calibrate weights based on domain expertise; higher weights are harder to violate
4. **What-if batching**: Use push/pop for rapid scenario comparison without session recreation
---
# Solver What-If Pattern
URL: https://docs.nxus.systems/nxuskit/examples/patterns/solver-what-if
Demonstrates push/pop scoping, assumption-based solving, and what-if analysis using the nxusKit constraint solver. Each scenario defines a base problem and several what-if variants that temporarily modify the model to explore alternative outcomes.
> Explore alternative outcomes without rebuilding your model — push constraints, solve, compare, and pop back to baseline in one clean pattern.
**Scenarios**: `wedding` · `mars` · `recipe`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · Solver
- **Summary:** What-if scenario analysis with solver streaming
- **Scenario:** Stream solver results for interactive what-if scenario exploration
- **`tech_tags` in manifest:** `Solver, Streaming` — example id **`solver-what-if`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust, python, bash (paths under this directory).
- **Solver entitlement:** Requires a Pro or trial entitlement because it uses the Z3-backed solver. No LLM provider is required.
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **SolverSession Lifecycle** | Create, build model incrementally, solve, and close via the nxuskit SDK |
| **Push/Pop Scoping** | Save and restore model state for reversible experimentation |
| **What-If Analysis** | Add temporary constraints, solve, compare deltas, then restore |
| **Explanation / Unsat Core** | Retrieve constraint labels that cause infeasibility via `Explanation()` |
| **Delta Comparison** | Compare base vs. what-if variable assignments and objective values |
**Provider Compatibility**: Uses the nxusKit Z3-based constraint solver (no LLM provider required)
## Technologies
Solver, Streaming
## Pattern Overview
Real-world planning often involves asking "what if?" -- exploring how changes to assumptions affect the optimal solution. This pattern uses the solver's push/pop mechanism to efficiently evaluate multiple alternative scenarios without rebuilding the model from scratch.
The pipeline for each run:
1. **Load** a problem with base constraints, objective, and what-if scenario definitions
2. **Solve** the base problem to establish a baseline optimal solution
3. **For each what-if scenario**:
- **Push** the current solver state (saves all constraints and objective)
- **Add** temporary constraints that define the alternative scenario
- **Solve** under the modified model
- If UNSAT, **retrieve explanation** (unsat core labels)
- **Compare** the what-if result to the baseline (show variable deltas)
- **Pop** the solver state (restores the base model)
4. **Summarize** all scenarios in a comparison table
## Scenarios
Three themed scenarios are included under `scenarios/`:
- **Wedding Budget Planning** -- Allocate a $25,000 wedding budget across venue, catering, flowers, photography, music, and decor. What-if: splurge on a fancy venue, cut the DJ, or double the budget.
- **Mars Colony Resource Allocation** -- Design a Mars colony by balancing colonists against solar panels, water recyclers, greenhouses, habitats, and power storage under a cargo mass limit. What-if: require 50+ colonists, simulate a dust storm, or get extra cargo capacity.
- **Recipe Scaling** -- Scale a baking recipe by adjusting flour, sugar, eggs, butter, milk, and vanilla while maintaining proper ratios. What-if: limited eggs, go fully vegan (may be UNSAT), or bake for a party.
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/solver-what-if`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
cd bash && make build
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario wedding
cargo run -- --scenario mars --verbose
cargo run -- --scenario recipe --step
```
### Go
```bash
cd go
make build
./bin/solver-what-if --scenario wedding
./bin/solver-what-if --scenario mars --verbose
./bin/solver-what-if --scenario recipe --step
```
### Python
```bash
cd python
python3 main.py --scenario wedding
python3 main.py --scenario mars --verbose
python3 main.py --scenario recipe --step
```
### CLI/Bash
```bash
cd bash
make run
make run ARGS="--scenario mars"
make run ARGS="--scenario recipe --verbose"
```
## Push/Pop Concepts
The solver's push/pop mechanism works like a stack of model snapshots:
```
Base model: [variables + constraints + objective]
|
push() --> saves state
|
add_constraints([temporary constraints])
solve() --> result under modified model
|
pop() --> restores base model (temporary constraints removed)
```
Key properties:
- **Push** creates a new scope level; all subsequent additions are scoped
- **Pop** removes everything added since the last push
- Multiple push/pop levels can be nested
- The solver does not re-initialize -- it reuses learned information for efficiency
## Unsat Core Explanation
When a what-if scenario makes the model infeasible (UNSAT), the solver can report which constraints are responsible:
1. Enable explanation with `ProduceExplanation: true` in the solve config
2. After an UNSAT result, call `Explanation()` to retrieve the unsat core
3. The `unsat_core_labels` array contains the constraint labels that form a minimal conflicting set
This is particularly useful for understanding *why* a scenario is impossible (e.g., the vegan recipe scenario where eggs=0 conflicts with the eggs-per-flour ratio constraint).
## Scenario Data Format
Each scenario is a directory containing a `problem.json` file:
```jsonc
{
"name": "Scenario Name",
"description": "Human-readable description.",
"variables": [
{
"name": "venue_cost",
"var_type": "integer",
"domain": { "min": 5000, "max": 15000 },
"label": "Cost of the venue in dollars"
}
],
"constraints": [
{
"name": "budget_limit",
"constraint_type": "le",
"variables": ["venue_cost", "catering_cost"],
"parameters": { "budget": 25000 },
"expression": "venue_cost + catering_cost <= 25000",
"label": "Budget constraint"
}
],
"objectives": [
{
"name": "maximize_total_quality",
"direction": "maximize",
"expression": "venue_cost + catering_cost",
"variable": "venue_cost",
"weight": 1.0,
"label": "Maximize total quality"
}
],
"what_if_scenarios": [
{
"name": "fancy_venue",
"description": "What if we splurge on a fancy venue?",
"additional_constraints": [
{
"name": "fancy_venue_min",
"constraint_type": "ge",
"variables": ["venue_cost"],
"parameters": { "min_value": 12000 },
"expression": "venue_cost >= 12000",
"label": "Fancy venue minimum"
}
]
}
]
}
```
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Wedding Budget Planning | Event planning, capital budgeting, portfolio allocation |
| Mars Colony Planning | Infrastructure sizing, supply chain planning, disaster preparedness |
| Recipe Scaling | Manufacturing scaling, formulation optimization, process engineering |
## Interactive Modes
All implementations support debugging flags:
```bash
# Verbose mode - show solver stats and constraint details
cargo run -- --scenario wedding --verbose # Rust
./bin/solver-what-if --scenario wedding --verbose # Go
python3 main.py --scenario wedding --verbose # Python
make run ARGS="--scenario wedding --verbose" # CLI/Bash
# Step mode - pause at each phase with explanations
cargo run -- --scenario wedding --step # Rust
./bin/solver-what-if --scenario wedding --step # Go
python3 main.py --scenario wedding --step # Python
make run ARGS="--scenario wedding --step" # CLI/Bash
# Combined mode
cargo run -- --scenario wedding --verbose --step
```
Or use environment variables where supported:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python smoke
cd python && python3 main.py --help
# CLI/Bash
cd bash && make test
```
## Production Considerations
1. **Push/Pop depth**: Keep nesting shallow; deep push/pop stacks add solver overhead
2. **Explanation cost**: Producing unsat cores adds overhead; only enable when needed
3. **Constraint interaction**: What-if constraints are *added* to existing constraints via push, not *replaced*. Design base constraints to be compatible with what-if additions.
4. **Timeout handling**: Set `timeout_ms` in `SolverConfig` to bound solve time on large models
---
# Streaming
URL: https://docs.nxus.systems/nxuskit/examples/patterns/streaming
Stream tokens from a chat completion as they arrive
> Stream LLM responses token by token with a unified async interface that works across Claude, OpenAI, and Ollama without changing your code.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · LLM · Streaming
- **Summary:** Streaming chat completion with real-time output
- **Scenario:** Stream tokens from a chat completion as they arrive
- **`tech_tags` in manifest:** `LLM, Streaming` — example id **`streaming`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Real-time chat interface, live transcription display
## Technologies
LLM, Streaming
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/streaming`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/streaming
```
### Python
```bash
cd python
python main.py
```
---
# Structured Output (JSON Mode) Pattern
URL: https://docs.nxus.systems/nxuskit/examples/patterns/structured-output
Demonstrates extracting typed, validated structured data from LLM responses using JSON mode.
> Stop parsing free-form LLM text — get typed, validated JSON structs back every time, across every provider.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** JSON mode and structured output generation
- **Scenario:** Request and parse structured JSON responses from an LLM
- **`tech_tags` in manifest:** `LLM` — example id **`structured-output`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **JSON Mode Abstraction** | nxusKit handles provider-specific JSON mode implementations |
| **Type-Safe Responses** | Strong typing with serde (Rust) / json (Go) for reliability |
| **Provider-Agnostic Schemas** | Same schema works across OpenAI, Claude, and Ollama |
**Provider Compatibility**: Ollama (format parameter), OpenAI (response_format), Claude (via tool use)
## Pattern Overview
LLMs naturally produce unstructured text, but many applications need structured data. This pattern uses JSON mode to ensure valid JSON output, then parses and validates it into typed structures.
## Key Features
- JSON mode ensures valid JSON response
- Type-safe parsing into structs
- Validation of enumerated fields
- Helper functions for testing
## Real-World Application
Data extraction, form auto-fill, API response generation.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/structured-output`:
cd rust && cargo build
cd go && make build
```
## Log Classification Example
The example classifies log entries into structured categories:
```json
{
"severity": "error",
"category": "auth",
"summary": "Failed login attempt for admin user",
"actionable": true
}
```
### Valid Values
- **severity**: `info`, `warning`, `error`, `critical`
- **category**: `auth`, `network`, `system`, `application`
## Library usage
### Rust
```rust
use structured_output::{classify_log, LogClassification};
let classification = classify_log(&provider, "llama3", log_entry).await?;
println!("Severity: {}", classification.severity);
println!("Actionable: {}", classification.actionable);
```
### Go
```go
classification, err := ClassifyLog(ctx, provider, "llama3", logEntry)
fmt.Println("Severity:", classification.Severity)
fmt.Println("Actionable:", classification.Actionable)
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Prompt Engineering Tips
1. **Be explicit**: Specify the exact JSON format in the system prompt
2. **List valid values**: Enumerate allowed values for each field
3. **Provide examples**: Include example JSON in complex cases
4. **Validate output**: Always validate parsed JSON against your schema
## Production Considerations
1. **Retry on validation failure**: LLMs may occasionally produce invalid values
2. **Fallback handling**: Have a default category for edge cases
3. **Schema evolution**: Version your schemas for backward compatibility
4. **Rate limiting**: JSON mode may use more tokens due to formatting
---
# Timeout Config
URL: https://docs.nxus.systems/nxuskit/examples/patterns/timeout-config
Configure request timeouts and connection pool settings
> Take control of LLM request timing with per-phase timeout configuration that catches network failures fast without killing long-running streams.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Timeout configuration and connection management
- **Scenario:** Configure request timeouts and connection pool settings
- **`tech_tags` in manifest:** `LLM` — example id **`timeout-config`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Latency-sensitive services, SLA-bound AI endpoints
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/timeout-config`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/timeout-config
```
---
# Streaming with Token Budget Pattern
URL: https://docs.nxus.systems/nxuskit/examples/patterns/token-budget
Demonstrates cost control by enforcing token limits during streaming responses.
> Stop paying for tokens you don't need — enforce real-time streaming budgets and cancel LLM requests the moment your limit is reached.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Token budget management and cost estimation
- **Scenario:** Track and limit token usage across requests
- **`tech_tags` in manifest:** `LLM` — example id **`token-budget`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust, bash (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** CLI/Bash defaults to the `loopback` provider for credential-free smoke tests. Set cloud provider API keys or run **Ollama** locally when using live providers in the **Run** steps.
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **Unified Streaming** | Same streaming interface across all providers (Stream in Rust, channels in Go) |
| **Stream Cancellation** | Graceful cancellation supported by all provider implementations |
| **Token Tracking** | Normalized token usage in final chunk regardless of provider |
**Provider Compatibility**: Any provider supporting streaming (Claude, OpenAI, Ollama)
## Pattern Overview
When streaming LLM responses, you may want to stop generation early to control costs or enforce response length limits. This pattern monitors token usage during streaming and cancels the request when a budget is reached.
## Key Features
- Real-time token estimation during streaming
- Graceful stream cancellation when budget exceeded
- Returns partial content and budget status
- Works with any streaming-capable provider
## Real-World Application
Usage metering, per-user quota enforcement.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
| CLI/Bash | `bash/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/token-budget`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
cd bash && make build
```
## Token Estimation
Since exact token counts aren't available during streaming, we use a simple heuristic:
- ~4 characters per token (works well for English text)
- Adjust this ratio for other languages or specialized content
## Library usage
### Rust
```rust
use token_budget::stream_with_budget;
// Stream with a 100 token budget
let result = stream_with_budget(&provider, &request, 100).await?;
println!("Content: {}", result.content);
println!("Tokens used: {}", result.estimated_tokens);
if result.budget_reached {
println!("Budget limit reached - response truncated");
}
```
### Go
```go
// Stream with a 100 token budget
result, err := StreamWithBudget(ctx, provider, req, 100)
fmt.Println("Content:", result.Content)
fmt.Println("Tokens used:", result.EstimatedTokens)
if result.BudgetReached {
fmt.Println("Budget limit reached - response truncated")
}
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
### Python
```bash
cd python
python3 main.py
```
### CLI/Bash
```bash
cd bash
make run
TOKEN_BUDGET_MAX=40 make run ARGS="ollama"
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
make run ARGS="--verbose" # CLI/Bash
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
make run ARGS="--step" # CLI/Bash
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python smoke
cd python && python3 main.py --help
# CLI/Bash
cd bash && make test
```
## Production Considerations
1. **Calibrate token ratio**: Adjust the 4 chars/token estimate for your specific use case
2. **Buffer margin**: Set budget slightly below hard limits to account for estimation error
3. **User feedback**: Indicate when responses are truncated due to budget
4. **Combine with max_tokens**: Use both streaming budget and API max_tokens for defense in depth
---
# Vision
URL: https://docs.nxus.systems/nxuskit/examples/patterns/vision
Send images alongside text prompts for multimodal analysis
> Send images alongside text to any LLM provider using one consistent API that handles encoding, formatting, and provider differences for you.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · LLM · Vision
- **Summary:** Vision and multimodal capabilities with images
- **Scenario:** Send images alongside text prompts for multimodal analysis
- **`tech_tags` in manifest:** `LLM, Vision` — example id **`vision`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust, bash (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys for live Claude/OpenAI calls, or run metadata-only CLI/Bash mode with `VISION_RUN_LIVE=0`. Ollama vision models can be selected when the local provider path is available.
## Real-World Application
Image captioning, visual QA, document understanding
## Technologies
LLM, Vision
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
| CLI/Bash | `bash/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/vision`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
cd bash && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/vision
```
### Python
```bash
cd python
python main.py
```
### CLI/Bash
```bash
cd bash
make run
VISION_RUN_LIVE=0 make run
make run ARGS="openai"
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python smoke
cd python && python3 main.py --help
# CLI/Bash
cd bash && make test
```
---
# Authentication
URL: https://docs.nxus.systems/nxuskit/getting-started/authentication
## Overview
nxusKit supports multiple authentication methods depending on the provider.
This matrix shows which methods are available for each provider and how to
configure them.
## Provider Matrix
| Provider | Auth Required | API Key | OAuth | Env Variable | Dashboard |
|----------|:------------:|:-------:|:-----:|--------------|-----------|
| OpenAI / GPT | Yes | Yes | — | `OPENAI_API_KEY` | [platform.openai.com/api-keys](https://platform.openai.com/api-keys) |
| Anthropic / Claude | Yes | Yes | — | `ANTHROPIC_API_KEY` | [console.anthropic.com/settings/keys](https://console.anthropic.com/settings/keys) |
| xAI Grok | Yes | Yes | — | `XAI_API_KEY` | [console.x.ai](https://console.x.ai/) |
| Groq | Yes | Yes | — | `GROQ_API_KEY` | [console.groq.com/keys](https://console.groq.com/keys) |
| Mistral AI | Yes | Yes | — | `MISTRAL_API_KEY` | [console.mistral.ai/api-keys](https://console.mistral.ai/api-keys) |
| Fireworks AI | Yes | Yes | — | `FIREWORKS_API_KEY` | [fireworks.ai/account/api-keys](https://fireworks.ai/account/api-keys) |
| Together AI | Yes | Yes | — | `TOGETHER_API_KEY` | [api.together.ai/settings/api-keys](https://api.together.ai/settings/api-keys) |
| OpenRouter | Yes | Yes | — | `OPENROUTER_API_KEY` | [openrouter.ai/settings/keys](https://openrouter.ai/settings/keys) |
| Perplexity | Yes | Yes | — | `PERPLEXITY_API_KEY` | [perplexity.ai/settings/api](https://www.perplexity.ai/settings/api) |
| Ollama | No | — | — | `OLLAMA_HOST` | — |
| LM Studio | No | — | — | `LM_STUDIO_HOST` | — |
**Legend**: Yes = supported, — = not applicable/not yet available
## Authentication Methods
### API Key
The standard authentication method for cloud providers. Obtain a key from
the provider's dashboard, then configure via any of these methods:
**Environment variable** (recommended for development and CI/CD):
```bash
export OPENAI_API_KEY="sk-..."
```
**Credential store** (recommended for persistent local development):
```bash
nxuskit-cli provider set openai sk-...
```
This stores the key in the OS credential store (macOS Keychain, Windows
Credential Manager, or Linux secret-service). Falls back to a file-based
store with 0600 permissions if no system store is available.
**Explicit parameter** (for programmatic use):
```python
provider = Provider.create("openai", api_key="sk-...")
```
### OAuth (Infrastructure Ready)
OAuth authentication infrastructure is implemented in v0.9.1 but no current
providers require it. When a provider enables OAuth support, the flow will
be:
```bash
# Start OAuth login
nxuskit-cli provider login
# Check auth status
nxuskit-cli provider status
```
The OAuth flow uses:
- PKCE (SHA-256 code challenge) for security
- Localhost callback on an ephemeral port
- State/CSRF validation
- Automatic browser launch
### No Authentication
Local providers (Ollama, LM Studio) run on the local machine and do not
require authentication. The host env variable is optional and defaults to
`localhost` on the provider's default port.
## Credential Precedence
When multiple credential sources exist, the SDK uses this precedence order:
| Priority | Source | Example |
|----------|--------|---------|
| 1 (highest) | Explicit API parameter | `Provider.create("openai", api_key="sk-...")` |
| 2 | Environment variable | `OPENAI_API_KEY=sk-...` |
| 3 (lowest) | OS credential store | Via `nxuskit-cli provider set` |
## Checking Auth Status
View authentication status for all providers:
```bash
nxuskit-cli provider status
```
For a specific provider:
```bash
nxuskit-cli provider status openai
```
JSON output (for scripts):
```bash
nxuskit-cli provider status --json
```
Example output:
```
Provider Status Source Auth Methods
─────────────────────────────────────────────────────────────
openai Authenticated env api_key
claude Authenticated store api_key
xai Not authenticated — api_key
groq Not authenticated — api_key
ollama Not required — —
lm-studio Not required — —
```
## Managing Credentials
```bash
# Store a credential
nxuskit-cli provider set
# Remove a stored credential
nxuskit-cli provider remove
# View status
nxuskit-cli provider status [provider]
```
## Per-Language Configuration
### Rust
```rust
use nxuskit::{auth_status, auth_set_credential, auth_resolve};
// Check status
let status = auth_status("openai")?;
// Store credential
auth_set_credential("openai", "sk-...")?;
// Resolve credential (follows precedence chain)
let resolution = auth_resolve("openai", None)?;
```
### Go
```go
import "github.com/nxus-SYSTEMS/nxuskit-go"
// Check status
status, err := nxuskit.AuthStatus("openai")
// Store credential
err = nxuskit.AuthSetCredential("openai", "sk-...")
// Resolve credential
resolution, err := nxuskit.AuthResolve("openai", "")
```
### Python
```python
from nxuskit import auth_status, auth_set_credential, auth_resolve
# Check status
status = auth_status("openai")
# Store credential
auth_set_credential("openai", "sk-...")
# Resolve credential
resolution = auth_resolve("openai")
```
---
# First Call
URL: https://docs.nxus.systems/nxuskit/getting-started/first-call
This guide assumes you have installed the SDK and configured at least one
provider credential. If you have not done that yet, start with
[Installation](/nxuskit/getting-started/installation/) and
[Authentication](/nxuskit/getting-started/authentication/).
## Fastest Path: CLI
Set a provider API key, then send a single chat request:
```bash
export OPENAI_API_KEY="sk-..."
nxuskit-cli chat \
--provider openai \
--model gpt-4o \
"Say hello from nxusKit in one sentence."
```
For structured shell workflows, use the Level 1 `call` command:
```bash
echo '{"provider":"openai","model":"gpt-4o","prompt":"Say hello from nxusKit."}' \
| nxuskit-cli call --input - --format json
```
## Rust
Use the Rust wrapper bundled with the SDK as a path dependency:
```toml
# Cargo.toml
[dependencies]
nxuskit = { path = "/absolute/path/to/nxuskit-sdk-{version}-{platform}/rust" }
```
```rust
use nxuskit::{ChatRequest, Message, NxuskitProvider, ProviderConfig};
fn main() -> Result<(), nxuskit::NxuskitError> {
let provider = NxuskitProvider::new(ProviderConfig {
provider_type: "openai".into(),
..Default::default()
})?;
let request = ChatRequest::new("gpt-4o")
.with_message(Message::user("Say hello from Rust."))
.with_max_tokens(100);
let response = provider.chat(request)?;
println!("{}", response.content);
Ok(())
}
```
## Go
Add the Go wrapper and alias the package as `nxuskit` in your import block:
```bash
go get github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go
```
```go
package main
import (
"context"
"fmt"
"os"
nxuskit "github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go"
)
func main() {
provider, err := nxuskit.NewOpenAIProvider(
nxuskit.WithAPIKey(os.Getenv("OPENAI_API_KEY")),
)
if err != nil {
panic(err)
}
req := nxuskit.ChatRequest{
Model: "gpt-4o",
Messages: []nxuskit.Message{
{Role: nxuskit.RoleUser, Content: "Say hello from Go."},
},
}
resp, err := provider.Chat(context.Background(), req)
if err != nil {
panic(err)
}
fmt.Println(resp.Content)
}
```
## Python
Install the Python wrapper, then create a provider and call it:
```bash
pip install nxuskit-py
```
```python
from nxuskit import Provider
provider = Provider.create("openai")
response = provider.chat(
model="gpt-4o",
messages=[{"role": "user", "content": "Say hello from Python."}],
max_tokens=100,
)
print(response.content)
```
## C
The SDK bundle includes `include/nxuskit.h` and platform libraries under
`lib/`. Compile against those files and set the provider API key in the
environment:
```bash
export OPENAI_API_KEY="sk-..."
cc -I "$NXUSKIT_SDK_DIR/include" \
-o basic_chat basic_chat.c \
-L "$NXUSKIT_SDK_DIR/lib" \
-lnxuskit \
-Wl,-rpath,"$NXUSKIT_SDK_DIR/lib"
```
Use the [C ABI Reference](/nxuskit/reference/api-reference/) for function,
ownership, and error-handling details.
## Local Providers
Local providers do not require API keys:
```bash
# Ollama default
export OLLAMA_HOST="http://localhost:11434"
# LM Studio default
export LMSTUDIO_HOST="http://localhost:1234/v1"
```
Use [Local LLM Providers](/nxuskit/reference/providers/local-llms/) for model
setup and provider-specific options.
## Next Steps
| Goal | Read |
|------|------|
| Configure credentials | [Authentication](/nxuskit/getting-started/authentication/) |
| Browse runnable projects | [Examples](/nxuskit/examples/) |
| Stream responses | [Streaming](/nxuskit/guides/streaming/) |
| Choose a provider | [Provider Model](/nxuskit/concepts/provider-model/) |
| Use CLI JSON contracts | [CLI Input Format Reference](/nxuskit/reference/cli-reference/) |
| Integrate through native boundaries | [C ABI Reference](/nxuskit/reference/api-reference/) |
---
# Installation
URL: https://docs.nxus.systems/nxuskit/getting-started/installation
This guide walks you through downloading, installing, and using the nxuskit SDK
to call LLM providers from Rust, Go, Python, or the C ABI.
## Prerequisites
- [GitHub CLI](https://cli.github.com/) (`gh`) installed
- Optional: authenticate with `gh auth login` for CI reliability, higher API
limits, or entitlement-gated/private assets
## 1. Download and Install the SDK
The examples below download Community Edition from the public
`nxus-SYSTEMS/nxusKit` release. Current release asset names use `oss` for the
Community Edition archive segment. Pro users can replace `oss` with `pro` in the
asset patterns and extracted directory names after activating or receiving a Pro
entitlement.
For Pro CLI workflows, use the v1.0.1 or newer Pro SDK bundle. v1.0.1 makes no
API or C ABI signature changes from v1.0.0; it fixes Pro CLI package
composition so Pro archives include the real Solver/ZEN engine command modules
instead of CE-safe stubs. Community Edition archives do not include Pro engine
execution.
### macOS (Apple Silicon)
```bash
# Download, extract, and remove macOS quarantine in one go
gh release download --repo nxus-SYSTEMS/nxusKit \
--pattern "nxuskit-sdk-*-oss-macos-arm64.tar.gz" \
--pattern "nxuskit-sdk-*-oss-macos-arm64.tar.gz.sha256"
shasum -a 256 -c nxuskit-sdk-*-oss-macos-arm64.tar.gz.sha256
tar xzf nxuskit-sdk-*-oss-macos-arm64.tar.gz
xattr -dr com.apple.quarantine nxuskit-sdk-*/
```
The `xattr` step removes the Gatekeeper quarantine flag that macOS applies to
downloaded files. Without it you'll get "can't be opened because Apple cannot
check it for malicious software" when loading the dylib.
### Linux (x86_64)
```bash
gh release download --repo nxus-SYSTEMS/nxusKit \
--pattern "nxuskit-sdk-*-oss-linux-x86_64.tar.gz" \
--pattern "nxuskit-sdk-*-oss-linux-x86_64.tar.gz.sha256"
sha256sum -c nxuskit-sdk-*-oss-linux-x86_64.tar.gz.sha256
tar xzf nxuskit-sdk-*-oss-linux-x86_64.tar.gz
```
### Windows (x86_64)
```powershell
gh release download --repo nxus-SYSTEMS/nxusKit `
--pattern "nxuskit-sdk-*-oss-windows-x86_64.zip" `
--pattern "nxuskit-sdk-*-oss-windows-x86_64.zip.sha256"
# Extract
Expand-Archive nxuskit-sdk-*-oss-windows-x86_64.zip -DestinationPath .
```
### Set SDK Path
After extracting, set the SDK path. **Use an absolute path** — relative paths
can fail because `cargo` and other tools may change the working directory during
builds.
```bash
# Get the absolute path to the extracted SDK directory
export NXUSKIT_SDK_DIR="$(cd nxuskit-sdk-*/ && pwd)"
echo "NXUSKIT_SDK_DIR=${NXUSKIT_SDK_DIR}"
```
To persist across sessions, add to your shell profile (`~/.bashrc`, `~/.zshrc`,
etc.):
```bash
export NXUSKIT_SDK_DIR="/absolute/path/to/nxuskit-sdk-1.0.1-oss-macos-arm64"
```
For CI systems, see [Download via PAT](#download-via-pat) below.
### CLI shell completions (optional)
The bundle includes `nxuskit-cli`. Generate shell completions with:
```bash
nxuskit-cli completions bash > /usr/local/etc/bash_completion.d/nxuskit-cli
nxuskit-cli completions zsh > ~/.zfunc/_nxuskit-cli # add ~/.zfunc to $fpath
nxuskit-cli completions fish > ~/.config/fish/completions/nxuskit-cli.fish
```
Supported shells for `completions` in v1.0.x: **bash**, **zsh**, **fish**.
PowerShell completion is **not generated** in v1.0.x (the `completions` command
accepts only those three shell names). JSON schemas referenced by the CLI ship
under the bundle's `include/` (the C header) and `conformance/` (packet/pipeline
schemas) directories; see [SDK Bundle Contents](#2-sdk-bundle-contents) above.
## 2. SDK Bundle Contents
```
nxuskit-sdk-{version}-{edition}-{platform}/
├── include/
│ └── nxuskit.h # C header — all API declarations
├── lib/
│ ├── libnxuskit.so # Shared library (Linux)
│ │ libnxuskit.dylib # Shared library (macOS)
│ │ nxuskit.dll # Shared library (Windows)
│ ├── libnxuskit.a # Static library (Linux/macOS)
│ │ nxuskit.lib # Static library (Windows)
│ └── nxuskit.dll.lib # Import library (Windows only)
├── rust/ # nxuskit Rust SDK wrapper (use as path dependency)
├── docs/ # This documentation
└── examples/ # Working examples in C, Rust, Go, Python
```
## 3. First Example — C
Set your provider API key, then compile and run:
```bash
export OPENAI_API_KEY="sk-..." # or ANTHROPIC_API_KEY, etc.
cd nxuskit-sdk-*/examples/c
make basic_chat
./bin/basic_chat
```
See [nxusKit examples](/nxuskit/examples/) for the source.
## 4. First Example — Go
```bash
export OPENAI_API_KEY="sk-..."
cd nxuskit-sdk-*/examples/go
go run basic_chat.go
```
See [nxusKit examples](/nxuskit/examples/) for the source.
## 5. First Example — Rust
The SDK bundles `nxuskit`, a safe Rust wrapper. Add it as a path dependency
in your `Cargo.toml` using the **absolute path** to the SDK's `rust/` directory:
```toml
# Cargo.toml
[dependencies]
nxuskit = { path = "/Users/you/nxuskit-sdk-1.0.1-oss-macos-arm64/rust" }
```
Then set your environment and run:
```bash
# NXUSKIT_SDK_DIR tells the wrapper where to find libnxuskit at runtime.
# Must be an absolute path (relative paths are unreliable across tools).
export NXUSKIT_SDK_DIR="/Users/you/nxuskit-sdk-1.0.1-oss-macos-arm64"
export OPENAI_API_KEY="sk-..."
cargo run
```
```rust
use nxuskit::{ChatRequest, Message, NxuskitProvider, ProviderConfig};
fn main() -> Result<(), nxuskit::NxuskitError> {
let provider = NxuskitProvider::new(ProviderConfig {
provider_type: "openai".into(),
..Default::default()
})?;
let request = ChatRequest::new("gpt-4o")
.with_message(Message::user("Hello from Rust!"))
.with_max_tokens(100);
let response = provider.chat(request)?;
println!("{}", response.content);
Ok(())
}
```
**Path troubleshooting:** If you see `LibraryNotFound`, verify:
1. `NXUSKIT_SDK_DIR` is set and is an absolute path (check with `echo $NXUSKIT_SDK_DIR`)
2. The `lib/` subdirectory exists: `ls $NXUSKIT_SDK_DIR/lib/`
3. On macOS: quarantine was removed (see Step 1 above)
See [nxusKit examples](/nxuskit/examples/) for a runnable project, and
[Rust SDK API documentation](/nxuskit/reference/api/) for the full nxuskit API documentation.
## 6. First Example — Python
```bash
pip install nxuskit-py
export OPENAI_API_KEY="sk-..."
python examples/python/basic_chat.py
```
See [nxusKit examples](/nxuskit/examples/) for the source.
## Core Concepts
### JSON-in / JSON-out
All data crosses the FFI boundary as JSON strings. You send a JSON config to
create a provider, send a JSON request for chat, and receive a JSON response.
### Provider Lifecycle
```
create_provider(config_json) → provider handle
↓
chat(provider, request_json) → response handle → response_json(response) → JSON
↓
free_response(response)
free_provider(provider)
```
### Streaming
```
chat_stream(provider, request_json, on_chunk, on_done, user_data) → stream handle
↓ (callbacks fire from background thread)
on_chunk(chunk_json, user_data) ← called per chunk
on_done(final_json, user_data) ← called once at end
↓
free_stream(stream)
```
### Thread Safety
- All `nxuskit_*` functions are thread-safe
- Provider handles can be shared across threads
- Error messages are thread-local (`nxuskit_last_error()`)
### Supported Providers
| Provider | Config `provider_type` | Required Env Var |
|----------|----------------------|------------------|
| OpenAI | `openai` | `OPENAI_API_KEY` |
| Anthropic Claude | `claude` | `ANTHROPIC_API_KEY` |
| Ollama | `ollama` | `OLLAMA_HOST` (optional) |
| LM Studio | `lmstudio` | — |
| xAI Grok | `xai` | `XAI_API_KEY` |
| Groq | `groq` | `GROQ_API_KEY` |
| Fireworks | `fireworks` | `FIREWORKS_API_KEY` |
| Together | `together` | `TOGETHER_API_KEY` |
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` |
| Perplexity | `perplexity` | `PERPLEXITY_API_KEY` |
| Mistral | `mistral` | `MISTRAL_API_KEY` |
| CLIPS | `clips` | — |
| MCP | `mcp` | — |
| Mock (testing) | `mock` | — |
| Loopback (testing) | `loopback` | — |
`xai` is xAI Grok and uses `XAI_API_KEY`. `groq` is Groq, Inc.'s provider and
uses `GROQ_API_KEY`. There is no `grok` provider alias.
### CLIPS Quick Start
CLIPS runs in-process (no API key needed). Create a provider with
`provider_type: "clips"` and `model` pointing to your rules directory. Send
facts as JSON in the user message:
```c
const char *input = "{\"facts\": [{\"template\": \"sensor\", \"values\": {\"name\": \"temp\", \"value\": 150}}]}";
// ... create provider, build request with input as user message, call nxuskit_chat()
```
The user message must conform to the `ClipsInput` schema — see the
[Rule Authoring Guide](/nxuskit/guides/clips-rule-authoring/#clipsinput-json-reference) for the full
field reference. CLIPS also provides a session API for direct engine access; see
the [API Reference](/nxuskit/reference/api-reference/#clips-session-api).
## Linking Reference
### GCC / Clang (dynamic)
```bash
cc -I sdk/include -o myapp myapp.c -L sdk/lib -lnxuskit -Wl,-rpath,sdk/lib
```
### GCC / Clang (static)
```bash
cc -I sdk/include -o myapp myapp.c sdk/lib/libnxuskit.a -lpthread -ldl -lm
```
### MSVC (dynamic — recommended)
```
cl /I sdk\include myapp.c /link sdk\lib\nxuskit.dll.lib
```
### MSVC (static)
```
cl /I sdk\include myapp.c /link sdk\lib\nxuskit.lib ucrt.lib userenv.lib ntdll.lib ws2_32.lib bcrypt.lib advapi32.lib
```
### CGo
```go
// #cgo CFLAGS: -I${SRCDIR}/sdk/include
// #cgo linux LDFLAGS: -L${SRCDIR}/sdk/lib -lnxuskit -Wl,-rpath,${SRCDIR}/sdk/lib
// #cgo darwin LDFLAGS: -L${SRCDIR}/sdk/lib -lnxuskit -Wl,-rpath,${SRCDIR}/sdk/lib
// #cgo windows LDFLAGS: -L${SRCDIR}/sdk/lib -lnxuskit
// #include "nxuskit.h"
import "C"
```
### Python (cffi)
```python
from cffi import FFI
ffi = FFI()
ffi.cdef(open("sdk/include/nxuskit.h").read())
lib = ffi.dlopen("sdk/lib/libnxuskit.so") # or .dylib / .dll
```
## Download via PAT
For CI systems that can't use `gh`, or that need authenticated GitHub API
access:
1. Create a fine-grained PAT at https://github.com/settings/personal-access-tokens
- **Repository access**: Select `nxus-SYSTEMS/nxusKit`
- **Permissions**: Contents → Read-only
2. Use the token:
```bash
export GH_TOKEN="github_pat_..."
# List available SDK releases
curl -H "Authorization: Bearer $GH_TOKEN" \
"https://api.github.com/repos/nxus-SYSTEMS/nxusKit/releases?per_page=5" \
| jq '.[].tag_name'
# Download a specific asset
curl -L -H "Authorization: Bearer $GH_TOKEN" \
-H "Accept: application/octet-stream" \
"https://api.github.com/repos/nxus-SYSTEMS/nxusKit/releases/assets/{ASSET_ID}" \
-o nxuskit-sdk.tar.gz
```
## Next Steps
- [API Reference](/nxuskit/reference/api-reference/) — full C ABI documentation
- [Provider Reference](/nxuskit/reference/providers/cloud-llms/) — provider-specific configuration
- [Rule Authoring Guide](/nxuskit/guides/clips-rule-authoring/) — writing, testing, and deploying custom CLIPS rules
- [nxusKit examples](/nxuskit/examples/) — working code for SDK languages and C ABI workflows
---
# CLIPS Rule Authoring Guide
URL: https://docs.nxus.systems/nxuskit/guides/clips-rule-authoring
This guide explains how to write, test, and deploy custom CLIPS rules with the nxusKit SDK.
## CLIPS Rule Syntax
nxusKit uses CLIPS 6.4, a forward-chaining inference engine. Rules follow the pattern:
```clips
(defrule rule-name
"Documentation string"
;; LHS: conditions (pattern matching)
(template-name (slot-name ?variable))
(test (< ?variable 100))
=>
;; RHS: actions (assertions, side effects)
(assert (alert
(alert-type "threshold_exceeded")
(severity "warning")
(message (str-cat "Value " ?variable " is out of range"))
(recommendation "Check your input data")
(entity-id ?id)
(rule-name "rule-name")
(module-name "data-qc"))))
```
## Defining Templates
Templates define the fact schemas your rules operate on. Define them in shared template files loaded before any module rules:
```clips
;;; shared/000-core.clp — Core templates
(deftemplate input-data
"A single data record to evaluate"
(slot record-id (type INTEGER))
(slot value (type FLOAT))
(slot category (type STRING))
(slot confidence (type FLOAT) (range 0.0 1.0)))
(deftemplate threshold-config
"Configurable thresholds for QC checks"
(slot value-min (type FLOAT))
(slot value-max (type FLOAT))
(slot confidence-min (type FLOAT) (default 0.5)))
(deftemplate alert
"Output: a raised alert from rule inference"
(slot alert-type (type STRING))
(slot severity (type STRING)) ;; "critical", "high", "warning", "info"
(slot message (type STRING))
(slot recommendation (type STRING))
(slot entity-id (type INTEGER))
(slot rule-name (type STRING))
(slot module-name (type STRING)))
```
## Modules
CLIPS modules provide namespace isolation for rules. Each module groups related rules:
```clips
;;; In data-qc/bounds-check.clp
(defmodule data-qc (export ?ALL))
(defrule bounds-check
"Flag records outside configured bounds"
(threshold-config (value-min ?vmin) (value-max ?vmax))
(input-data (record-id ?rid) (value ?v&:(or (< ?v ?vmin) (> ?v ?vmax))))
=>
(assert (alert
(alert-type "out_of_bounds")
(severity "high")
(message (str-cat "Record " ?rid " value " ?v " outside [" ?vmin "-" ?vmax "]"))
(recommendation "Verify input data or adjust thresholds")
(entity-id ?rid)
(rule-name "bounds-check")
(module-name "data-qc"))))
```
## Directory Structure
Organize rules with shared templates loaded first, then per-module rule files:
```
rules/
shared/ # Shared templates (loaded first, alphabetically)
000-core.clp # input-data, threshold-config, alert
010-domain.clp # Additional domain-specific templates
data-qc/ # Data quality checks
bounds-check.clp
confidence-check.clp
classification/ # Classification rules
category-classifier.clp
custom/ # User-defined rules
my-custom-check.clp
```
## CLIPS Integration Paths
nxusKit provides two ways to use CLIPS:
- **Provider chat** — CLIPS as a standard chat provider. Send `ClipsInput` JSON
as the user message; receive `ClipsOutput` JSON in the response content.
Best for request/response workflows and cross-language portability.
- **Session API** — Direct engine access via `ClipsSession` (Rust, Go, Python)
or the C ABI (`nxuskit_clips_session_*`). Best for interactive, multi-step
rule authoring, debugging, and fine-grained fact manipulation.
This guide focuses on the **provider chat** path. For the session API, see the
[API Reference](/nxuskit/reference/api-reference/#clips-session-api).
## ClipsInput JSON Reference
The user message JSON must conform to the `ClipsInput` schema. Unknown fields
are rejected (the engine uses strict deserialization).
```json
{
"facts": [
{"template": "sensor", "values": {"name": "temp-1", "value": 150}}
],
"templates": [
{"name": "alert", "slots": [{"name": "type", "type": "STRING"}, {"name": "severity", "type": "STRING"}]}
],
"rules": [
{"name": "high-temp", "source": "(defrule high-temp (sensor (value ?v&:(> ?v 100))) => (assert (alert (type \"over-threshold\") (severity \"high\"))))"}
],
"config": {
"max_rules": 1000,
"include_trace": true,
"derived_only_new": true
},
"focus": ["data-qc"],
"globals": {"*threshold*": 100}
}
```
All fields are optional. The minimal valid input is `{}` (empty object).
| Field | Type | Description |
|-------|------|-------------|
| `facts` | array of `{template, values}` | Facts to assert before running inference |
| `templates` | array of `{name, slots}` | Templates to create (if not in rule base) |
| `rules` | array of `{name, source}` or `{name, conditions, actions}` | Rules to create programmatically |
| `config` | object | Request-level overrides (see below) |
| `focus` | array of strings | Module focus stack (controls which rules fire) |
| `globals` | object | Global variable values to set |
| `command` | string | Special command: `"reset"`, `"clear"`, `"retract"` |
| `modules` | array of `{name, doc, imports}` | Modules to create |
| `policy_id` | string | Cache key for session reuse |
**Config fields:**
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `max_rules` | integer | -1 (unlimited) | Maximum rules to fire |
| `include_trace` | boolean | false | Include rule firing trace in output |
| `derived_only_new` | boolean | false | Only return newly derived facts |
| `output_templates` | array of strings | all | Only return facts matching these templates |
## Rule Loading
nxusKit's CLIPS provider loads rules through the `ClipsInput` configuration. Rules can be loaded from:
1. **Text strings** — CLIPS source passed directly via `rules_text`
2. **File paths** — `.clp` files loaded at runtime via `rules` array
3. **Binary images** — Pre-compiled `.bin` files via `binary_rules`
### Loading Order
1. Shared templates are loaded first (alphabetically by filename)
2. Module rules are loaded next, in the order specified by the `focus` configuration
3. User override rules are loaded last (taking precedence)
### Rust Example
```rust
use nxuskit::{AsyncProvider, ChatRequest, Message, NxuskitProvider, ProviderConfig};
let config = ProviderConfig {
provider_type: "clips".into(),
model: Some("/path/to/rules".into()),
..Default::default()
};
let provider = NxuskitProvider::new(config)?;
let request = ChatRequest::new("clips")
.with_message(Message::user(r#"{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 150.0}}]}"#))
.with_provider_options(serde_json::json!({
"focus": ["data-qc"],
"derived_only_new": true
}));
let response = provider.chat(request).await?;
println!("Alerts: {}", response.content);
```
### Go Example
```go
import "github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go"
config := nxuskit-go.ProviderConfig{
ProviderType: "clips",
Model: strPtr("/path/to/rules"),
}
provider, _ := nxuskit-go.NewProvider(config)
request := nxuskit-go.NewChatRequest("clips").
AddMessage(nxuskit-go.UserMessage(`{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 150.0}}]}`))
request.ProviderOptions = map[string]interface{}{
"focus": []string{"data-qc"},
"derived_only_new": true,
}
response, _ := provider.Chat(ctx, request)
fmt.Println("Alerts:", response.Content)
```
### Python Example
```python
from nxuskit-py import create_provider, Message
provider = create_provider("clips", model="/path/to/rules")
response = provider.chat(
model="clips",
messages=[Message.user('{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 150.0}}]}')],
provider_options={
"focus": ["data-qc"],
"derived_only_new": True,
},
)
print("Alerts:", response.content)
```
## Writing Custom Rules
### 1. Create a Rule File
Place your `.clp` file in the appropriate module directory:
```
/path/to/my-rules/data-qc/my-custom-check.clp
```
### 2. Reference Shared Templates
Do NOT redefine templates. Use templates from the shared `shared/*.clp` files:
```clips
;;; my-custom-check.clp
;;; Custom confidence check for strict environments
(defrule strict-confidence-check
"Flag records with confidence below 0.8"
(input-data (record-id ?rid) (confidence ?c&:(< ?c 0.8)))
=>
(assert (alert
(alert-type "low_confidence")
(severity "warning")
(message (str-cat "Record " ?rid " confidence " ?c " below threshold 0.8"))
(recommendation "Review data source quality")
(entity-id ?rid)
(rule-name "strict-confidence-check")
(module-name "data-qc"))))
```
### 3. Use Configurable Thresholds
Reference the `threshold-config` fact instead of hard-coding values:
```clips
(defrule configurable-bounds-check
"Flag records outside configured bounds"
(threshold-config (value-min ?vmin) (value-max ?vmax))
(input-data (record-id ?rid) (value ?v&:(or (< ?v ?vmin) (> ?v ?vmax))))
=>
(assert (alert
(alert-type "value_out_of_bounds")
(severity "high")
(message (str-cat "Record " ?rid " value " ?v " outside [" ?vmin "-" ?vmax "]"))
(recommendation "Check data or adjust threshold configuration")
(entity-id ?rid)
(rule-name "configurable-bounds-check")
(module-name "data-qc"))))
```
### 4. Naming Conventions
- **File names**: `NNN-descriptive-name.clp` (NNN = numeric prefix for load order)
- **Rule names**: `kebab-case`, descriptive of what is being checked
- **Alert types**: `snake_case`, machine-readable identifiers
- **Module names**: `kebab-case`, matching the directory name
## Testing Custom Rules
### Rust
```rust
use nxuskit::{AsyncProvider, ChatRequest, Message, MockProvider};
// Unit test with MockProvider (no SDK binary required)
#[tokio::test]
async fn test_with_mock() {
let provider = MockProvider::new(r#"{"alerts": [{"type": "low_confidence"}]}"#);
let request = ChatRequest::new("clips")
.with_message(Message::user("test input"));
let response = provider.chat(request).await.unwrap();
assert!(response.content.contains("low_confidence"));
}
// Integration test with real CLIPS engine (requires SDK binary)
#[tokio::test]
#[ignore = "requires libnxuskit runtime"]
async fn test_with_clips_engine() {
use nxuskit::{NxuskitProvider, ProviderConfig};
let config = ProviderConfig {
provider_type: "clips".into(),
model: Some("tests/rules".into()),
..Default::default()
};
let provider = NxuskitProvider::new(config).unwrap();
let request = ChatRequest::new("clips")
.with_message(Message::user(r#"{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 999.0}}]}"#));
let response = provider.chat(request).await.unwrap();
assert!(response.content.contains("out_of_bounds"));
}
```
### Go
```go
func TestRulesWithMock(t *testing.T) {
provider := nxuskit-go.NewMockProvider(
nxuskit-go.WithResponse(`{"alerts": [{"type": "low_confidence"}]}`),
)
req := nxuskit-go.NewChatRequest("clips").
AddMessage(nxuskit-go.UserMessage("test input"))
resp, err := provider.Chat(context.Background(), req)
require.NoError(t, err)
assert.Contains(t, resp.Content, "low_confidence")
}
```
### Python
```python
import pytest
from nxuskit-py import create_provider, Message
def test_rules_with_mock():
provider = create_provider("mock", responses=["low_confidence alert fired"])
response = provider.chat(
model="clips",
messages=[Message.user("test input")],
)
assert "low_confidence" in response.content
```
## Debugging Rules
### Enable Tracing
Set the `RUST_LOG` environment variable when using the Rust SDK:
```bash
RUST_LOG=nxuskit=debug cargo test -- --nocapture
```
This shows:
- Which rule files are loaded
- Module loading order and file counts
- Warnings for syntax errors
### Inspect CLIPS Facts
Access the CLIPS session API directly (Rust SDK):
```rust
use nxuskit::ClipsSession;
let session = ClipsSession::create()?;
session.load_string("(deftemplate input-data (slot record-id (type INTEGER)) (slot value (type FLOAT)))")?;
session.load_string("(deftemplate alert (slot alert-type (type STRING)) (slot severity (type STRING)))")?;
session.load_string(r#"(defrule check (input-data (record-id ?rid) (value ?v&:(> ?v 100.0))) =>
(assert (alert (alert-type "over-threshold") (severity "high"))))"#)?;
session.reset()?;
session.assert_string(r#"(input-data (record-id 1) (value 150.0))"#)?;
session.run(-1)?;
// List facts by template
let facts_json = session.facts_by_template("alert")?;
println!("Alert facts: {}", facts_json);
// Drop destroys the session automatically
```
### Step Limit Debugging
If inference hits the step limit, check for rule cycles. Common causes:
- Rules that assert facts matching their own LHS (infinite loop)
- Missing `not` patterns allowing rules to fire repeatedly
- Very large fact sets with cross-product patterns
Increase the step limit if needed:
```rust
session.run(500000)?; // Pass -1 to run until agenda exhausted
```
## Best Practices
1. **Keep rules simple** — One check per rule. Complex logic should be split across multiple rules.
2. **Use configurable thresholds** — Reference threshold facts instead of hard-coding values.
3. **Document every rule** — Use the CLIPS documentation string for a brief description.
4. **Test in isolation** — Load only shared templates and the single rule file under test.
5. **Use meaningful names** — Rule names should describe what is checked, not how.
6. **Set appropriate salience** — Use `(declare (salience N))` to control firing order when needed.
---
# CLIPS Excluded Capabilities & Workarounds
URL: https://docs.nxus.systems/nxuskit/guides/clips-workarounds
Four CLIPS capabilities are intentionally excluded from the Session API.
This document explains why and provides working alternatives.
## 1. User-Defined Functions (UDFs)
**What it is:** CLIPS allows registering C functions callable from rule RHS actions
(`(my-custom-fn ?arg)`).
**Why excluded:** UDFs require raw C function pointers — exposing this through the
session-based FFI would bypass safety guarantees and create ABI fragility.
**Workaround:** Use `nxuskit_clips_eval()` to call built-in CLIPS functions, or
encode custom logic as rules:
```c
// Instead of a UDF that computes weighted score:
// (my-weighted-score ?base ?multiplier)
// Use a rule that computes and asserts the result:
nxuskit_clips_session_load_string(s,
"(defrule compute-weighted-score"
" (input (base ?b) (multiplier ?m))"
" =>"
" (assert (result (score (* ?b ?m)))))");
```
For complex custom functions, pre-compute values in your host language and assert
them as facts:
```c
// Compute in C, assert as fact
double score = my_complex_calculation(base, mult);
char buf[256];
snprintf(buf, sizeof(buf), "(result (score %f))", score);
nxuskit_clips_fact_assert_string(s, buf);
```
## 2. I/O Routers
**What it is:** CLIPS uses I/O routers to redirect `printout`, `read`, and other
I/O operations to custom handlers.
**Why excluded:** Router registration requires persistent C callbacks with
environment-specific state — incompatible with the session handle model.
**Workaround:** Use dribble logging to capture output:
```c
// Capture all CLIPS output to a file
nxuskit_clips_dribble_on(s, "/tmp/clips-output.log");
nxuskit_clips_session_run(s, -1);
nxuskit_clips_dribble_off(s);
// Read /tmp/clips-output.log for captured output
```
For structured output, use facts instead of `printout`:
```c
// Instead of: (printout t "Result: " ?value crlf)
// Use: (assert (output (message (str-cat "Result: " ?value))))
// Then query output facts:
char *outputs = nxuskit_clips_facts_by_template(s, "output");
// Parse JSON array of output facts
nxuskit_free_string(outputs);
```
## 3. Periodic Functions
**What it is:** CLIPS supports registering functions that execute between rule
firings (e.g., for progress callbacks or heartbeat checks).
**Why excluded:** Requires raw function pointers called from within the CLIPS
engine loop — cannot be safely exposed through FFI session handles.
**Workaround:** Use batch `run()` with a step limit and poll between batches:
```c
// Instead of a periodic callback, run in controlled batches
int64_t total_fired = 0;
while (true) {
int64_t fired = nxuskit_clips_session_run(s, 100); // 100 rules per batch
if (fired <= 0) break;
total_fired += fired;
// Your "periodic" logic here:
printf("Progress: %lld rules fired\n", total_fired);
// Check if we should halt
if (should_stop()) {
nxuskit_clips_session_halt(s);
break;
}
}
```
For thread-safe cancellation from another thread:
```c
// Thread 1: run inference
int64_t fired = nxuskit_clips_session_run(s, -1);
// Thread 2: signal halt after timeout
sleep(5);
nxuskit_clips_session_halt(s); // Thread-safe
```
## 4. External Addresses
**What it is:** CLIPS external addresses allow storing opaque C pointers as slot
values, enabling rules to reference host-language objects.
**Why excluded:** External address values are raw `void*` pointers — they cannot
be safely serialized through JSON and would create dangling pointer risks across
session boundaries.
**Workaround:** Use string or integer keys as indirect references:
```c
// Instead of storing a pointer to a connection object:
// (connection (handle ))
// Store an integer key and maintain a lookup table in your host code:
nxuskit_clips_session_load_string(s,
"(deftemplate connection (slot handle (type INTEGER)) (slot status (type SYMBOL)))");
// In C: maintain a mapping
int handle_id = register_connection(conn); // Your lookup table
char buf[128];
snprintf(buf, sizeof(buf), "(connection (handle %d) (status active))", handle_id);
nxuskit_clips_fact_assert_string(s, buf);
// When a rule fires referencing the handle, look up the real object:
// (defrule process-connection
// (connection (handle ?h) (status active))
// =>
// (assert (connection-result (handle ?h) (processed TRUE))))
```
## Summary
| Capability | Status | Workaround Pattern |
|------------|--------|-------------------|
| User-Defined Functions | Excluded | Encode as rules or pre-compute in host language |
| I/O Routers | Excluded | Dribble logging or output facts |
| Periodic Functions | Excluded | Batch `run()` with step limit + polling |
| External Addresses | Excluded | Integer/string keys with host-side lookup table |
All four exclusions are by design — they involve raw C pointers or callbacks that
cannot be safely exposed through the session-handle FFI boundary. The workarounds
provide equivalent functionality using the session API's safe data exchange patterns.
---
# Streaming
URL: https://docs.nxus.systems/nxuskit/guides/streaming
## Overview
Streaming lets your application receive partial model output as it is produced.
Use it for chat UIs, long-running responses, progress reporting, and command-line
tools that should show output immediately instead of waiting for the final
message.
Most LLM providers support token-by-token streaming. Deterministic providers
such as CLIPS and Z3 may emit a single result chunk or a small number of status
updates, depending on the operation.
## When to Use Streaming
| Use streaming when | Use a regular call when |
|--------------------|-------------------------|
| Users should see output immediately | You need one complete JSON response |
| Responses may be long | Responses are small and predictable |
| You want progress or partial results | You need simpler error handling |
| You are building CLI or chat interfaces | You are running batch jobs |
## Rust
```rust
use futures::StreamExt;
use nxuskit::{completion_stream, NxuskitError};
#[tokio::main]
async fn main() -> Result<(), NxuskitError> {
let mut stream = completion_stream("gpt-4o", "Count from one to five.").await?;
while let Some(chunk) = stream.next().await {
print!("{}", chunk?);
}
Ok(())
}
```
## CLI
```bash
nxuskit-cli chat \
--provider openai \
--model gpt-4o \
--stream \
"Explain streaming responses in one paragraph."
```
For machine-readable output, use the Level 1 `call` command with JSONL:
```bash
echo '{"provider":"openai","model":"gpt-4o","prompt":"Count to five."}' \
| nxuskit-cli call --input - --format jsonl --stream
```
## Stream Events
Streaming APIs generally emit:
- **Content chunks** — Partial text or structured deltas.
- **Metadata** — Provider, model, token usage, timing, or trace information when available.
- **Completion** — Final status, finish reason, or terminal error.
The exact fields vary by provider. Code that handles multiple providers should
append content chunks as they arrive and treat metadata as optional.
## Error Handling
Handle errors in the stream loop, not only at stream creation time. A provider
can accept a request and still fail later because of rate limits, network
interruptions, token limits, or a cancelled operation.
## Related Reference
- [Provider Model](/nxuskit/concepts/provider-model/)
- [Cloud LLM Providers](/nxuskit/reference/providers/cloud-llms/)
- [Local LLM Providers](/nxuskit/reference/providers/local-llms/)
- [CLI Input Format Reference](/nxuskit/reference/cli-reference/)
---
# CLIPS Session Migration
URL: https://docs.nxus.systems/nxuskit/migration/clips-session-migration
This guide covers migrating from the legacy `ClipsEnvironment` / `nxuskit_clips_env_*` API
to the new `ClipsSession` / `nxuskit_clips_session_*` API introduced in SDK v0.9.1.
## What Changed
| Aspect | Old API | New API |
|--------|---------|---------|
| Handle type | Opaque pointer (`NxuskitClipsEnv*`) | `uint64_t` session handle |
| Safety | Manual pointer management | Generational index (use-after-free protection) |
| Fact builder | Separate `NxuskitClipsFactBuilder` type | `nxuskit_clips_fact_assert_structured()` (JSON slots) |
| Fact iteration | Pointer chain (`first_fact` → `fact_next`) | `nxuskit_clips_facts_by_template()` (JSON array) |
| Template lookup | `nxuskit_clips_find_template()` → pointer | `nxuskit_clips_template_exists()` / `template_list()` |
| Thread safety | Not guaranteed | Session registry with RwLock; `session_halt()` for cross-thread signalling |
## Who Needs to Migrate
- **Chat provider users** (`NxuskitProvider` / `ChatRequest`): **No changes needed.** The Chat provider interface is unchanged.
- **Direct C ABI users** (`nxuskit_clips_env_*` functions): **Must migrate.** Old functions are removed.
- **Rust SDK users** (`nxuskit::ClipsEnvironment`): **Must migrate** to `nxuskit::ClipsSession`.
## C ABI Migration
### Session Lifecycle
```c
// OLD
struct NxuskitClipsEnv *env = nxuskit_clips_env_create();
nxuskit_clips_env_load_file(env, "rules.clp");
nxuskit_clips_env_reset(env);
nxuskit_clips_env_run(env, -1);
nxuskit_clips_env_destroy(env);
// NEW
uint64_t s = nxuskit_clips_session_create();
nxuskit_clips_session_load_file(s, "rules.clp");
nxuskit_clips_session_reset(s);
nxuskit_clips_session_run(s, -1);
nxuskit_clips_session_destroy(s);
```
### Asserting Facts
```c
// OLD — string-based
nxuskit_clips_env_assert_string(env, "(sensor (name \"t1\") (value 42))");
// OLD — fact builder
struct NxuskitClipsFactBuilder *fb = nxuskit_clips_fb_create(env, "sensor");
nxuskit_clips_fb_put_string(fb, "name", "t1");
nxuskit_clips_fb_put_integer(fb, "value", 42);
nxuskit_clips_fb_assert(fb);
// NEW — string-based (unchanged pattern)
nxuskit_clips_fact_assert_string(s, "(sensor (name \"t1\") (value 42))");
// NEW — structured (replaces fact builder)
nxuskit_clips_fact_assert_structured(s, "sensor",
"{\"name\":\"t1\",\"value\":42}");
```
### Querying Facts
```c
// OLD — pointer iteration
struct NxuskitClipsTemplate *tmpl = nxuskit_clips_find_template(env, "sensor");
struct NxuskitClipsFact *fact = nxuskit_clips_template_first_fact(tmpl);
while (fact) {
char *slot = nxuskit_clips_fact_get_slot(fact, "value");
// use slot...
nxuskit_free_string(slot);
struct NxuskitClipsFact *next = nxuskit_clips_fact_next(fact);
nxuskit_clips_fact_destroy(fact);
fact = next;
}
nxuskit_clips_template_destroy(tmpl);
// NEW — JSON array
char *facts = nxuskit_clips_facts_by_template(s, "sensor");
// facts is a JSON array of fact objects — parse with your JSON library
nxuskit_free_string(facts);
```
## Rust SDK Migration
### Basic Usage
```rust
// OLD
use nxuskit::ClipsEnvironment;
let env = ClipsEnvironment::new()?;
env.load_from_string("(deftemplate sensor (slot name) (slot value))")?;
env.reset()?;
env.assert_string("(sensor (name \"t1\") (value 42))")?;
env.run(None)?;
if let Some(tmpl) = env.find_template("sensor")? {
for fact in tmpl.facts().flatten() {
println!("{:?}", fact.get_slot("value")?);
}
}
// NEW
use nxuskit::ClipsSession;
let session = ClipsSession::create()?;
session.load_string("(deftemplate sensor (slot name) (slot value))")?;
session.reset()?;
session.assert_string("(sensor (name \"t1\") (value 42))")?;
session.run(-1)?;
let facts = session.facts_by_template("sensor")?;
println!("{}", facts);
// session is destroyed on drop
```
### FBP (Fact-Based Processing) Pattern
```rust
use nxuskit::ClipsSession;
// Create a persistent session for iterative processing
let session = ClipsSession::create()?;
session.load_file("rules/shared/000-core.clp")?;
session.load_file("rules/data-qc/bounds-check.clp")?;
// Cycle 1: Load initial data
session.reset()?;
session.assert_string(r#"(input-data (record-id 1) (value 150.0))"#)?;
session.run(-1)?;
let alerts = session.facts_by_template("alert")?;
// Cycle 2: New data, same rules (facts persist unless reset)
session.assert_string(r#"(input-data (record-id 2) (value 200.0))"#)?;
session.run(-1)?;
let more_alerts = session.facts_by_template("alert")?;
```
### LKS (Load-知識-Solve) Pattern
```rust
use nxuskit::ClipsSession;
// Load once, solve many times
let session = ClipsSession::create()?;
session.load_file("expert-system.clp")?;
for case in cases {
session.reset()?; // Clear facts, keep rules
session.assert_string(&format!("(case-data (id {}) (symptoms {}))",
case.id, case.symptoms))?;
session.run(-1)?;
let diagnosis = session.facts_by_template("diagnosis")?;
println!("Case {}: {}", case.id, diagnosis);
}
```
## New Capabilities (No Old Equivalent)
These features are only available in the Session API:
| Feature | Function | Description |
|---------|----------|-------------|
| Session halt | `session_halt()` | Thread-safe inference cancellation |
| Session cache | `session_preload()` / `get_cached()` | Named session caching |
| Fact retraction | `fact_retract()` / `fact_retract_by_template()` | Targeted fact removal |
| Rule debugging | `rule_breakpoint_set()` / `rule_times_fired()` | Rule-level debugging |
| Global variables | `global_get_value()` / `global_set_value()` | Defglobal access |
| Watch/dribble | `watch()` / `dribble_on()` | Tracing and logging |
| Strategy control | `strategy_get()` / `strategy_set()` | Conflict resolution |
| Module focus | `focus_push()` / `focus_pop()` | Module execution control |
| Structured assert | `fact_assert_structured()` | JSON-based fact assertion |
| Binary save/load | `session_save_binary()` / `load_binary()` | Fast environment serialization |
---
# Logprobs Migration
URL: https://docs.nxus.systems/nxuskit/migration/logprobs-migration
**Audience:** SDK consumers that previously needed to request token log
probabilities through `provider_options` because the SDK had no first-class
field.
## What Changed in v0.9.3
The Rust wrapper, Python SDK, Go SDK, and the C ABI now expose first-class
unary chat logprobs:
- **Request side:** `ChatRequest.logprobs: Option` and
`ChatRequest.top_logprobs: Option` (Rust); equivalents in Python and
the C ABI envelope. Use the Rust builders `with_logprobs(true)` /
`with_top_logprobs(n)`, the Python `ChatRequest(..., logprobs=True,
top_logprobs=5)`, or set the JSON fields directly when calling the C ABI.
- **Response side:** `ChatResponse.logprobs: Option` with
typed `TokenLogprob` (selected token + bytes) and `TopLogprob` (each
alternative + bytes). The wire path is `logprobs.content[]` (matches
OpenAI; pinned by
`packages/nxuskit-engine/crates/nxuskit-core/tests/logprobs_abi_passthrough_test.rs`).
- **Engine behavior:** `parameter_adapter.rs::adapt_logprobs` performs
warn-and-drop when a provider's `ProviderCapabilities.supports_logprobs`
is `false`, emits a structured `Info` warning with
`parameter == "logprobs"`, and drops both first-class fields. It does
**not** tunnel logprobs through `provider_options`.
## Migration For Existing Callers
If you previously stuffed logprobs into `provider_options` to work around
the missing first-class field:
```rust
// OLD (pre-v0.9.3) — pattern still parses but never reaches the provider
let req = ChatRequest::new("gpt-5.4")
.with_message(Message::user("..."))
.with_provider_options(serde_json::json!({
"logprobs": true,
"top_logprobs": 5,
}));
```
Switch to the first-class fields:
```rust
// NEW (v0.9.3+) — first-class, capability-gated, surfaces typed response
let req = ChatRequest::new("gpt-5.4")
.with_message(Message::user("..."))
.with_logprobs(true)
.with_top_logprobs(5);
```
Python:
```python
from nxuskit import ChatRequest
req = ChatRequest(
model="gpt-5.4",
messages=[{"role": "user", "content": "..."}],
logprobs=True,
top_logprobs=5,
)
```
C ABI / direct JSON:
```json
{
"model": "gpt-5.4",
"messages": [{"role": "user", "content": "..."}],
"logprobs": true,
"top_logprobs": 5
}
```
## Why The Switch Matters
- **Capability gating:** the engine only forwards logprobs to providers
whose capability map enables it. The legacy `provider_options` path
bypasses this check and silently dies on unsupported providers.
- **Typed responses:** `ChatResponse.logprobs` returns a typed
`LogprobsData` rather than raw provider JSON. Selected token and
alternative tokens are addressable as fields, including UTF-8 bytes
when present.
- **Cross-language parity:** Rust, Python, Go, and the C ABI all use the
same wire shape (`logprobs.content[]` with `token`, `logprob`, `bytes`,
`top_logprobs`). Switching once works everywhere.
- **No silent drops:** unsupported providers now emit a structured
warning instead of swallowing the request, so callers can detect and
fall back.
## v0.9.4 update
- **Streaming logprobs shipped in v0.9.4** (sprint S1 / branch 098).
`StreamChunk` now carries `logprobs: Option` (Rust),
`Logprobs *StreamLogprobsDelta` (Go), `logprobs: Optional[StreamLogprobsDelta]`
(Python) - additive, defaults to `None`/`nil` for non-supporting providers.
`ProviderCapabilities.supports_streaming_logprobs` gates it (with
`supports_streaming_logprobs => supports_logprobs` enforced). OpenAI is the
only provider with `supports_streaming_logprobs = true` per fixture evidence;
all others are `false` per the evidence-first rule. See the v0.9.4 CHANGELOG
entry for the cross-language parity harness.
- **`CapabilityManifest` v2** - a public preview subset for provider/model
capability discovery was introduced in v0.9.4 (sprint S2/S3 / branch 099);
the full internal manifest is unchanged. The publication decision is recorded
in the 099 artifacts.
---
# Upgrade Path
URL: https://docs.nxus.systems/nxuskit/migration/upgrade-path
## Overview
When a Pro feature is called without valid authorization, the SDK returns
a specific error type with an actionable message. This document maps every
error to its cause and resolution.
## Error Reference
### `FeatureUnavailable`
**Message**: varies by context (see sub-cases below)
This is the umbrella error returned when a Pro feature cannot be accessed.
The message text tells you exactly what to do.
---
### `LicenseRequired`
**Returned when**: A Pro feature is called but no valid license token was
found in the resolution chain (env var → file → API parameter).
**Message**:
```
License installation required.
```
**Resolution**:
1. Authenticate: `nxuskit-cli license login`
2. Activate your license: `nxuskit-cli license activate --key `
3. For CI/CD: set `NXUSKIT_LICENSE_TOKEN` environment variable with your
deployment token
4. To start a trial: `nxuskit-cli license login` then `nxuskit-cli license activate --trial`
---
### `LicenseExpired`
**Returned when**: The developer token's subscription period has ended.
**Message**:
```
License installation required.
```
**Resolution**:
1. Renew your subscription at your account dashboard
2. After renewal, run `nxuskit-cli license activate --key ` to get a
fresh token
3. Community features continue working during the gap
---
### `EditionInsufficient`
**Returned when**: You have a valid token but the binary is the Community
edition, which does not include Pro code.
**Message**:
```
This feature requires Pro edition.
```
**Resolution**:
1. Download the Pro edition binary (requires authenticated access)
2. Replace your Community binary with the Pro binary
3. Your existing license token will be recognized automatically
---
### `VersionCeilingExceeded`
**Returned when**: A deployment token's version ceiling is lower than the
running SDK version.
**Message**:
```
Deployment token covers up to v{ceiling}. Update your deployment token for v{current}+ support.
```
**Resolution**:
1. If you have an active support subscription, request an updated
deployment token from your account dashboard
2. Alternatively, pin the SDK version to stay within the token ceiling
3. Contact **support@nxus.systems** if you need help
---
### `TrialSuspended`
**Returned when**: A trial token was issued but not activated within
the 7-day grace period.
**Message**:
```
License installation required.
```
**Resolution**:
1. Run `nxuskit-cli license login` to authenticate
2. Run `nxuskit-cli license activate --trial` to resume the trial
3. This extends Pro access for the remainder of the 30-day trial period
---
### `TrialExpired`
**Returned when**: The 30-day trial period has ended.
**Message**:
```
License installation required.
```
**Resolution**:
1. Purchase a Pro license
2. Community features continue working without interruption
3. All Pro features will be restored immediately after activation
---
### `TrialIssuanceFailed`
**Returned when**: The SDK attempted to issue a trial token but could
not complete the operation.
**Message**:
```
License installation required.
```
**Resolution**:
1. Run `nxuskit-cli license login` to authenticate first
2. Then run `nxuskit-cli license activate --trial`
3. Community features remain available regardless
---
## Error Handling by Language
### Rust
```rust
use nxuskit::{FeatureUnavailableError, LicenseExpiredError, LicenseRequiredError};
match nxuskit::zen_evaluate(&table, &input) {
Ok(result) => { /* success */ }
Err(e) if e.is::() => {
eprintln!("{}", e); // "License installation required."
}
Err(e) if e.is::() => {
eprintln!("{}", e); // "License installation required."
}
Err(e) => { /* other errors */ }
}
```
### Python
```python
from nxuskit import zen_evaluate
from nxuskit import LicenseRequiredError, LicenseExpiredError, FeatureUnavailableError
try:
result = zen_evaluate(table_path, input_data)
except LicenseRequiredError as e:
print(e.message) # "License installation required."
except LicenseExpiredError as e:
print(e.message) # "License installation required."
except FeatureUnavailableError as e:
print(e.message) # generic feature gate
```
### Go
```go
import "github.com/nxus-SYSTEMS/nxuskit-go"
result, err := nxuskit.ZenEvaluate(table, input)
if err != nil {
switch {
case errors.Is(err, nxuskit.ErrLicenseRequired):
fmt.Println(err) // "License installation required."
case errors.Is(err, nxuskit.ErrLicenseExpired):
fmt.Println(err) // "License installation required."
default:
fmt.Println(err)
}
}
```
## Quick Decision Tree
```
Pro feature called
│
├─ No token found? → "License installation required."
├─ Token expired? → "License installation required."
├─ Community binary? → EditionInsufficient → download Pro binary
├─ Version ceiling hit? → VersionCeilingExceeded → update deployment token
├─ Trial not activated? → "License installation required."
├─ Trial past 30 days? → "License installation required."
├─ Can't reach service? → "License installation required."
└─ Valid token + Pro binary? → Success
```
---
# API Reference
URL: https://docs.nxus.systems/nxuskit/reference/api
## Overview
nxusKit APIs are organized around a small set of shared contracts:
- **Provider configuration** creates a backend connection.
- **Chat requests** carry model names, messages, and provider options.
- **Chat responses** return content, metadata, usage, and errors.
- **Streaming calls** emit incremental chunks for interactive workflows.
- **Specialized providers** such as CLIPS and Z3 use structured JSON payloads
inside the same request/response pattern.
Use this page as the entry point for API-level reference material.
## Core References
| Reference | Use for |
|-----------|---------|
| [C ABI Reference](/nxuskit/reference/api-reference/) | C functions, ownership rules, FFI handles, CLIPS session calls, and memory management. |
| [CLI Input Format Reference](/nxuskit/reference/cli-reference/) | Structured JSON/YAML/JSONL input contracts for `nxuskit-cli`. |
| [Cloud LLM Providers](/nxuskit/reference/providers/cloud-llms/) | Provider configuration for hosted LLM APIs. |
| [Local LLM Providers](/nxuskit/reference/providers/local-llms/) | Ollama, LM Studio, and in-process local model configuration. |
| [Expert System & Utility Providers](/nxuskit/reference/providers/expert-systems/) | CLIPS, MCP, Mock, and Loopback configuration. |
| [Z3 Constraint Satisfaction Provider](/nxuskit/reference/providers/z3-solver/) | Z3 input, output, optimization, and streaming contracts. |
## Shared Chat Shape
The language wrappers expose native types, but the shared request shape is:
```json
{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "You are concise."},
{"role": "user", "content": "Summarize nxusKit."}
],
"max_tokens": 512,
"temperature": 0.2,
"stream": false
}
```
Responses include provider content plus optional metadata:
```json
{
"content": "nxusKit is a multi-language SDK...",
"model": "gpt-4o",
"finish_reason": "stop",
"usage": {
"input_tokens": 24,
"output_tokens": 12
}
}
```
Provider-specific options belong in the configuration object or provider options
map. See the provider reference pages before relying on a field across multiple
backends.
## Memory and Ownership
When calling through the C ABI, every returned provider handle, response handle,
stream handle, and allocated string has an explicit free function. Use the
[ownership summary](/nxuskit/reference/api-reference/#ownership-summary) before
integrating from C, C++, Go FFI, Python FFI, or another native boundary.
---
# C ABI Reference
URL: https://docs.nxus.systems/nxuskit/reference/api-reference
All functions are declared in `nxuskit.h`. The ABI uses opaque handles and JSON
strings for all data exchange. Every function is thread-safe unless noted.
## Version
### `nxuskit_version`
```c
const char *nxuskit_version(void);
```
Returns the library version string (e.g., `"1.0.1"`). The returned pointer is
static and valid for the process lifetime. Never returns NULL.
## Provider Lifecycle
### `nxuskit_create_provider`
```c
struct NxuskitProvider *nxuskit_create_provider(const char *config_json);
```
Creates a provider from a JSON configuration string.
**Parameters:**
- `config_json` — JSON string with at minimum `{"provider_type": "..."}`.
See [Provider Reference](../providers/cloud-llms/) for provider-specific fields.
**Returns:** Opaque provider handle, or NULL on failure. On failure, call
`nxuskit_last_error()` for the error message.
**Ownership:** Caller owns the returned handle. Must call `nxuskit_free_provider()`
when done.
**Config JSON fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `provider_type` | string | Yes | Provider identifier (see providers list) |
| `api_key` | string | Varies | API key for cloud providers |
| `model` | string | No | Default model name |
| `base_url` | string | No | Custom API endpoint |
| `timeout_ms` | integer | No | Request timeout in milliseconds |
**Example:**
```c
const char *config = "{\"provider_type\":\"openai\",\"api_key\":\"sk-...\"}";
struct NxuskitProvider *p = nxuskit_create_provider(config);
if (!p) {
fprintf(stderr, "Error: %s\n", nxuskit_last_error());
}
```
### `nxuskit_free_provider`
```c
void nxuskit_free_provider(struct NxuskitProvider *provider);
```
Frees a provider handle. Safe to call with NULL (no-op).
**Parameters:**
- `provider` — Handle from `nxuskit_create_provider()`, or NULL.
## Synchronous Chat
### `nxuskit_chat`
```c
struct NxuskitResponse *nxuskit_chat(
struct NxuskitProvider *provider,
const char *request_json
);
```
Sends a synchronous chat request. Blocks until the response is complete.
**Parameters:**
- `provider` — Provider handle (must not be NULL)
- `request_json` — JSON chat request string
**Returns:** Response handle, or NULL on failure.
**Ownership:** Caller owns the returned handle. Must call `nxuskit_free_response()`.
**Request JSON fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `model` | string | Yes | Model identifier |
| `messages` | array | Yes | Array of `{role, content}` objects |
| `temperature` | float | No | Sampling temperature (0.0–2.0) |
| `max_tokens` | integer | No | Maximum tokens in response |
| `top_p` | float | No | Nucleus sampling parameter |
| `stop` | array | No | Stop sequences |
| `stream` | boolean | No | Must be `false` for sync (default) |
| `response_format` | object | No | Response format constraints |
**Message object:**
| Field | Type | Description |
|-------|------|-------------|
| `role` | string | `"system"`, `"user"`, or `"assistant"` |
| `content` | string | Message content |
### `nxuskit_response_json`
```c
const char *nxuskit_response_json(const struct NxuskitResponse *response);
```
Returns the JSON string from a response handle.
**Parameters:**
- `response` — Response handle from `nxuskit_chat()` (must not be NULL)
**Returns:** JSON string pointer. Valid only while the response handle exists.
Do **not** free this pointer — it is owned by the response handle.
**Response JSON fields:**
| Field | Type | Description |
|-------|------|-------------|
| `content` | string | The model's response text |
| `model` | string | Model used |
| `provider` | string | Provider name |
| `usage` | object | Token usage (if available) |
| `usage.prompt_tokens` | integer | Input tokens |
| `usage.completion_tokens` | integer | Output tokens |
| `usage.total_tokens` | integer | Total tokens |
| `finish_reason` | string | Why generation stopped |
| `warnings` | array | Provider warnings (if any) |
### `nxuskit_free_response`
```c
void nxuskit_free_response(struct NxuskitResponse *response);
```
Frees a response handle. Safe to call with NULL.
## Streaming Chat
### Callback Types
```c
typedef int32_t (*NxuskitStreamCallback)(
const char *chunk_json,
void *user_data
);
typedef void (*NxuskitStreamDoneCallback)(
const char *final_json,
void *user_data
);
```
**`NxuskitStreamCallback`** is called for each streaming chunk. Return 0 to
continue, non-zero to request cancellation.
**`NxuskitStreamDoneCallback`** is called exactly once when streaming completes
(success, error, or cancellation).
**Important:** Callbacks fire from a **background thread**. The caller must
ensure `user_data` is thread-safe.
### `nxuskit_chat_stream`
```c
struct NxuskitStream *nxuskit_chat_stream(
struct NxuskitProvider *provider,
const char *request_json,
NxuskitStreamCallback on_chunk,
NxuskitStreamDoneCallback on_done,
void *user_data
);
```
Starts a streaming chat request. Returns immediately; chunks arrive via callbacks.
**Parameters:**
- `provider` — Provider handle (must not be NULL)
- `request_json` — JSON chat request string
- `on_chunk` — Called for each chunk (from background thread)
- `on_done` — Called once when streaming ends (from background thread)
- `user_data` — Opaque pointer passed to both callbacks
**Returns:** Stream handle, or NULL on failure.
**Chunk JSON fields:**
| Field | Type | Description |
|-------|------|-------------|
| `delta` | string | Incremental text content |
| `index` | integer | Chunk sequence number (0-based) |
| `thinking` | string | Chain-of-thought reasoning (if enabled, optional) |
| `finish_reason` | string | Why generation stopped (set on final chunk, optional) |
| `usage` | object | Token usage statistics (typically only on final chunk, optional) |
| `tool_calls` | array | Tool call deltas (if applicable, optional) |
**Done JSON fields:** Same as synchronous response JSON, plus optional `error`:
| Field | Type | Description |
|-------|------|-------------|
| `error.error_type` | string | Error category |
| `error.message` | string | Error description |
### `nxuskit_cancel_stream`
```c
void nxuskit_cancel_stream(struct NxuskitStream *stream);
```
Cancels a streaming request. Blocks until all pending callbacks have completed.
After this call returns, no further callbacks will fire.
Safe to call with NULL.
### `nxuskit_free_stream`
```c
void nxuskit_free_stream(struct NxuskitStream *stream);
```
Frees a stream handle. Must be called after the stream completes or is cancelled.
Safe to call with NULL.
**Typical lifecycle:**
```c
stream = nxuskit_chat_stream(provider, request, on_chunk, on_done, data);
// ... callbacks fire ...
// After on_done fires (or if you want to cancel):
nxuskit_cancel_stream(stream); // optional — ensures no more callbacks
nxuskit_free_stream(stream); // required — frees resources
```
## Model Discovery
### `nxuskit_list_models`
```c
char *nxuskit_list_models(struct NxuskitProvider *provider);
```
Returns a JSON array of available models.
**Parameters:**
- `provider` — Provider handle (must not be NULL)
**Returns:** JSON string (caller-owned), or NULL on failure.
**Ownership:** Caller must free the returned string with `nxuskit_free_string()`.
**Response format:**
```json
[
{"id": "gpt-4o", "name": "GPT-4o"},
{"id": "gpt-4o-mini", "name": "GPT-4o Mini"}
]
```
## Error Handling
### `nxuskit_last_error`
```c
const char *nxuskit_last_error(void);
```
Returns the last error message for the **calling thread**. Returns NULL if no
error has occurred on this thread.
**Thread-local:** Each thread has its own error state. Calling any `nxuskit_*`
function may overwrite the previous error on that thread.
**Lifetime:** The returned pointer is valid until the next `nxuskit_*` call on
the same thread.
## Memory Management
### `nxuskit_free_string`
```c
void nxuskit_free_string(char *ptr);
```
Frees a caller-owned string returned by any `nxuskit_*` function that returns
`char*` (e.g., `nxuskit_list_models()`, `nxuskit_clips_facts_list()`,
`nxuskit_clips_eval()`). Safe to call with NULL.
**Important:** Only use this for strings documented as "caller-owned". Do not
use it for strings from `nxuskit_response_json()` (those are owned by the
response handle) or `nxuskit_version()` (static).
## Ownership Summary
| Function | Returns | Owned By | Free With |
|----------|---------|----------|-----------|
| `nxuskit_version()` | `const char*` | Library (static) | Never free |
| `nxuskit_create_provider()` | `NxuskitProvider*` | Caller | `nxuskit_free_provider()` |
| `nxuskit_chat()` | `NxuskitResponse*` | Caller | `nxuskit_free_response()` |
| `nxuskit_response_json()` | `const char*` | Response handle | Freed with response |
| `nxuskit_chat_stream()` | `NxuskitStream*` | Caller | `nxuskit_free_stream()` |
| `nxuskit_list_models()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_last_error()` | `const char*` | Thread-local | Never free |
## CLIPS Session API
Direct access to the CLIPS 6.4.2 rule engine via session-based handles — create
sessions, load rules, assert facts, run inference, and inspect results without
going through the provider/chat abstraction.
All CLIPS operations use opaque `uint64_t` session handles (generational indices
that prevent use-after-free). Return conventions:
- `int32_t` functions return 0 on success, -1 on error
- `char*` functions return a JSON string (caller-owned, free with `nxuskit_free_string()`) or NULL on error
- `bool` functions return the queried value; check `nxuskit_last_error()` on unexpected results
### Session Lifecycle
#### `nxuskit_clips_session_create`
```c
uint64_t nxuskit_clips_session_create(void);
```
Creates a new isolated CLIPS session. Returns a non-zero session handle, or 0 on
failure (check `nxuskit_last_error()`).
#### `nxuskit_clips_session_destroy`
```c
void nxuskit_clips_session_destroy(uint64_t session);
```
Destroys a session and frees all resources. No-op if the handle is invalid.
#### `nxuskit_clips_session_reset`
```c
int32_t nxuskit_clips_session_reset(uint64_t session);
```
Resets the session: clears all facts, preserves rules, restores initial-fact.
#### `nxuskit_clips_session_clear`
```c
int32_t nxuskit_clips_session_clear(uint64_t session);
```
Clears everything (facts, rules, templates) — returns the session to a pristine state.
#### `nxuskit_clips_session_info`
```c
char *nxuskit_clips_session_info(uint64_t session);
```
Returns session metadata as a JSON object (module count, rule count, fact count, etc.).
### Loading Constructs
#### `nxuskit_clips_session_load_file`
```c
int32_t nxuskit_clips_session_load_file(uint64_t session, const char *path);
```
Loads constructs from a `.clp` file.
#### `nxuskit_clips_session_load_string`
```c
int32_t nxuskit_clips_session_load_string(uint64_t session, const char *constructs);
```
Loads constructs from an in-memory string.
**Example:**
```c
uint64_t s = nxuskit_clips_session_create();
nxuskit_clips_session_load_string(s,
"(deftemplate sensor (slot name) (slot value))");
```
#### `nxuskit_clips_session_load_binary`
```c
int32_t nxuskit_clips_session_load_binary(uint64_t session, const char *path);
```
Loads a pre-compiled binary image (`.bin` file created with `save_binary`).
#### `nxuskit_clips_session_save_binary`
```c
int32_t nxuskit_clips_session_save_binary(uint64_t session, const char *path);
```
Saves the current session state as a binary image for fast reloading.
#### `nxuskit_clips_session_build`
```c
int32_t nxuskit_clips_session_build(uint64_t session, const char *construct);
```
Builds a single CLIPS construct (deftemplate, defrule, etc.) from a string.
#### `nxuskit_clips_session_batch`
```c
int32_t nxuskit_clips_session_batch(uint64_t session, const char *path);
```
Executes a batch file of CLIPS commands.
#### `nxuskit_clips_session_load_json`
```c
int32_t nxuskit_clips_session_load_json(uint64_t session, const char *json);
```
Loads constructs from a JSON specification (templates, rules, facts in one call).
### Session Cache
#### `nxuskit_clips_session_preload`
```c
int32_t nxuskit_clips_session_preload(const char *name, const char *rules_json);
```
Preloads a named session into the cache. The session is created, rules are loaded,
and the session is stored for later retrieval via `get_cached`.
#### `nxuskit_clips_session_get_cached`
```c
uint64_t nxuskit_clips_session_get_cached(const char *name);
```
Returns a cached session handle by name. Returns 0 if not found.
#### `nxuskit_clips_session_cache_remove`
```c
int32_t nxuskit_clips_session_cache_remove(const char *name);
```
Removes a named session from the cache and destroys it.
### Fact Operations
#### `nxuskit_clips_fact_assert_string`
```c
int64_t nxuskit_clips_fact_assert_string(uint64_t session, const char *fact_string);
```
Asserts a fact using CLIPS syntax. Returns the fact index (>= 0) on success, or -1 on error.
**Example:**
```c
int64_t idx = nxuskit_clips_fact_assert_string(s,
"(sensor (name \"temp-1\") (value 150))");
```
#### `nxuskit_clips_fact_assert_structured`
```c
int64_t nxuskit_clips_fact_assert_structured(
uint64_t session,
const char *template_name,
const char *slots_json
);
```
Asserts a fact using a JSON slot specification. Returns the fact index or -1.
**Example:**
```c
int64_t idx = nxuskit_clips_fact_assert_structured(s, "sensor",
"{\"name\":\"temp-1\",\"value\":150}");
```
#### `nxuskit_clips_fact_retract`
```c
int32_t nxuskit_clips_fact_retract(uint64_t session, int64_t fact_index);
```
Retracts a fact by its index.
#### `nxuskit_clips_fact_retract_by_template`
```c
int32_t nxuskit_clips_fact_retract_by_template(uint64_t session, const char *template_name);
```
Retracts all facts of a given template.
#### `nxuskit_clips_fact_exists`
```c
bool nxuskit_clips_fact_exists(uint64_t session, int64_t fact_index);
```
Returns true if the fact index refers to an existing fact.
#### `nxuskit_clips_fact_get_slot`
```c
char *nxuskit_clips_fact_get_slot(uint64_t session, int64_t fact_index, const char *slot_name);
```
Returns a slot value as a type-tagged JSON string (e.g., `{"type":"integer","value":42}`).
**Slot JSON types:**
| CLIPS Type | JSON `type` | JSON `value` |
|------------|-------------|--------------|
| INTEGER | `"integer"` | number |
| FLOAT | `"float"` | number |
| STRING | `"string"` | string |
| SYMBOL | `"symbol"` | string |
| MULTIFIELD | `"multifield"` | array of typed values |
#### `nxuskit_clips_fact_slot_values`
```c
char *nxuskit_clips_fact_slot_values(uint64_t session, int64_t fact_index);
```
Returns all slot values as a JSON object.
#### `nxuskit_clips_fact_pp_form`
```c
char *nxuskit_clips_fact_pp_form(uint64_t session, int64_t fact_index);
```
Returns the pretty-printed CLIPS representation of a fact.
#### `nxuskit_clips_fact_index`
```c
int64_t nxuskit_clips_fact_index(uint64_t session, int64_t fact_index);
```
Returns the canonical CLIPS fact index, or -1 on error.
#### `nxuskit_clips_facts_list`
```c
char *nxuskit_clips_facts_list(uint64_t session);
```
Returns all facts as a JSON array.
#### `nxuskit_clips_facts_by_template`
```c
char *nxuskit_clips_facts_by_template(uint64_t session, const char *template_name);
```
Returns all facts matching a template as a JSON array.
#### `nxuskit_clips_fact_duplication_get` / `set`
```c
bool nxuskit_clips_fact_duplication_get(uint64_t session);
int32_t nxuskit_clips_fact_duplication_set(uint64_t session, bool allow);
```
Query or set whether duplicate facts are allowed.
### Template Operations
#### `nxuskit_clips_template_exists`
```c
bool nxuskit_clips_template_exists(uint64_t session, const char *name);
```
Returns true if the named template exists in the session.
#### `nxuskit_clips_template_list`
```c
char *nxuskit_clips_template_list(uint64_t session);
```
Returns all template names as a JSON array.
#### `nxuskit_clips_template_slot_names`
```c
char *nxuskit_clips_template_slot_names(uint64_t session, const char *template_name);
```
Returns slot names for a template as a JSON array.
#### `nxuskit_clips_template_slot_info`
```c
char *nxuskit_clips_template_slot_info(uint64_t session, const char *template_name);
```
Returns detailed slot information (types, defaults, constraints) as JSON.
#### `nxuskit_clips_template_facts`
```c
char *nxuskit_clips_template_facts(uint64_t session, const char *template_name);
```
Returns all facts of a template as a JSON array.
#### `nxuskit_clips_template_pp_form`
```c
char *nxuskit_clips_template_pp_form(uint64_t session, const char *template_name);
```
Returns the pretty-printed CLIPS definition of a template.
### Inference Engine
#### `nxuskit_clips_session_run`
```c
int64_t nxuskit_clips_session_run(uint64_t session, int64_t limit);
```
Runs inference. Pass `limit = -1` to run until the agenda is exhausted.
Returns the number of rules fired, or -1 on error.
#### `nxuskit_clips_session_halt`
```c
int32_t nxuskit_clips_session_halt(uint64_t session);
```
Signals the session to halt inference (thread-safe — can be called from another thread).
#### `nxuskit_clips_agenda_size`
```c
int64_t nxuskit_clips_agenda_size(uint64_t session);
```
Returns the number of activations on the agenda.
#### `nxuskit_clips_agenda_clear`
```c
int32_t nxuskit_clips_agenda_clear(uint64_t session);
```
Removes all activations from the agenda.
#### `nxuskit_clips_agenda_reorder`
```c
int32_t nxuskit_clips_agenda_reorder(uint64_t session);
```
Reorders the agenda using the current conflict resolution strategy.
#### `nxuskit_clips_strategy_get` / `set`
```c
char *nxuskit_clips_strategy_get(uint64_t session);
int32_t nxuskit_clips_strategy_set(uint64_t session, const char *strategy);
```
Get or set the conflict resolution strategy. Valid values: `"depth"`, `"breadth"`,
`"simplicity"`, `"complexity"`, `"lex"`, `"mea"`, `"random"`.
#### `nxuskit_clips_salience_mode_get` / `set`
```c
char *nxuskit_clips_salience_mode_get(uint64_t session);
int32_t nxuskit_clips_salience_mode_set(uint64_t session, const char *mode);
```
Get or set the salience evaluation mode.
### Rule Operations
#### `nxuskit_clips_rule_exists`
```c
bool nxuskit_clips_rule_exists(uint64_t session, const char *name);
```
Returns true if the named rule exists.
#### `nxuskit_clips_rule_list`
```c
char *nxuskit_clips_rule_list(uint64_t session);
```
Returns all rule names as a JSON array.
#### `nxuskit_clips_rule_times_fired`
```c
int64_t nxuskit_clips_rule_times_fired(uint64_t session, const char *rule_name);
```
Returns how many times a rule has fired, or -1 on error.
#### `nxuskit_clips_rule_breakpoint_set` / `remove` / `has_breakpoint`
```c
int32_t nxuskit_clips_rule_breakpoint_set(uint64_t session, const char *rule_name);
int32_t nxuskit_clips_rule_breakpoint_remove(uint64_t session, const char *rule_name);
bool nxuskit_clips_rule_has_breakpoint(uint64_t session, const char *rule_name);
```
Manage breakpoints on rules for debugging.
#### `nxuskit_clips_rule_refresh`
```c
int32_t nxuskit_clips_rule_refresh(uint64_t session, const char *rule_name);
```
Refreshes a rule, placing its activations back on the agenda.
#### `nxuskit_clips_rule_pp_form`
```c
char *nxuskit_clips_rule_pp_form(uint64_t session, const char *rule_name);
```
Returns the pretty-printed CLIPS definition of a rule.
#### `nxuskit_clips_rule_delete`
```c
int32_t nxuskit_clips_rule_delete(uint64_t session, const char *rule_name);
```
Deletes a rule from the session.
### Module Operations
#### `nxuskit_clips_module_exists`
```c
bool nxuskit_clips_module_exists(uint64_t session, const char *name);
```
Returns true if the named module exists.
#### `nxuskit_clips_module_list`
```c
char *nxuskit_clips_module_list(uint64_t session);
```
Returns all module names as a JSON array.
#### `nxuskit_clips_module_current_get` / `set`
```c
char *nxuskit_clips_module_current_get(uint64_t session);
int32_t nxuskit_clips_module_current_set(uint64_t session, const char *name);
```
Get or set the current module.
#### `nxuskit_clips_focus_push` / `get` / `pop` / `clear`
```c
int32_t nxuskit_clips_focus_push(uint64_t session, const char *module_name);
char *nxuskit_clips_focus_get(uint64_t session);
int32_t nxuskit_clips_focus_pop(uint64_t session);
int32_t nxuskit_clips_focus_clear(uint64_t session);
```
Manage the module focus stack (controls which module's rules are eligible to fire).
### Global Variables
#### `nxuskit_clips_global_exists`
```c
bool nxuskit_clips_global_exists(uint64_t session, const char *name);
```
Returns true if the named defglobal exists.
#### `nxuskit_clips_global_list`
```c
char *nxuskit_clips_global_list(uint64_t session);
```
Returns all global variable names as a JSON array.
#### `nxuskit_clips_global_get_value` / `set_value`
```c
char *nxuskit_clips_global_get_value(uint64_t session, const char *name);
int32_t nxuskit_clips_global_set_value(uint64_t session, const char *name, const char *value_json);
```
Get or set a global variable value. Values use the type-tagged JSON format.
#### `nxuskit_clips_reset_globals_get` / `set`
```c
bool nxuskit_clips_reset_globals_get(uint64_t session);
int32_t nxuskit_clips_reset_globals_set(uint64_t session, bool reset);
```
Query or set whether globals are reset when `session_reset` is called.
### Evaluation
#### `nxuskit_clips_eval`
```c
char *nxuskit_clips_eval(uint64_t session, const char *expression);
```
Evaluates a CLIPS expression and returns the result as a type-tagged JSON string.
#### `nxuskit_clips_function_call`
```c
char *nxuskit_clips_function_call(uint64_t session, const char *function_name, const char *args);
```
Calls a CLIPS function by name with optional arguments string.
### Debugging
#### `nxuskit_clips_watch` / `unwatch`
```c
int32_t nxuskit_clips_watch(uint64_t session, const char *item);
int32_t nxuskit_clips_unwatch(uint64_t session, const char *item);
```
Enable or disable tracing for a watch item. Valid items: `"facts"`, `"rules"`,
`"activations"`, `"compilations"`, `"statistics"`, `"globals"`, `"focus"`, `"all"`.
#### `nxuskit_clips_dribble_on` / `off`
```c
int32_t nxuskit_clips_dribble_on(uint64_t session, const char *path);
int32_t nxuskit_clips_dribble_off(uint64_t session);
```
Start or stop logging all CLIPS I/O to a file.
### CLIPS Ownership Summary
| Function | Returns | Owned By | Free With |
|----------|---------|----------|-----------|
| `nxuskit_clips_session_create()` | `uint64_t` | Session registry | `nxuskit_clips_session_destroy()` |
| `nxuskit_clips_session_get_cached()` | `uint64_t` | Session cache | `nxuskit_clips_session_cache_remove()` |
| `nxuskit_clips_session_info()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_fact_get_slot()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_fact_slot_values()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_fact_pp_form()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_facts_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_facts_by_template()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_slot_names()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_slot_info()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_facts()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_pp_form()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_rule_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_rule_pp_form()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_module_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_module_current_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_focus_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_global_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_global_get_value()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_strategy_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_salience_mode_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_eval()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_function_call()` | `char*` | Caller | `nxuskit_free_string()` |
### Complete Example
```c
#include "nxuskit.h"
#include
int main(void) {
// Create session
uint64_t s = nxuskit_clips_session_create();
if (!s) {
fprintf(stderr, "Error: %s\n", nxuskit_last_error());
return 1;
}
// Load rules
nxuskit_clips_session_load_string(s,
"(deftemplate sensor (slot name (type STRING)) (slot value (type INTEGER)))");
nxuskit_clips_session_load_string(s,
"(defrule high-temp"
" (sensor (name ?n) (value ?v&:(> ?v 100)))"
" =>"
" (printout t \"ALERT: \" ?n \" = \" ?v crlf))");
// Assert facts and run
nxuskit_clips_session_reset(s);
nxuskit_clips_fact_assert_string(s, "(sensor (name \"temp-1\") (value 150))");
int64_t fired = nxuskit_clips_session_run(s, -1);
printf("Rules fired: %lld\n", fired);
// Inspect results
char *facts = nxuskit_clips_facts_list(s);
printf("Facts: %s\n", facts);
nxuskit_free_string(facts);
// Cleanup
nxuskit_clips_session_destroy(s);
return 0;
}
```
## Error Types
Errors returned in response JSON or via `nxuskit_last_error()`:
| Error Type | Description |
|------------|-------------|
| `configuration` | Invalid config, missing API key, version mismatch |
| `invalid_request` | Malformed request JSON, missing required fields |
| `authentication` | Invalid or expired API key |
| `rate_limit` | Provider rate limit exceeded |
| `provider` | Provider-side error (server error, model not found) |
| `timeout` | Request timed out |
| `stream` | Streaming error (connection lost, cancelled) |
| `internal` | Unexpected internal error |
---
# Changelog
URL: https://docs.nxus.systems/nxuskit/reference/changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
Public SDK release tags begin at `sdk-v0.9.0`. Earlier entries preserve
pre-public development history with normalized pre-public version numbers after
historical version resets.
## [Unreleased]
## [1.0.1] - 2026-06-08
> Patch release for Pro SDK bundle composition. No API or C ABI signature
> changes from v1.0.0 are introduced.
### Fixed
- Pro SDK bundles now compile `nxuskit-cli solver` and `nxuskit-cli zen` with
the real Pro engine command modules instead of CE-safe stubs.
- Pro CLI builds now enable solver/ZEN capability flags in both `nxuskit-engine`
and `nxuskit-core`, so valid Pro tokens can execute the bundled commands.
- SDK bundle verification now fails if a Pro CLI is compiled with CE stubs or
OSS edition metadata.
## [1.0.0] - 2026-05-28
> General Availability release for the v0.9.4-stabilized SDK API surface.
> This release is intentionally narrow: version metadata moves to `1.0.0`,
> public documentation now reflects GA posture, and SDK bundle packaging guards
> include the Rust benchmark targets required by the wrapper manifest.
### Changed
- Promoted nxusKit SDK to GA in public README/support copy.
- Updated Rust workspace, C ABI, Go SDK, Python SDK, and package metadata to
lockstep version `1.0.0`.
- Promoted Python package classifier to `Development Status :: 5 -
Production/Stable`.
- Refreshed public architecture and README links to the hosted docs site.
- Clarified loopback CLI examples so local copy-paste commands use explicit
loopback model names.
### Fixed
- SDK release workflows now copy `packages/nxuskit/benches` into the bundled
Rust wrapper so the declared benchmark target is present in release archives.
- Packaging verification now fails if the bundled Rust wrapper omits the
declared `logprobs_serialization` benchmark target.
### Compatibility
- No API or C ABI signature changes from v0.9.4 are introduced in this GA cut.
- Pro installation packages continue to be published on the public release page;
Pro capabilities still require a valid license key.
## [0.9.4] - 2026-05-11
> v0.9.4 release candidate. Provider-capability modernization and release
> hardening, consolidating sprints S1 (streaming logprobs, branch 098),
> S2/S3 (provider capability modernization + Capability Manifest v2 decision,
> branch 099), and S4-S6 (CLI Level 2 completion, examples & bundle alignment,
> docs & release candidate, branch 100). Lockstep version bump `0.9.3 -> 0.9.4`
> across all components. **No C ABI signature changes** in this release.
### Added - S1: Streaming Logprobs + Capability Metadata (branch 098)
- `StreamLogprobsDelta` type (Rust engine + wrapper, Go, Python) carrying
per-chunk `TokenLogprob` entries on streaming responses.
- `StreamChunk.logprobs: Option` (Rust),
`StreamChunk.Logprobs *StreamLogprobsDelta` (Go), and
`StreamChunk.logprobs: Optional[StreamLogprobsDelta]` (Python) - additive,
defaults to `None`/`nil` for non-supporting providers.
- `ProviderCapabilities.supports_streaming_logprobs: bool` flag with
`debug_assert!` enforcing `supports_streaming_logprobs => supports_logprobs`.
- GPT-5.4 reasoning-compat warn-and-drop guard: when `reasoning.effort != "none"`,
`temperature`, `top_p`, and `logprobs` are dropped with a warning rather than
passed through.
- CLI `provider info` exposes the `streaming_logprobs` row (human + JSON).
- Cross-language parity harness at
`internal/tests/parity/stream_logprobs/run_parity.sh`.
- OpenAI: `supports_streaming_logprobs = true` (only supporting provider per
fixture evidence); all other providers `false` per the evidence-first rule.
### Added - S2/S3: Provider Capability Modernization + Manifest v2 (branch 099)
- Provider capability surface modernized; `CapabilityProvider` / "capability
provider" vocabulary introduced (no breaking `LLMProvider` rename).
- xAI Grok runtime provider support under canonical provider id `xai`
(`XAI_API_KEY`, default base URL `https://api.x.ai/v1`); `groq` remains
Groq, Inc. and no confusing `grok` alias is registered.
- `CapabilityManifest` v2 concept with a public preview subset for
provider/model capability discovery (full internal manifest unchanged); the
publication decision is recorded in the 099 artifacts.
- OpenAI remains Chat-Completions-first (no full Responses API migration).
### Added - S4: CLI Level 2 completion & stabilization (branch 100)
- **`nxuskit-cli zen validate`** (Pro) - structural validation of a ZEN JSON
Decision Model (JDM): rejects `functionNode` (JavaScript), checks decision
table node shape, attempts expression compilation, and reports
node/decision-table/rule counts. Backed by a new pure
`nxuskit_engine::providers::zen::validate(model_json) -> Result`
engine entry point. Exit 0 = valid; exit 5 = `parse_error` (unparseable input)
or `zen_validate_error` (structurally invalid, with a `problems[]` report);
exit 4 = `entitlement_denied`.
- **`nxuskit-cli zen test`** (Pro) - run a ZEN decision table against a fixture
set `{table, cases: [{name, input, expected}]}` and compare each actual
output to `expected`; on mismatch emits a structured diff report (exit 5,
`zen_test_mismatch`), a per-case eval error is `zen_test_eval_error`, a
fixture parse error is `parse_error`.
- **`nxuskit-cli bn learn`** - parameter learning (MLE / Bayesian) of a
Bayesian network's CPDs from a CSV dataset given the network skeleton; output
is the learned network, BIF-exportable. **`nxuskit-cli bn evidence`** -
validate/normalize an observations map against a network. (Community edition.)
- `solver what-if --compare` and the unsatisfiable-assumptions path are now
covered by non-`#[ignore]`d, entitlement-aware tests (skip-with-reason in CE,
assertions run in the Pro CI lane `.github/workflows/ci-pro.yml`).
- `CliError::CommandValidation { code, message, details }` - exit 5 with a
command-specific `code` string + structured `details` (used by the new ZEN
commands; exit-code *set* unchanged, FR-001 / Article IV).
- Shell support policy documented (`completions`: bash, zsh, fish supported;
PowerShell not generated in v0.9.4; helper snippets + schema bundle locations).
### Added - S5: Examples repo & bundle alignment (branch 100)
- Examples portfolio bundle-instruction refs bumped to v0.9.4;
`PYTHON_EXAMPLES_STATUS.md` records the v0.9.4 Python-parity scope (minimal
slice: the SDK-side `packages/nxuskit-py` FFI version-guard alignment is in
scope; the 17 already-passing Python examples stay; new examples remain
examples-team backlog). Rust vision example confirmed using the v0.9.2
multimodal wrapper API with no text-only caveat.
### Changed
- `nxuskit-py` `_ffi.py` `EXPECTED_VERSION` aligned to the package version
(`0.9.1` -> `0.9.4`) - the cffi loader requires the linked library's
`nxuskit_version()` to match; this unblocks the Python FFI examples that were
previously `broken-upstream` against the v0.9.3 mismatch.
- Lockstep version bump `0.9.3 -> 0.9.4`: Rust workspace + `nxuskit` crate, C
ABI version constant (`nxuskit-core`), Go `nxuskit-go` (`Version` +
`ExpectedNxuskitVersion`), Python `nxuskit-py` (`__version__` + pyproject).
### Compatibility
- **No C ABI signature changes** in v0.9.4 - only the ABI version constant
moves (`0.9.3 -> 0.9.4`); function signatures and struct layouts are frozen
(Article XIV).
- All v0.9.4 additions are additive. The CLI exit-code *set* (0/1/2/3/4/5/130)
is unchanged; the new ZEN commands introduce new `code` strings within exit 5.
- S1/S2/S3 baseline behavior (streaming logprobs, provider capability metadata)
is preserved.
## [0.9.3] - 2026-04-29
> Published SDK release `sdk-v0.9.3`. Production licensing real-purchase
> activation/recovery, PR readiness, and supported-platform SDK build checks
> passed before release publication.
### Added
- **Production licensing cutover** (Phase 4):
- Release builds embed the production ES256 public key with
`kid: es256-v1`.
- Release default endpoint is `https://nxus.systems/licensing-api/v1`.
- `nxuskit-cli license status --json` exposes endpoint, environment, and
signing-key diagnostics.
- SDK accepts `real_purchase` and `leased` token kinds even while
`nxus-licensing-client` lags on its enum (ES256 fallback verifier).
- Stable licensing errors include `authentication_required`,
`environment_mismatch`, `wrong_product_identifier`, etc.
- Activation timeouts extended to 30s on both client and proxy
(`EXTENDED_TIMEOUT_SECS = 30`) for cold-start activation paths.
- **First-class unary chat logprobs** (Phase 5, US2):
- **Rust wrapper** (`nxuskit`): `ChatRequest::with_logprobs(bool)` and
`with_top_logprobs(u8)`; typed `ChatResponse.logprobs: LogprobsData`
with `TokenLogprob` (selected token + bytes) and `TopLogprob`
(alternative + bytes). Doctests on `with_logprobs` and `LogprobsData`.
- **Python SDK** (`nxuskit-py`): new `ChatRequest` dataclass with
`logprobs` / `top_logprobs` kwargs; `LogprobsData`, `TokenLogprob`,
`TopLogprob` exported from top-level `nxuskit`. FFI response decode
populates typed logprobs.
- **C ABI**: round-trip preserves `logprobs.content[]`, alternative
tokens, and UTF-8 bytes. Wire path is `logprobs.content[]` (matches
OpenAI; pinned by
`tests/logprobs_abi_passthrough_test.rs::response_envelope_uses_content_field_for_logprobs_token_array`).
- **Engine**: `parameter_adapter.rs::adapt_logprobs` performs warn-and-
drop when a provider lacks `supports_logprobs`, with structured Info
warning. `provider_options` does **not** tunnel logprobs.
- **Migration guide:** The [logprobs migration guide](/nxuskit/migration/logprobs-migration/) covers
Rust + Python + C ABI before/after with capability-gating rationale.
- **ABI / version consistency** (Phase 3):
- Workspace, Rust wrapper, Python package, Go markers, C ABI version
constant, capabilities ABI JSON, current SDK docs, and `Cargo.lock`
all bumped to v0.9.3.
- Pre-logprobs v0.9.2 fixture compatibility tests (Rust + Python) prove
requests without logprobs serialize byte-identically to v0.9.2.
- Stale-version guard: `scripts/check-version-inventory.sh`.
### Changed
- `data-model.md` corrected: logprobs response token array is `content`
(matches Rust/Python/C ABI implementations and OpenAI wire format),
not the earlier draft's `tokens`. Pinned by ABI passthrough test.
### Test counts (logprobs surface, cumulative)
- 7 Rust wrapper (mock_provider) + 6 ABI passthrough + 6 engine
warn-drop + 3 streaming-scope + 18 Python = **40 logprobs tests** green
across all SDK surfaces.
## [0.9.2] - 2026-04-13
### Added
- **CLI Level 2 request surface**: richer JSON request construction across chat/call flows, including multimodal image input handling where supported.
- **Provider diagnostics**: provider ping/status improvements for checking SDK environment readiness from the CLI.
- **Python SDK hardening**: runtime library discovery deprecation warning and SecurityValidator coverage for common unsafe input patterns.
- **Release confidence checks**: conformance, parity, performance, and packaging checks expanded for the supported SDK surfaces.
### Changed
- CLI and runtime-loading documentation refreshed for v0.9.2 behavior.
- Test fixtures and CI checks hardened so SDK builds can validate without relying on local native-library side effects.
- Workspace and lockfile versions bumped to v0.9.2.
## [0.9.1] - 2026-04-05
### CLI Level 1 Semantic Remediation
- **Real Engine Integration**: `zen eval`, `solver solve`, `clips eval`, and `bn infer` now execute real engine logic - no more placeholder/stub responses
- **Pipeline Execution**: `pipeline run` dispatches all stage types (LLM, CLIPS, ZEN, solver, BN) through real engines with output handoff and partial results on failure
- **Call Envelope**: `call` propagates tool definitions and includes `tool_calls` and `inference_metadata` in responses
- **Artifact Deep Merge**: `artifact merge` performs recursive deep merge with dot-notation conflict paths
- **Models Capabilities**: `models --supports` filter uses real capability inference from model metadata
- **Provider Auth**: `provider status` uses structured auth subsystem; `provider logout` is provider-scoped
- **Judge/Branch**: `judge select` returns structured errors; `branch compare` produces field-level diffs
### CLI Documentation and Solver Format Compatibility
- **CLI Input Reference**: New `docs/user/cli-input-reference.md` covering all 13 Level 1 commands with JSON schemas, working examples, and common errors
- **Enhanced Help Text**: Every engine command's `--help` now shows input format structure
- **Solver Format Compatibility**: `solver solve` accepts library API format (ConstraintInput with `var_type`, structured constraints, domains, objectives) directly from shared `problem.json` scenario files - no format conversion needed
- **SMT-LIB Support**: `solver solve` accepts SMT-LIB 2 format (S-expressions) as convenience input for Z3 experts
- **Auto-Detection**: Solver input format (simplified CLI, library API, SMT-LIB) is auto-detected from content
### Positioning
- **CLI Description**: Updated from "CLI for interacting with multiple LLM providers" to "JSON-first control plane for shell automation, CI, and multi-engine reasoning workflows"
- **README**: Added CLI / Shell Automation section with examples
- **Naming**: Fixed `nxuskit-engine-cli` -> `nxuskit-cli` naming drift across all docs and scripts
### Compliance
- **NOTICE**: Regenerated with zen-engine and z3-sys entries; Python section reformatted to remove excessive whitespace padding
- **Constitution v2.4.0**: Added semantic test assertions, stub prohibition, and task verification criteria (Articles II and III)
- **Acceptance Fixtures**: Three PoR 4.1 acceptance workflow scripts (intake-routing, generator-validator-retry, typed-artifact-handoff)
## [0.9.0] - 2026-03-13
Initial public release of the nxusKit SDK.
### Highlights
- **Polyglot SDK**: Unified LLM interfaces across Rust, Go, and Python
- **14 LLM Providers**: Claude, OpenAI, Ollama, LM Studio, Mistral, OpenRouter, Together, Groq, Fireworks, Perplexity, MCP, CLIPS, Mock, Loopback
- **CLIPS Expert System**: Rule-based inference via embedded CLIPS 6.4.2 engine with FFI bindings
- **Bayesian Network Inference**: Full-featured BN provider with Variable Elimination, Junction Tree, Loopy BP, NUTS/HMC, and structure/parameter learning
- **Z3 Constraint Solver**: Stateful solver sessions with multi-objective optimization, soft constraints, push/pop scoping, and UNSAT core extraction
- **ZEN Decision Tables**: JSON Decision Model evaluation via zen-engine
- **Plugin Architecture**: Signed plugin loading with Ed25519 verification and capability-based sandboxing
- **SDK CLI**: Command-line tool for all providers (`nxuskit-cli`)
- **SDK Installer**: Cross-platform SDK manager (`install.sh`) with version management
- **Cross-Language Conformance**: Shared test vectors ensuring API parity across Rust, Go, and Python
### Platform Support
| Platform | Architecture | Status |
|----------|-------------|--------|
| Linux | x86_64 | Supported |
| macOS | ARM64 (Apple Silicon) | Supported |
| macOS | x86_64 | Supported |
| Windows | x86_64 | Supported |
### Language SDKs
| Language | Package | Description |
|----------|---------|-------------|
| Rust | `nxuskit` | FFI wrapper with safe Rust API |
| Go | `nxuskit-go` | Idiomatic Go with context support |
| Python | `nxuskit-py` | Pure Python with `requests` HTTP client |
### Getting Started
See `sdk-packaging/docs/getting-started.md` for installation and usage instructions.
For runnable examples, see the [nxusKit-examples](https://github.com/nxus-SYSTEMS/nxusKit-examples) repository.
## [0.8.23] - 2026-02-24
### Added
- **Solver Progress Streaming (US1)**: Real-time progress events during optimization solves
- `nxuskit_solver_solve_stream` C ABI function with `on_chunk`/`on_done` callbacks
- `SolverProgressEvent` struct: iteration, status, elapsed_ms, objective_value, bound_gap, is_final
- nxuskit-rs `SolverStreamReceiver` with sync Iterator and async `futures_core::Stream` interfaces
- `solve_stream_async()` convenience method for tokio-based async consumption
- **Z3 Context Pooling (US2)**: Reusable Z3 context pool for reduced solver startup overhead
- Pool checkout/return benchmarked at 290us per 100-variable FFI round-trip
- Configurable via `SolverConfig.pool_size` and `pool_max_idle_ms`
- **ZEN Decision Table Evaluation (US3)**: JSON Decision Model (JDM) evaluation via zen-engine
- `nxuskit_zen_evaluate` / `nxuskit_zen_free_result` C ABI functions (stateless, no session)
- Supports decision table nodes, expression nodes, and switch nodes
- Function nodes rejected with clear error (no QuickJS dependency)
- Benchmarked at 0.39ms average for 100-row decision tables (well under 1ms target)
- Go wrapper: `gollyllm.ZenEvaluate()` with automatic memory management
- Rust provider: `zen::evaluate()` async function with pre-compilation optimization
- **BN Min-Weight Variable Elimination (US4)**: Alternative elimination heuristic
- `EliminationHeuristic::MinWeight` option for VE inference
- Identical posteriors to MinFill (verified on Asia and Alarm networks, max diff 2.22e-16)
- Configurable via `{"elimination_heuristic": "min_weight"}` in inference config JSON
- **clips-sys Windows Stub Parity (US5)**: Windows compilation stubs for CLIPS FFI functions
- **7 Code Examples**: Full Rust + Go implementations across patterns and integrations
- **E1 Constraint Solver** (`patterns/constraint-solver`): Basic Z3 solver session with 3 scenarios
- **E2 Bayesian Inference** (`patterns/bayesian-inference`): BN loading, evidence, multi-algorithm inference with 3 scenarios
- **E3 Multi-Provider Pipeline** (`integrations/solver-bn-pipeline`): 3-stage BN→Solver→CLIPS pipeline with 3 scenarios (festival, rescue, bakery)
- **E4 LLM-Solver Hybrid** (`integrations/llm-solver-hybrid`): LLM constraint extraction + Z3 solving with mock/live modes, 3 scenarios (seating, dungeon, road-trip)
- **E5 Solver What-If** (`patterns/solver-what-if`): Push/pop what-if analysis with UNSAT detection, 3 scenarios (wedding, mars, recipe)
- **E6 BN Structure Learning** (`integrations/bn-structure-learning`): Hill-Climb+BIC, K2, MLE parameter learning, log-likelihood scoring with 3 scenarios (golf, bmx, sourdough)
- **E7 ZEN Decision Tables** (`integrations/zen-decisions`): JDM evaluation with first/collect hit policies, expression nodes, 3 scenarios (maze-rat, potion, food-truck)
### Changed
- Go BN FFI (`ffi_bn.go`): Added `SearchStructure()`, `LearnMLE()`, `LogLikelihood()` wrappers with `BnSearchStructureConfig`, `BnStructureResult`, `BnEdge` types
- Go header (`nxuskit.h`): Added `nxuskit_zen_evaluate` and `nxuskit_zen_free_result` declarations
- `log::debug!` instrumentation added to solver streaming and ZEN evaluate hot paths for timing observability
### Performance
- Solver FFI overhead: 290us per 100-variable add_variables call
- Solver first-chunk latency: 21ms (well under 400ms Doherty Threshold)
- ZEN 100-row evaluation: 0.39ms avg, 0.55ms worst-case (under 1ms target)
- Z3 pool bench: >=50% improvement documented (PR-009)
## [0.8.22] - 2026-02-23
### Added
- **Solver Part 2 (044-solver-perf-audit)**: Multi-objective optimization, soft constraints, and explainability
- **Multi-objective optimization**: Weighted sum and lexicographic modes via Z3 Optimize API
- **Soft constraints**: Penalty-weighted constraints that can be violated, with violated constraint tracking
- **Constraint labels & explainability**: Human-readable labels on constraints/variables/objectives, UNSAT core with label mapping, binding constraints and slack values
- **Assumption-based solving**: Push/pop scoping with retractable assumptions
- **Go solver wrapper**: 21 C ABI solver functions wrapped via CGo FFI with full type parity
- **Python solver wrapper**: 21 C ABI solver functions wrapped via CFFI with context managers and dataclass types
- **Performance audit**: Criterion benchmarks for all SDK providers (Z3, CLIPS, Chat, FFI overhead); SC-007 (≤1ms FFI) and SC-008 (≤200ms composite) verified passing
- **Constitution v2.3.0**: PR-007 (cumulative overhead), PR-008 (platform-specific optimization), PR-009 (benchmark platform representativeness)
- **BN Part 2 (043-bn-part2-advanced)**: Advanced inference algorithms and cross-language parity
- **Loopy Belief Propagation**: Message-passing inference for cyclic/large networks with configurable damping and convergence diagnostics
- **Linear Gaussian Bayesian Networks**: Gaussian variable types with moment-matching exact inference and 95% credible intervals
- **NUTS/HMC Sampling**: Gradient-based MCMC via `nuts-rs` crate for continuous variables with ESS/R-hat diagnostics
- **BIF Export**: Round-trip BIF file export with 15-digit precision and CPT completeness validation
- **Parallel Junction Tree**: Rayon-based parallel collect/distribute with deterministic results and auto-fallback
- **Go BN wrapper**: Full C ABI coverage for Part 2 — BnNetwork, BnEvidence, BnResult with goroutine-safe inference and streaming via channels
- **Python BN wrapper**: Full C ABI coverage for Part 2 — context managers, async inference, generator-based streaming
- **C ABI extensions**: 8 new exported functions for Gaussian variables, config-based inference, streaming, and BIF save
### Changed
- **Dependency Audit & Update (043-deps-audit-update)**: Comprehensive dependency updates across Rust, Go, and Python
- **Rust — Breaking upgrades**:
- `thiserror`: 1.0 → 2.0 (unified across workspace, eliminates dual compilation)
- `reqwest`: 0.12 → 0.13 (rustls TLS default, improved security)
- `serde_yaml` → `serde_yaml_ng`: 0.9 → 0.10 (replaces archived/deprecated crate via Cargo rename)
- `rand`: 0.9 → 0.10, `rand_chacha`: 0.9 → 0.10 (trait renames: Rng→RngExt, from_os_rng removed)
- `quick-xml`: 0.37 → 0.39 (drop-in for our usage)
- `rmcp`: 0.8 → 0.16 (not yet used in source — pure Cargo.toml bump)
- `libloading`: 0.8 → 0.9 (in nxuskit-rs, AsFilename trait)
- `infer`: 0.16 → 0.19 (additive changes only)
- `criterion`: 0.5 → 0.8 (dev-only)
- `wiremock`: 0.5 → 0.6 (dev-only, hyper 1.0 migration)
- `mockito`: 1.2 → 1.7 (dev-only, semver-compatible)
- **Rust — Semver-compatible floor bumps**: regex 1.12, uuid 1.21, csv 1.4, cc 1.2, tempfile 3.20, openapiv3 2.2
- **Go**: go-edlib 1.7.0, pflag 1.0.10, plus transitive updates in all examples
- **Python**: cffi ≥2.0.0, pytest ≥9.0.0, pytest-cov ≥7.0.0, ruff ≥0.15.0
- **Toolchain**: Rust MSRV 1.92 → 1.93 (Go 1.26 bump deferred pending CI toolchain update)
## [0.8.21] - 2026-02-21
### Added
- **Bayesian Network Inference Engine (040-bayesian-network-inference)**: Full-featured Bayesian network provider
- **BIF parser**: Reads standard Bayesian Interchange Format network files (Asia, Cancer, Alarm, Survey, Earthquake)
- **4 inference algorithms**: Variable Elimination (exact), Likelihood Weighted Sampling, Gibbs Sampling (MCMC), Junction Tree
- **3 structure learning algorithms**: K2, Hill Climbing (BIC-scored), Bayesian structure learning
- **2 parameter learning algorithms**: Maximum Likelihood Estimation, Bayesian parameter estimation
- **Streaming support**: Real-time probability updates during sampling-based inference
- **C ABI integration**: 14 BN SDK functions with opaque handle pattern for cross-language access
- **nxuskit-rs BN wrapper**: RAII wrapper with dual-dispatch (static-link + dynamic-link)
- **Reference test data**: Python-generated reference marginals for deterministic validation
- **Benchmarks**: Performance benchmarks for all inference algorithms
- **Solver Tier 2 Session API (042-solver-tier2-api)**: Stateful Z3 solver sessions with incremental model building
- **Typed solver domain types** (`solver_types.rs`): `VariableDef`, `ConstraintDef`, `ObjectiveDef`, `SolveResult`, `SolverStats`, `SolverConfig`, `SolverCapabilities`, `SessionStatus`, with 20 constraint type variants and full serde round-trip fidelity
- **Mock solver backend** (`mock_solver.rs`): Deterministic contract testing without Z3 runtime — pre-configured responses, operation recording, atomic response cycling
- **17 C ABI solver session functions** (`solver_sdk.rs`): Opaque handle pattern for cross-language access — create/destroy, add variables/constraints, set objective, retract, push/pop, solve, reset, introspection (variables, constraints, status, capabilities, counts)
- **nxuskit-rs SolverSession wrapper** (`solver.rs`): RAII wrapper with dual-dispatch (static-link + dynamic-link), typed methods, automatic cleanup on drop
- **Internal solver session engine** (`solver_session.rs`): Accumulates state as plain Rust data, rebuilds Z3 solver on each solve via `with_z3_config` closure re-entry
- **Push/pop scoping**: Checkpoint/restore model state for what-if analysis (5 nested levels tested)
- **Unsat core extraction**: Named constraint labels propagated through Z3 assertion tracking, conflict identification on UNSAT
- **Solver configuration**: Timeout, random seed, and max-conflicts controls for deterministic, bounded-resource solving
- **Backend capability introspection**: Query Z3 or mock feature flags (incremental, unsat core, push/pop, multi-objective)
- **New Providers (041-new-providers)**: Local LLM and Z3 constraint solver providers
- **Local LLM provider**: In-process inference via llama.cpp (feature-gated `provider-local-llama`) and mistral.rs (feature-gated `provider-local-mistralrs`)
- **Z3 constraint solver provider**: Constraint satisfaction and optimization via Z3 (feature-gated `provider-z3`)
- **Go FFI constructors**: `NewLocalProvider()` and `NewZ3Provider()` in gollyllm
- **ModelLister implementations**: For Local and Z3 providers
### Changed
- **Tier 1 Z3 refactor**: `Z3Provider::chat()` now delegates to `session::solve_ephemeral()` for shared validation and dispatch logic — no external behavior change
- **Constitution v2.1.0**: Extended lockstep versioning to all nxusKit components (rustyllm, gollyllm, pythicllm), unified under single `sdk-v*` tag line
- **Go toolchain**: Bumped to 1.24.13 for crypto/tls security fix (GO-2026-4337)
- **gollyllm LKS Parity (018-gollyllm-lks-parity)**: Go library now has API parity with rustyllm
- **`InferenceMetadata` and `InferenceStep` types**: Structured metadata for inference results
- `InferenceMetadata` with `IsComplete`, `FinishReason`, `TokenUsage`, `ThinkingTrace`, `InferenceSteps`
- `InferenceStep` for capturing tool calls, thinking traces, and custom steps
- Builder pattern with fluent methods (`Completed()`, `WithTokenUsage()`, `AddInferenceStep()`, etc.)
- `ChatResponse.InferenceMetadata` field populated by all 12 providers
- **`SessionResetter` interface**: Deterministic testing support
- `FreshSession() (LLMProvider, error)` method on all 12 providers
- Stateless providers return self, MockProvider creates new instance
- Enables reproducible test results in CI/CD pipelines
- **`ModelLister` interface**: Dynamic model discovery
- `ListAvailableModels(ctx) ([]ModelInfo, error)` for local providers
- Implemented by: Ollama, LM Studio, Mock, Loopback
- Cloud providers don't implement (API doesn't support dynamic listing)
- **Backward Compatibility**: `ChatResponse.Metadata` field preserved with deprecation notice
- **85.9% Test Coverage**: Exceeds target of ≥85%
### Changed
- **Project Naming Migration**: Unified naming conventions across all language implementations
- Umbrella project renamed from "RustyLLM/LLMKit" to "nxusKit"
- Go library: `go/llmkit-go/` → `gollyllm/`, package `llmkit` → `gollyllm`
- Go module path: `github.com/llmkit/llmkit-go` → `github.com/nxus-SYSTEMS/nxusKit/gollyllm`
- Go CLI: `gollm` → `gollyllm`
- Python library: `rustyllm-py/` → `pythicllm/`, package `rustyllm` → `pythicllm`
- Python tools: `python-tools/` → `nxusKit-tools/`
- Rust library: `rustyllm` (unchanged)
- Updated all documentation, examples, and configuration files
## [0.8.20] - 2026-01-29
### Added
- **`ModelLister` Trait**: New trait for polymorphic model discovery
- Enables `Box` for provider registries
- Implemented for Ollama, LmStudio, CLIPS, Mock, and Loopback providers
- Correct vtable dispatch through trait objects
- **`InferenceMetadata` and `InferenceStep` Types**: Unified response metadata
- `InferenceMetadata` provides consistent access to execution details across all providers
- `InferenceStep` captures inference traces (rule firings for CLIPS, tool calls, etc.)
- All providers now populate `response.inference_metadata`
- **`fresh_session()` Method**: Per-provider method for deterministic CI/testing
- Returns a fresh provider instance with clean state
- Implemented for all 13 providers
- Enables reproducible test results
- **`BlockingProvider
` Wrapper**: Synchronous API for non-async contexts
- Feature-gated under `blocking-api`
- Uses internal tokio Runtime
- Supports `chat()` and `list_models()` (when wrapped provider implements ModelLister)
- **`full` Feature Flag**: Convenience feature combining `clips` + `blocking-api`
- **CLIPS Ordering Guarantees**: Deterministic output ordering
- Conclusions sorted by fact_index
- Rules fired sorted by name for determinism
- Conflict strategy recorded in provider_metadata
- **Documentation**: New integration guides
- `docs/INTEGRATION_PATTERNS.md` - Polymorphic providers, deterministic evaluation, sync API
- `docs/MINIMAL_BUILD.md` - Feature flag reference and build configurations
- **CI Improvements**: Feature flag verification steps
- Tests `--no-default-features`, `--features blocking-api`, `--features full` builds
- **Examples**:
- `polymorphic_example.rs` - Provider registry pattern with ModelLister
- `blocking_example.rs` - Synchronous API usage patterns
- **`as_clips_output()` Method**: Typed accessor for CLIPS results (feature = "clips")
- Avoids manual JSON parsing for CLIPS inference results
- Returns `Option` with typed access to conclusions, traces, stats
- Returns `None` for non-CLIPS response content
- **`all-providers` Feature Flag**: Enables all provider features (`pro` + `mcp`)
- **Documentation Enhancements**:
- Error handling patterns in INTEGRATION_PATTERNS.md
- CLIPS ordering guarantees documentation
- WASM compatibility notes in MINIMAL_BUILD.md
- CI optimization tips for feature matrix testing
### Changed
- `ChatResponse` now includes `inference_metadata: InferenceMetadata` field (backward compatible with `#[serde(default)]`)
## [0.8.19] - 2026-01-28
### Added
- **CLIPS Provider Options**: New configuration options for expert system inference
- `strategy` option for conflict resolution strategy selection
- `allow_duplicate_facts` option for fact assertion behavior control
- **CLI Support for All 14 Providers**: Command-line interface now supports all providers
- Claude, OpenAI, Ollama, LM Studio, Mistral, OpenRouter, Together, Groq, Fireworks, Perplexity, MCP, CLIPS, Mock, Loopback
- **Stop Patterns**: Conditional inference halting based on output patterns
- Enables early termination when specific patterns are detected in responses
- **CLIPS Expert System Enhancements**:
- Binary rule loading support for pre-compiled rule bases
- Search paths for rule file discovery
- Schema conversion utilities for fact/rule translation
- Help commands for CLIPS debugging and introspection
## [0.8.18] - 2026-01-23
### Breaking Changes
- **`ThinkingMode::Auto` behavior changed**: Now intelligently enables thinking for thinking-capable models (qwen3, deepseek-r1, etc.) instead of omitting the parameter. Use `ThinkingMode::Omit` for the old behavior.
### Added
- **`ThinkingMode::Omit` variant**: Explicitly omit the `think` parameter from Ollama requests, letting the model use its raw default behavior. Use this if you need the pre-0.8.18 `Auto` behavior.
- **Smart `Auto` mode for Ollama thinking models**: `ThinkingMode::Auto` now detects thinking-capable models and enables thinking automatically, preventing empty response issues with models like qwen3-vl.
- **Native Ollama Structured Output Support**: Full JSON mode and JSON schema support for Ollama provider
- **JSON Mode**: Use `ResponseFormat::Json` to get structured JSON responses from Ollama models
- **JSON Schema Mode**: Use `ResponseFormat::JsonSchema { schema }` for schema-validated responses (Ollama 0.5.0+)
- Native API integration - sends `format: "json"` or `format: { schema }` directly to Ollama
- No more prompt-based fallback needed for JSON mode with Ollama
- Updated `supports_json_schema: true` in Ollama provider capabilities
- **Helper methods on `ThinkingMode`**:
- `is_auto()` - Check if mode requires smart automatic behavior
- `is_omit()` - Check if mode explicitly omits the thinking parameter
### Fixed
- **Ollama JSON Mode Gap**: Previously, Ollama declared `supports_json_mode: true` but didn't actually send the `format` field to the API. Now properly implemented with native support.
- **Empty responses with qwen3-vl models**: Models like qwen3-vl would return empty content when the `think` parameter was omitted. The new smart `Auto` behavior prevents this by enabling thinking for known thinking models.
## [0.8.17] - 2026-01-20
### Added
- **`ThinkingMode` Enum**: Provider-agnostic control over chain-of-thought reasoning
- `ThinkingMode::Auto` - Use model's default behavior (recommended)
- `ThinkingMode::Enabled` - Force thinking mode on
- `ThinkingMode::Disabled` - Force thinking mode off for faster responses
- New `ChatRequest.with_thinking_mode()` builder method
- Automatically translated to provider-specific parameters (e.g., `think` for Ollama)
- **Ollama `think` Parameter Support**: Direct API integration for thinking control
- Added `think: Option` to internal `OllamaRequest` struct
- Maps from `ChatRequest.thinking_mode` automatically
- **Thinking Model Detection**: Auto-detection with warnings
- `OllamaProvider::is_thinking_model()` detects qwen3*, deepseek-r1/v3, :thinking variants
- Debug warnings when `max_tokens < 200` for thinking models (token budget may be exhausted)
- **StreamChunk Helper Methods**: Easier access to combined content
- `all_content()` - Returns `(Option<&str>, Option<&str>)` tuple of (thinking, content)
- `combined_text(separator)` - Combines thinking + content into single string
### Fixed
- **Empty Response Bug**: Resolved issue where thinking models returned empty responses
- Root cause: `max_tokens` setting too low, causing thinking tokens to exhaust budget
- Solution: Added `ThinkingMode` control and detection warnings
## [0.8.16] - 2026-01-20
### Added
- **Ollama Thinking Mode Support**: Reliable streaming for models with chain-of-thought reasoning (e.g., Qwen3)
- **Bug Fix**: Streaming no longer returns empty responses when using thinking-enabled models
- Previously, Qwen3 models would intermittently return empty responses because thinking chunks were dropped
- Stream now correctly stays active during thinking phase and delivers all content
- **Important**: Thinking tokens count toward `max_tokens` limit - avoid setting low `max_tokens` values with thinking models or you may get empty responses
- New `StreamChunk.thinking` field exposes model reasoning content (when available)
- New helper methods on `StreamChunk`:
- `thinking(String)` - Create a thinking-only chunk
- `with_thinking(String, String)` - Create a chunk with both content and thinking
- `has_thinking()` - Check if chunk contains thinking content
- `has_content()` - Check if chunk has any content (delta or thinking)
- Token counting now includes thinking tokens in completion count
- `StreamingTokenAccumulator` updated with `add_thinking_chunk()` method
- Backward compatible: existing code works unchanged, `thinking` field is `Option`
- Affected models: `qwen3:*`, `qwen3-vl:*`, and any future models using Ollama's thinking field
- See the Ollama provider documentation for usage details
### Fixed
- Custom `Debug` implementation for `TokenEstimator` to avoid derive issues with `tiktoken_rs::CoreBPE`
## [0.8.15] - 2026-01-19
### Added
- **Streaming Token Usage Tracking**: Real-time token consumption monitoring across all 13 LLM providers
- Every streaming chunk now includes token usage information (both actual and estimated)
- Dual accuracy: 100% actual counts from providers + 95-99% estimated counts via client-side tokenization
- New `TokenEstimator` for client-side token counting with tiktoken-rs support (95-99% accuracy)
- New `StreamingTokenAccumulator` for real-time token aggregation during streaming
- New `TokenUsage` structure with dual count support (actual + estimated)
- New `stream_with_usage()` convenience method on `LLMProvider` trait
- Feature-gated `stream-token-estimation` enables high-accuracy token counting (~50KB binary size)
- Provider Support:
- **Tier 1 (100% Actual)**: Claude, OpenAI, Ollama
- **Tier 2 (95-99% Estimated)**: Groq, Mistral, Fireworks, Together, OpenRouter, Perplexity, LM Studio
- **Tier 3 (70-90% Heuristic)**: MCP
- **Tier 4 (100% Test)**: Mock, Loopback providers
- All 13 providers updated with streaming token tracking implementation
- 6 new integration tests covering token tracking across providers
- See: `docs/PROVIDER_TOKEN_ACCURACY.md`
- **Comprehensive Documentation**
- Enhanced README.md with new "Streaming Token Usage Tracking" section
- New PROVIDER_TOKEN_ACCURACY.md with detailed provider breakdown and cost tracking guidance
- Updated quickstart.md with 5 practical examples and migration guide
- New DOCUMENTATION_GUIDE.md for navigation and reader journeys
- 1,110+ lines of documentation, 30+ code examples
### Changed
- TokenUsage structure now includes both actual and estimated counts for dual accuracy
- All streaming chunks now include token usage information (previously only some providers)
- Updated exports in lib.rs to include TokenEstimator and EstimationMethod
### Fixed
- Fixed unit tests to use new TokenUsage structure (estimated_only, best_available methods)
- Addressed clippy warning about unnecessary clone of Copy type in lmstudio.rs
## [0.8.14] - 2025-12-08
### Added
- **Retry-After Header Parsing**: All providers now parse the `Retry-After` header from HTTP 429 responses
- When rate limited, `LlmError::RateLimit { retry_after }` now contains the duration
- Enables intelligent retry logic: clients can wait exactly as long as needed
- Supports delay-seconds format (e.g., "30" for 30 seconds)
- Added `parse_retry_after()` helper function in `providers/mod.rs`
- All 9 providers updated: Claude, OpenAI, Ollama, Groq, Together, Fireworks, Mistral, Perplexity, OpenRouter
- Implements Retry-After header parsing per HTTP/1.1 specification
## [0.8.13] - 2025-12-08
### Fixed
- **Critical Bug Fix**: Streaming requests now use `total_timeout` instead of `connection_timeout`
- The `chat_stream()` methods were incorrectly using `.timeout(self.connection_timeout)` on the request builder
- This overrode the client's `total_timeout` (default 600s) with `connection_timeout` (default 10s)
- Caused streaming to fail after ~10 seconds even with longer timeout configurations
- Affects: `ClaudeProvider`, `OpenAIProvider`, `OllamaProvider`
- Added regression tests to prevent this issue from recurring
- **All providers now use centralized `build_http_client()` helper**
- Previously, only Claude, OpenAI, and Ollama used the helper
- Now all providers use consistent timeout configuration with `read_timeout` for streaming
- Fixed providers: `FireworksProvider`, `GroqProvider`, `PerplexityProvider`, `TogetherProvider`, `LmStudioProvider`, `MistralProvider`, `OpenRouterProvider`
- `MistralProvider` and `OpenRouterProvider` were using `Client::new()` which ignored ALL timeouts
- Other providers were missing `read_timeout` which is critical for streaming
## [0.8.12] - 2025-12-08
### Fixed
- **Critical Bug Fix**: Timeout configurations are now properly applied to HTTP clients
- Previously, `connection_timeout`, `stream_read_timeout`, and `total_timeout` values were stored but never applied to the underlying `reqwest::Client`
- This caused requests to use reqwest's default timeouts instead of user-configured values
- Streaming requests would fail prematurely (~10s) regardless of timeout configuration
- Affects: `ClaudeProvider`, `OpenAIProvider`, `OllamaProvider`
- Root cause: timeout was set on the request builder instead of the HTTP client builder
### Added
- **`build_http_client()` helper function**: Centralized HTTP client creation with proper timeout application
- Ensures all providers use consistent timeout configuration
- Prevents this class of bug in future provider implementations
- See: `docs/PROVIDER_IMPLEMENTATION.md`
- **Timeout configuration regression tests**: Comprehensive test suite to catch timeout misconfigurations
- Tests for all three timeout types across all providers
- `verify_provider_respects_timeout()` helper for testing new providers
- Behavioral tests with mock servers and configurable delays
### Changed
- **Upgraded `reqwest` from 0.11 to 0.12**: Enables `read_timeout` support for streaming responses
- `read_timeout` applies per-chunk during response body reading
- Critical for LLM streaming where there are pauses between tokens
## [0.8.11] - 2025-12-07
### Added
- **Loopback Provider**: Test/development provider that echoes back user messages
- Useful for testing without API calls
- Configurable response delays for timeout testing
## [0.8.10] - 2025-11-25
### Breaking Changes
- **LLMProvider Trait**: Added `get_capabilities()` method to the trait
- All custom provider implementations must now implement this method
- Returns `ProviderCapabilities` struct describing what the provider supports
- **ChatResponse**: Added new fields
- `warnings: Vec` - Parameter adaptation warnings
- `logprobs: Option` - Token probability data (when requested)
### Added
- **New Parameters in ChatRequest**:
- `stop: Option>` - Stop sequences for generation
- `presence_penalty: Option` - Repetition penalty (-2.0 to 2.0)
- `frequency_penalty: Option` - Frequency penalty (-2.0 to 2.0)
- `seed: Option` - Deterministic generation seed
- `logprobs: Option` - Enable token probabilities
- `top_logprobs: Option` - Number of top alternatives (0-20)
- `response_format: Option` - JSON mode control
- `provider_options: Option` - Provider-specific parameters
- **Parameter Adapter**: Graceful degradation system
- Automatically adapts parameters to provider capabilities
- Truncates stop sequences to provider limits with warnings
- Ignores unsupported parameters with info-level warnings
- Falls back to prompt-based JSON mode when native not supported
- **Provider Capabilities System**:
- `ProviderCapabilities` struct for querying provider support
- Runtime capability detection for all parameters
- Enables write-once code that adapts to any provider
- **New Providers** (6 total):
- `MistralProvider` - Mistral AI API
- `OpenRouterProvider` - OpenRouter unified API (100+ models)
- `TogetherProvider` - Together AI (open source models)
- `GroqProvider` - Groq (ultra-fast inference)
- `FireworksProvider` - Fireworks AI (optimized inference)
- `PerplexityProvider` - Perplexity AI (search-augmented)
- **MCP Auto-Discovery**:
- Automatic server discovery from `~/.config/mcp/servers.json`
- `RUSTYLLM_MCP_CONFIG` environment variable override
- `McpProvider::discover_servers()` API
- `McpProvider::builder().discover_server("name")` pattern
- **Supporting Types**:
- `ResponseFormat` enum (Text, Json, JsonSchema)
- `ProviderOptions` enum with `OllamaOptions` variant
- `ParameterWarning` and `WarningSeverity` for warnings
- `LogprobsData`, `TokenLogprob`, `TopLogprob` for token probabilities
### Changed
- All existing providers updated to implement `get_capabilities()`
- All providers now integrate with ParameterAdapter for graceful degradation
- MockProvider enhanced with full capability support for testing
### Fixed
- Test race conditions in env_detector and MCP tests (mutex serialization)
- Test assertions for provider metadata flexibility
## [0.8.9] - 2025-11-25
### Changed
- Updated plans for new versioning with open source beta target (pre-v1.x.x)
- Cleanup and tightened various compiler warnings
## [0.8.8] - 2025-11-25
### Changed
- Version bump for release preparation
## [0.8.7] - 2025-11-25
### Changed
- Release preparation updates
## [0.8.6] - 2025-11-25
### Changed
- Minor fixes and updates
## [0.8.5] - 2025-11-25
### Changed
- Release updates
## [0.8.4] - 2025-11-24
### Changed
- Post-reset stabilization
## [0.8.3] - 2025-11-24
### Added
- Initial Tier-1 provider implementations (Mistral, OpenRouter, Together, Groq, Fireworks, Perplexity)
- MCP auto-discovery groundwork
## [0.8.2] - 2025-11-24
### Added
- LiteLLM-style convenience API with automatic provider detection
- Graceful parameter degradation foundation
## [0.8.1] - 2025-11-24
### Added
- Provider expansion preparation
- API refinements
## [0.8.0] - 2025-11-24
### Changed
- **Version Reset**: Reset version numbering from the earlier 2.x line into the pre-public development line
- Pre-1.0 versioning (0.x.y) signals API is not yet stable per semantic versioning
- Allows breaking changes in minor versions during development
- Functionality from the earlier 2.x line carried forward unchanged
- Historical 2.x changelog preserved in the internal archive
- Previous 2.x release artifacts archived outside the public SDK release line
### Notes
This was a version numbering reset only - no code functionality changed. Features, fixes, and improvements from the earlier 2.x line carried forward into the pre-public development line. The reset better reflected the library's development stage and followed Rust ecosystem conventions for pre-release crates.
The older 2.x history is intentionally kept out of the public SDK changelog.
---
# CLI Input Format Reference
URL: https://docs.nxus.systems/nxuskit/reference/cli-reference
Single source of truth for every Level 1 `nxuskit-cli` command's input schema,
with local loopback examples where the command can succeed without a semantic
LLM response.
All commands accept `--input -` for stdin and `--format json` (default).
Output is wrapped in a `ResponseEnvelope` with `trace_id`, `request_metadata`,
and timing fields.
Loopback examples that are intended to execute locally use explicit loopback
model names. In nxusKit CLI v1.0.x, do not rely on an omitted model resolving
to `"default"` for the `loopback` provider; use `"echo"` for plain echo tests
or `"echo-json-native"` when you need a loopback model that advertises native
JSON support. Commands that require a semantic structured answer, such as
`judge select`, should use a configured non-loopback LLM provider because
loopback models echo the prompt.
For Pro `solver` and `zen` command execution, install the v1.0.1 or newer Pro
SDK bundle. v1.0.1 makes no API or C ABI signature changes from v1.0.0; it
fixes Pro CLI package composition so Pro archives include the real Solver/ZEN
engine command modules instead of CE-safe stubs. Pro engine commands still
require a valid Pro entitlement at runtime.
---
## Table of Contents
- [call](#call)
- [zen eval](#zen-eval)
- [zen validate](#zen-validate)
- [zen test](#zen-test)
- [solver solve](#solver-solve)
- [Solver Format Disambiguation](#solver-format-disambiguation)
- [solver what-if](#solver-what-if)
- [clips eval](#clips-eval)
- [clips session](#clips-session)
- [clips session create](#clips-session-create)
- [clips session list](#clips-session-list)
- [clips session destroy](#clips-session-destroy)
- [provider list](#provider-list)
- [provider info](#provider-info)
- [bn infer](#bn-infer)
- [bn learn](#bn-learn)
- [bn evidence](#bn-evidence)
- [pipeline run](#pipeline-run)
- [artifact merge](#artifact-merge)
- [artifact summarize](#artifact-summarize)
- [packet validate](#packet-validate)
- [tool-loop run](#tool-loop-run)
- [judge select](#judge-select)
- [branch fork](#branch-fork)
- [branch compare](#branch-compare)
- [Error responses](#error-responses)
---
### `call`
LLM invocation. Accepts either `prompt` (single-turn) or `messages` (multi-turn).
**Input schema (`CallInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `prompt` | string | no | Single-turn user prompt (convenience shorthand) |
| `messages` | array of `{role, content}` | no | Multi-turn conversation messages |
| `system` | string | no | System message prepended to the conversation |
| `provider` | string | no | Provider name (default: `loopback`, or `$NXUSKIT_PROVIDER`) |
| `model` | string | no | Model identifier. For `loopback`, use a valid loopback model such as `"echo"` or `"echo-json-native"`; do not rely on the implicit `"default"` model in v1.0.x. |
| `tool_definitions` | array of JSON objects | no | Tool/function schemas passed to the LLM |
| `tool_choice` | JSON value | no | Provider-compatible tool choice policy passed with `tool_definitions` |
| `response_format` | object | no | Response format constraint: `{"type":"text"}`, `{"type":"json_object"}`, or `{"type":"json_schema","schema":{...}}` |
| `thinking_mode` | string | no | Thinking policy: `auto`, `enabled`, `disabled`, or `omit` |
| `max_tokens` | u32 | no | Maximum output tokens |
| `temperature` | f32 | no | Sampling temperature |
| `stream` | bool | no | Enable streaming (JSONL output) |
At least one of `prompt` or `messages` should be provided.
**Example:**
```bash
echo '{"prompt": "Hello", "provider": "loopback", "model": "echo"}' \
| nxuskit-cli call --input - --format json
```
**Common errors:**
- `Invalid call input JSON: missing field ...` -- Fix: ensure the input is valid JSON with at least `prompt` or `messages`.
- `Unknown provider "xyz"` -- Fix: use a valid provider name (`loopback`, `openai`, `claude`, etc.) or set `$NXUSKIT_PROVIDER`.
---
### `zen eval`
ZEN decision table evaluation (Pro-gated).
**Input schema (`ZenEvalInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `table` | JSON object | **yes** | JDM (JSON Decision Model) decision table definition |
| `input` | JSON object | **yes** | Context data evaluated against the table |
The `table` field must be a valid JDM model with `nodes` and `edges` arrays.
Decision table nodes have `type: "decisionTableNode"` and contain `rules` in
their `content`.
**Example:**
```bash
echo '{
"table": {
"nodes": [
{
"id": "1",
"name": "input",
"type": "inputNode",
"content": {}
},
{
"id": "2",
"name": "decision",
"type": "decisionTableNode",
"content": {
"hitPolicy": "first",
"rules": [
{"_id": "r1", "input.age": ">= 18", "output.status": "adult"}
],
"inputs": [{"id": "i1", "name": "age", "field": "input.age"}],
"outputs": [{"id": "o1", "name": "status", "field": "output.status"}]
}
},
{
"id": "3",
"name": "output",
"type": "outputNode",
"content": {}
}
],
"edges": [
{"id": "e1", "sourceId": "1", "targetId": "2", "type": "edge"},
{"id": "e2", "sourceId": "2", "targetId": "3", "type": "edge"}
]
},
"input": {"age": 25}
}' | nxuskit-cli zen eval --input - --format json
```
**Common errors:**
- `Entitlement check failed: zen` -- Fix: ZEN is Pro-gated. Ensure a valid Pro license is active.
- `Invalid ZEN eval input: missing field "table"` -- Fix: both `table` and `input` are required fields.
---
### `zen validate`
Structural validation of a ZEN JSON Decision Model (JDM) - no evaluation
(Pro-gated, Level 2 utility). Checks that the model parses into the JDM
structure, rejects `functionNode`s (JavaScript not supported), checks decision
table node shape, attempts to compile expressions, and counts nodes / decision
tables / rules.
The `--input` content is the **JDM model itself** - NOT the `{table, input}`
envelope that `zen eval` accepts.
| Field (input) | Type | Required | Description |
|---|---|---|---|
| (whole document) | JSON object | **yes** | A JDM model with `nodes` (and usually `edges`) arrays |
**Success output (`--format json`):**
```json
{
"result": {
"valid": true,
"node_count": 3,
"decision_table_count": 1,
"rule_count": 4,
"problems": [],
"elapsed_ms": 1.2
},
"trace_id": "...", "timestamp": "...", "request_metadata": { "...": "..." }
}
```
**Failure (structurally invalid JDM)** - exit 5, stderr `ErrorEnvelope`:
```json
{
"code": "zen_validate_error",
"message": "JDM is structurally invalid: 1 problem(s) found",
"details": { "problems": [
{ "kind": "FunctionNodeRejected", "path": "nodes[1] (id=fn1)", "message": "JDM contains a Function node (JavaScript); not supported ..." }
] },
"trace_id": "...", "timestamp": "..."
}
```
`problems[].kind` is one of: `ParseError`, `FunctionNodeRejected`,
`MalformedNode`, `ExpressionError`, `MissingField`.
**Example:**
```bash
echo '{
"contentType": "application/vnd.gorules.decision",
"nodes": [
{"id":"input","type":"inputNode","name":"In","position":{"x":0,"y":0}},
{"id":"dt","type":"decisionTableNode","name":"T","content":{
"hitPolicy":"first",
"rules":[{"_id":"r1","age":">= 21","tier":"\"A\""},{"_id":"r2","age":"","tier":"\"B\""}],
"inputs":[{"id":"age","name":"Age","field":"age"}],
"outputs":[{"id":"tier","name":"Tier","field":"tier"}]
},"position":{"x":200,"y":0}},
{"id":"output","type":"outputNode","name":"Out","position":{"x":400,"y":0}}
],
"edges":[
{"id":"e1","sourceId":"input","targetId":"dt","type":"edge"},
{"id":"e2","sourceId":"dt","targetId":"output","type":"edge"}
]
}' | nxuskit-cli zen validate --input - --format json
```
**Exit codes:** 0 = structurally valid; 4 = `entitlement_denied` (no Pro); 5 =
unparseable input (`parse_error`) or structurally invalid JDM (`zen_validate_error`);
1 = unexpected internal error. No new exit codes beyond the stable scheme.
---
### `zen test`
Run a ZEN decision table against a set of fixture cases and compare each actual
output to its `expected` (Pro-gated, Level 2 utility). On mismatch, emits a
diff-style report - never an opaque internal error.
**Input envelope:**
| Field | Type | Required | Description |
|---|---|---|---|
| `table` | JSON object | **yes** | JDM model (same shape `zen eval`'s `table` accepts) |
| `cases` | array | **yes** | List of `{name, input, expected}` cases |
| `cases[].name` | string | **yes** | Case identifier |
| `cases[].input` | JSON object | **yes** | Context data for this case |
| `cases[].expected` | JSON value | **yes** | Expected evaluation output (deep equality) |
**Success output (`--format json`):**
```json
{
"result": {
"total": 2, "passed": 2, "failed": 0,
"cases": [
{"name":"low_risk","passed":true,"expected":{"tier":"A"},"actual":{"tier":"A"}},
{"name":"high_risk","passed":true,"expected":{"tier":"C"},"actual":{"tier":"C"}}
],
"elapsed_ms": 3.4
},
"trace_id": "...", "timestamp": "...", "request_metadata": { "...": "..." }
}
```
**Failure (one or more mismatches)** - exit 5, stderr `ErrorEnvelope`:
```json
{
"code": "zen_test_mismatch",
"message": "1 of 2 case(s) did not match expected output",
"details": { "failed": [
{"name":"high_risk","expected":{"tier":"C"},"actual":{"tier":"B"},"diff":{"tier":{"expected":"C","actual":"B"}}}
] },
"trace_id": "...", "timestamp": "..."
}
```
A *fixture parse error* is `code = "parse_error"` (exit 5); an *evaluation
error on a case* (e.g. the table itself is malformed) is `code = "zen_test_eval_error"`
(exit 5) with the offending case named in `details.case` - both distinct from a
mismatch (`zen_test_mismatch`).
**Example:**
```bash
echo '{
"table": { "...": "JDM model" },
"cases": [
{"name":"prime","input":{"age":30,"score":800},"expected":{"tier":"A"}},
{"name":"young","input":{"age":19,"score":400},"expected":{"tier":"C"}}
]
}' | nxuskit-cli zen test --input - --format json
```
**Exit codes:** 0 = all cases match; 4 = `entitlement_denied`; 5 = parse error
(`parse_error`), per-case eval error (`zen_test_eval_error`), or one+ mismatches
(`zen_test_mismatch`); 1 = unexpected internal error.
---
### `solver solve`
Z3 constraint solving (Pro-gated). Auto-detects three input formats.
#### Solver Format Disambiguation
The CLI accepts three distinct input formats, auto-detected at parse time:
| Format | Detection Rule | Best For |
|--------|---------------|----------|
| **Simplified** | JSON with `"type"` on variables and string constraints | Quick CLI one-liners, human-authored problems |
| **Library API** | JSON with `"var_type"` on variables or `"constraint_type"` on constraints | Cross-language scenario sharing with nxuskit-go/nxuskit-py |
| **SMT-LIB 2** | Input starts with `(` | Direct Z3 interaction, academic benchmarks |
The **library API format** uses the same `ConstraintInput` struct as the Rust, Go,
and Python SDKs. This means a JSON file authored for `solver solve` can be loaded
directly by `nxuskit.solve()` in any SDK, enabling cross-language scenario sharing.
---
#### Format 1: Simplified
**Input schema (`SolverInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `variables` | array of `SolverVariable` | **yes** | Variable declarations |
| `constraints` | array of strings | **yes** | Constraint expressions (e.g. `"x + y == 10"`) |
| `objective` | string | no | `"minimize"` or `"maximize"` |
| `objective_expr` | string | no | Expression to optimize (requires `objective`) |
**`SolverVariable` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Variable identifier |
| `type` | string | **yes** | `"integer"`, `"real"`, or `"boolean"` |
| `bounds` | array of `{"min": n}` / `{"max": n}` | no | Domain bounds |
Supported constraint operators: `==`, `!=`, `>=`, `<=`, `>`, `<`.
Arithmetic in LHS: `x + y == 10`, `x - y == 5`, `x * y == 12`.
**Example (simplified):**
```bash
echo '{
"variables": [
{"name": "x", "type": "integer", "bounds": [{"min": 0}, {"max": 10}]},
{"name": "y", "type": "integer", "bounds": [{"min": 0}, {"max": 10}]}
],
"constraints": ["x + y == 10", "x >= 3"],
"objective": "maximize",
"objective_expr": "x"
}' | nxuskit-cli solver solve --input - --format json
```
---
#### Format 2: Library API (`ConstraintInput`)
**Input schema (`ConstraintInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `variables` | array of `VariableDef` | no | Variable declarations |
| `constraints` | array of `ConstraintDef` | no | Structured constraint definitions |
| `objective` | `ObjectiveDef` | no | Single optimization objective |
| `objectives` | array of `ObjectiveDef` | no | Multiple objectives (multi-objective mode) |
| `config` | `SolverConfig` | no | Per-request solver configuration overrides |
| `retract` | array of strings | no | Named constraints to remove |
| `assumptions` | array of `ConstraintDef` | no | Temporary constraints (auto-retracted after solve) |
**`VariableDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Variable identifier |
| `var_type` | string | **yes** | `"integer"`, `"real"`, or `"boolean"` |
| `domain` | `{"min": f64, "max": f64}` or `[min, max]` | no | Domain bounds |
| `label` | string | no | Human-readable description |
**`ConstraintDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | no | Identifier for retraction / unsat core |
| `constraint_type` | string | **yes** | `"eq"`, `"neq"`, `"lt"`, `"gt"`, `"le"`, `"ge"`, `"add"`, `"sub"`, `"mul"`, `"div"`, `"and"`, `"or"`, `"not"`, `"implies"`, `"iff"`, `"all_different"`, `"at_most"`, `"at_least"`, `"exactly"`, `"in_range"` |
| `params` / `parameters` | JSON object | no | Type-specific parameters (e.g. `{"left": "x", "right": 3}`). Both field names accepted. If omitted, auto-inferred from `variables` and `expression` fields (see below). |
| `variables` | string[] | no | Variable names involved in the constraint. Used to auto-infer `params` when omitted. |
| `expression` | string | no | Human-readable expression (e.g. `"a * 20 = c"`). Used to auto-infer `params` when omitted. |
| `weight` | f64 | no | Soft constraint penalty (omit for hard constraint) |
| `label` | string | no | Human-readable description |
**`ObjectiveDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Unique objective identifier |
| `direction` | string | **yes** | `"minimize"` or `"maximize"` |
| `expression` | string | **yes** | Expression to optimize (references variable names) |
| `weight` | f64 | no | Weight for weighted multi-objective mode |
| `label` | string | no | Human-readable description |
| `priority` | u32 | no | Priority for lexicographic mode (lower = higher priority) |
**Params auto-inference**: When `params`/`parameters` is omitted or null, the CLI infers it from the `variables` and `expression` fields — matching the behavior of the Rust SDK's `ensure_parameters()` helper. This means shared `problem.json` scenario files work directly without modification:
- Comparison constraints (`ge`, `le`, `eq`, etc.) with `variables: ["a", "b"]` → infers `params: {"left": "a", "right": "b"}`
- Arithmetic constraints (`add`, `mul`, etc.) with `variables: ["a", "b", "c"]` and `expression: "a * 20 = c"` → infers `params: {"left": "a", "right": 20, "result": "c"}`
- Set constraints (`all_different`, `at_most`, `at_least`, `exactly`) with `variables: ["x", "y", "z"]` → infers `params: {"variables": ["x", "y", "z"]}`
- Partial params (e.g., `{"right": 19000}` with `variables: ["salary"]`) → merges to `{"left": "salary", "right": 19000}`
**Type aliases**: The CLI accepts `equal` (→ `eq`) and `not_equal` (→ `neq`) as long-form constraint type names for compatibility with some scenario files.
**Example (library API):**
```bash
echo '{
"variables": [
{"name": "x", "var_type": "integer", "domain": {"min": 0, "max": 10}},
{"name": "y", "var_type": "integer", "domain": {"min": 0, "max": 10}}
],
"constraints": [
{"name": "sum", "constraint_type": "add", "params": {"left": "x", "right": "y", "result": 10}},
{"name": "lower_bound", "constraint_type": "ge", "params": {"left": "x", "right": 3}}
],
"objective": {
"name": "max_x",
"direction": "maximize",
"expression": "x"
}
}' | nxuskit-cli solver solve --input - --format json
```
---
#### Format 3: SMT-LIB 2
Raw SMT-LIB 2 text. Auto-detected when input starts with `(`.
**Example (SMT-LIB):**
```bash
echo '(declare-const x Int)
(declare-const y Int)
(assert (>= x 0))
(assert (<= x 10))
(assert (>= y 0))
(assert (<= y 10))
(assert (= (+ x y) 10))
(assert (>= x 3))
(check-sat)
(get-model)' | nxuskit-cli solver solve --input - --format json
```
**Common errors (all formats):**
- `Entitlement check failed: solver` -- Fix: solver is Pro-gated. Ensure a valid Pro license.
- `Cannot parse constraint expression: 'x + y = 10'` -- Fix: use `==` for equality, not `=`.
- `Invalid solver input JSON: ...` -- Fix: ensure JSON is well-formed. Check that simplified format uses `"type"` (not `"var_type"`).
- `Invalid solver library format: ...` -- Fix: library format requires `"var_type"` on variables and `"constraint_type"` on constraints.
---
### `clips eval`
CLIPS rule engine evaluation.
**Input schema (`ClipsEvalInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `rules` | string | **yes** | CLIPS rule definitions (defrule, deftemplate, etc.) |
| `facts` | array of strings | no | Initial facts to assert (default: `[]`) |
> **Newline escaping:** CLIPS rules contain newlines. In JSON strings you must
> use `\n` for line breaks. When piping from a shell, use `$'...'` quoting or
> a heredoc to embed literal newlines, then let `jq` handle escaping.
**Example:**
```bash
echo '{
"rules": "(defrule greet (person (name ?n)) => (assert (greeting (message (str-cat \"Hello \" ?n)))))",
"facts": ["(person (name \"World\"))"]
}' | nxuskit-cli clips eval --input - --format json
```
**Multi-line rules (using jq for safe escaping):**
```bash
RULES=$(cat <<'CLIPS'
(deftemplate person (slot name))
(deftemplate greeting (slot message))
(defrule greet
(person (name ?n))
=>
(assert (greeting (message (str-cat "Hello " ?n)))))
CLIPS
)
jq -n --arg rules "$RULES" '{"rules": $rules, "facts": ["(person (name \"World\"))"]}' \
| nxuskit-cli clips eval --input - --format json
```
**Common errors:**
- `Failed to load CLIPS rules: ...` -- Fix: check CLIPS syntax. Common issues: unbalanced parentheses, missing `=>` in defrule.
- `Failed to assert fact '(foo)': ...` -- Fix: if using deftemplates, facts must match the template signature (e.g. `(person (name "x"))` not `(person "x")`).
- `Invalid CLIPS eval input: missing field "rules"` -- Fix: `rules` is required. Use `"rules": ""` for an empty ruleset.
---
### `bn infer`
Bayesian network inference via variable elimination.
**Input schema (`BnInferInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `network` | `NetworkDef` | **yes** | Bayesian network structure and CPDs |
| `evidence` | map of string to string | no | Observed variable states (default: `{}`) |
| `query_nodes` | array of strings | **yes** | Variables to compute posterior probabilities for |
| `algorithm` | string | no | Inference algorithm (default: `"variable_elimination"`) |
**`NetworkDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `nodes` | array of `NodeDef` | **yes** | Variable definitions with states |
| `edges` | array of `EdgeDef` | **yes** | Directed edges (parent to child) |
| `cpds` | map of string to `CpdDef` | **yes** | Conditional probability distributions |
**`NodeDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Variable name |
| `states` | array of strings | **yes** | Possible states for this variable |
**`EdgeDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `from` | string | **yes** | Parent node name |
| `to` | string | **yes** | Child node name |
**`CpdDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `probabilities` | array of f64 | **yes** | Flat probability table (row-major order over parent states) |
**Example:**
```bash
echo '{
"network": {
"nodes": [
{"name": "Rain", "states": ["yes", "no"]},
{"name": "Sprinkler", "states": ["on", "off"]},
{"name": "GrassWet", "states": ["wet", "dry"]}
],
"edges": [
{"from": "Rain", "to": "GrassWet"},
{"from": "Sprinkler", "to": "GrassWet"}
],
"cpds": {
"Rain": {"probabilities": [0.2, 0.8]},
"Sprinkler": {"probabilities": [0.4, 0.6]},
"GrassWet": {"probabilities": [0.99, 0.01, 0.9, 0.1, 0.8, 0.2, 0.0, 1.0]}
}
},
"evidence": {"GrassWet": "wet"},
"query_nodes": ["Rain"]
}' | nxuskit-cli bn infer --input - --format json
```
**Common errors:**
- `Invalid variable name '...': ...` -- Fix: node names must be non-empty alphanumeric identifiers.
- `Failed to set CPD for '...': ...` -- Fix: probability array length must equal the product of the node's state count and all parent nodes' state counts.
- `Invalid BN inference input: missing field "network"` -- Fix: `network` and `query_nodes` are both required.
---
### `bn learn`
Parameter learning: estimate the conditional probability tables (CPDs) of a
network from a CSV dataset, given the network *skeleton* (variables + edges, no
CPDs). The learned network is BIF-exportable. Community edition.
**Input schema (`BnLearnInput`):**
| Field | Type | Required | Description |
|---|---|---|---|
| `network` | object | **yes** | Network skeleton: `{"nodes": [{"name","states"}], "edges": [{"from","to"}]}` -- NO `cpds` |
| `data_file` | string | **yes** | Path to the CSV dataset; column headers must map to variable names |
| `learner` | string | no (default `"mle"`) | `"mle"` (Maximum Likelihood + Laplace smoothing) or `"bayesian"` (Dirichlet prior) |
| `pseudocount` | number | no (default `1.0`) | Laplace pseudocount; for `bayesian`, the default Dirichlet alpha |
**Output (`--format json`):** `{"result": {"learned_cpts": {var: [probs]}, "bif": "", "num_rows": N, "num_variables": M, "learner": "mle", "elapsed_ms": ...}}`.
**Example:**
```bash
echo '{
"network": {
"nodes": [
{"name":"Rain","states":["yes","no"]},
{"name":"Sprinkler","states":["on","off"]},
{"name":"WetGrass","states":["yes","no"]}
],
"edges": [{"from":"Rain","to":"WetGrass"},{"from":"Sprinkler","to":"WetGrass"}]
},
"data_file": "/abs/path/to/training.csv",
"learner": "mle",
"pseudocount": 0.0
}' | nxuskit-cli bn learn --input - --format json
```
**Common errors:**
- `Training CSV not found: ...` -- Fix: `data_file` must be a path to an existing CSV file.
- `Failed to load dataset '...': ...` -- Fix: CSV column headers must match the network's variable names; cell values must match declared states (empty / `?` cells are treated as missing).
- `Unknown learner '...'. Valid: mle, bayesian` -- Fix: use one of the two supported learners.
**Excluded from v1.0.x:** structure *search* (`hill_climb` / `k2`) is engine-only, not a CLI surface; streaming; team-runtime lineage.
---
### `bn evidence`
Validate and normalize an observations map against a fully-specified network
(same `network` shape as `bn infer`). Returns the validated observations or a
structured validation error naming the offending variable/state. Community edition.
**Input schema (`BnEvidenceInput`):**
| Field | Type | Required | Description |
|---|---|---|---|
| `network` | object | **yes** | `{"nodes": [...], "edges": [...], "cpds": {...}}` (same as `bn infer`) |
| `observations` | object | no | `{var: state, ...}` -- each is validated against the network |
**Output (`--format json`):** `{"result": {"valid": true, "evidence": {var: state}, "observation_count": N, "elapsed_ms": ...}}`.
**Example:**
```bash
echo '{
"network": {
"nodes": [{"name":"Rain","states":["yes","no"]},{"name":"WetGrass","states":["yes","no"]}],
"edges": [{"from":"Rain","to":"WetGrass"}],
"cpds": {"Rain":{"probabilities":[0.2,0.8]},"WetGrass":{"probabilities":[0.9,0.1,0.1,0.9]}}
},
"observations": {"Rain":"yes"}
}' | nxuskit-cli bn evidence --input - --format json
```
**Common errors:**
- `Invalid observation Rain=maybe: ...` (exit 5, `validation`) -- Fix: the observed state must be one of the variable's declared states.
- `Invalid observation variable '...': ...` -- Fix: the variable must exist in the network.
---
### `pipeline run`
Sequential multi-stage pipeline execution. Accepts YAML or JSON.
**Input schema (`PipelineDefinition`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Pipeline name |
| `stages` | array of `Stage` | **yes** | Ordered list of stages to execute |
**`Stage` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Stage identifier |
| `type` | string | **yes** | Stage type: `"llm"`, `"clips_eval"`, `"zen_eval"`, `"solver_solve"`, `"bn_infer"` |
| `config` | JSON object | no | Stage-specific configuration (passed to the engine) |
| `output_key` | string | no | Bind stage output to a named key for `{{key}}` interpolation in later stages |
For `llm` stages, `config` accepts `prompt`, `provider`, and `model`.
For `clips_eval` stages, `config` accepts `rules` and `facts`.
For other stage types, `config` mirrors the respective command's input schema.
Stages execute sequentially. Each stage receives the previous stage's output.
String values in `config` support `{{key}}` interpolation from `output_key` bindings.
If a stage fails, all subsequent stages are marked `"skipped"`.
**Example:**
```bash
echo '{
"name": "demo-pipeline",
"stages": [
{
"name": "generate",
"type": "llm",
"config": {"prompt": "Say hello", "provider": "loopback", "model": "echo"},
"output_key": "llm_result"
},
{
"name": "evaluate",
"type": "llm",
"config": {"prompt": "Summarize: {{llm_result}}", "provider": "loopback", "model": "echo"}
}
]
}' | nxuskit-cli pipeline run --input - --format json
```
**Common errors:**
- `Invalid pipeline definition: ...` -- Fix: ensure input is valid YAML or JSON with `name` and `stages` fields.
- `Unknown stage type: xyz` -- Fix: valid stage types are `llm`, `clips_eval`, `zen_eval`, `solver_solve`, `bn_infer`.
- `PipelineStageFailed { stage: "...", detail: ... }` -- Fix: check the `stages[].result.message` field in the output for the root cause.
---
### `artifact merge`
Deep-merge multiple JSON artifact files with conflict detection.
This command takes multiple `--input` flags (not stdin JSON). Each input must be a
JSON object (not an array or scalar).
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--input` | string (repeatable) | **yes** (>= 2) | Paths to JSON files to merge |
| `--merge-strategy` | string | no | Conflict resolution: `"error"` (default), `"first"`, `"last"` |
No JSON input schema -- inputs are arbitrary JSON objects read from files.
**Example:**
```bash
echo '{"a": 1, "b": {"x": 10}}' > /tmp/art1.json
echo '{"b": {"y": 20}, "c": 3}' > /tmp/art2.json
nxuskit-cli artifact merge \
--input /tmp/art1.json --input /tmp/art2.json \
--format json
```
**Common errors:**
- `artifact merge requires at least 2 input files` -- Fix: provide at least two `--input` paths.
- `MergeConflict { paths: ["b.x"] }` -- Fix: two files have different values at the same key path. Use `--merge-strategy first` or `--merge-strategy last` to resolve.
- `'...' is not a JSON object` -- Fix: each input file must contain a JSON object (`{...}`), not an array or scalar.
---
### `artifact summarize`
Summarize a JSON artifact's structure and estimated token cost.
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--input` | string | **yes** | Path to JSON file or `-` for stdin |
No JSON input schema -- the input is any valid JSON value.
**Output fields:**
| Field | Type | Description |
|-------|------|-------------|
| `field_count` | u32 | Total number of fields (recursive) |
| `top_level_keys` | array of strings | Keys at the root level |
| `estimated_tokens` | u32 | Rough token estimate (byte length / 4) |
**Example:**
```bash
echo '{"name": "test", "data": {"x": 1, "y": 2}}' \
| nxuskit-cli artifact summarize --input - --format json
```
**Common errors:**
- `Invalid artifact JSON: ...` -- Fix: input must be valid JSON.
---
### `packet validate`
Validate a JSON document against a JSON Schema.
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--input` | string | **yes** | Packet data file (JSON) or `-` for stdin |
| `--schema` | string | **yes** | Path to a JSON Schema file |
No custom input schema -- the packet is any JSON value validated against the
provided JSON Schema.
**Example:**
```bash
echo '{"type": "string"}' > /tmp/schema.json
echo '"hello"' | nxuskit-cli packet validate --input - --schema /tmp/schema.json --format json
```
**Output fields:**
| Field | Type | Description |
|-------|------|-------------|
| `valid` | bool | `true` if the packet conforms to the schema |
| `errors` | array of `{path, message, keyword}` | Validation errors (empty when valid) |
**Common errors:**
- `SchemaNotFound { path: "..." }` -- Fix: the `--schema` path must point to an existing file.
- `Invalid JSON Schema: ...` -- Fix: ensure the schema file is a valid JSON Schema draft.
- Exits with code 1 when validation fails (output still written to stdout).
---
### `tool-loop run`
Iterative tool-augmented LLM loop. The model is called repeatedly until it
converges (stops requesting tool calls) or hits `max_iterations`.
**Input schema (`ToolLoopInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `prompt` | string | **yes** | Initial user prompt |
| `provider` | string | no | Provider name (default: `loopback` or `$NXUSKIT_PROVIDER`) |
| `model` | string | no | Model identifier. For `loopback`, use a valid loopback model such as `"echo"`; do not rely on the implicit `"default"` model in v1.0.x. |
| `max_iterations` | u32 | no | Maximum loop iterations (default: `10`) |
| `tools` | array of strings | no | Tool adapter names: `"file_reader"`, `"calculator"`, `"web_search"` |
| `tool_configs` | JSON object | no | Per-tool configuration |
| `tool_definitions` | array of JSON objects | no | Function/tool schemas passed to the LLM for function calling |
Built-in tool adapters:
- `file_reader` -- reads a file, expects `{"path": "..."}` arguments
- `calculator` -- evaluates a math expression, expects `{"expression": "..."}` arguments
- `web_search` -- searches the web, expects `{"query": "..."}` arguments (MCP-gated)
**Example:**
```bash
echo '{
"prompt": "What is 2 + 2?",
"provider": "loopback",
"model": "echo",
"tools": ["calculator"],
"max_iterations": 5
}' | nxuskit-cli tool-loop run --input - --format json
```
**Common errors:**
- `Invalid tool-loop input: missing field "prompt"` -- Fix: `prompt` is the only required field.
- `Unknown tool adapter: xyz` -- Fix: valid adapters are `file_reader`, `calculator`, `web_search`.
- `Entitlement check failed: mcp` -- Fix: the `mcp` tool adapter is Pro-gated.
---
### `judge select`
LLM-based candidate selection. Sends candidates and criteria to an LLM and
parses a structured JSON response with scores and reasoning.
**Input schema (`JudgeSelectInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `candidates` | array of `Candidate` | **yes** | Candidates to evaluate |
| `criteria` | string | no | Evaluation criteria description |
| `provider` | string | no | Provider name (default: `"loopback"`) |
| `model` | string | no | Model identifier. Use a configured LLM model; `loopback` echoes the judge prompt and can fail structured parsing. |
**`Candidate` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | string | **yes** | Unique candidate identifier |
| `content` | string | **yes** | Candidate text to evaluate |
**Example:**
```bash
echo '{
"candidates": [
{"id": "a", "content": "The answer is 42."},
{"id": "b", "content": "The answer is approximately 42.0."}
],
"criteria": "accuracy and conciseness",
"provider": "your-provider",
"model": "your-json-capable-model"
}' | nxuskit-cli judge select --input - --format json
```
**Common errors:**
- `Invalid judge select input: missing field "candidates"` -- Fix: `candidates` array is required with at least one entry.
- `Failed to parse judge response as structured JSON: ...` -- Fix: the LLM must return a JSON object with `selected_id`, `reasoning`, and `scores`. The loopback provider may not produce valid judge output; use a real LLM provider for meaningful results.
---
### `branch fork`
Fan out a single prompt to multiple models concurrently.
**Input schema (`BranchForkInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `prompt` | string | **yes** | Prompt sent to all models |
| `models` | array of strings | **yes** | Model identifiers to invoke in parallel |
| `provider` | string | no | Provider name (default: `"loopback"`) |
| `system` | string | no | System message prepended to each request |
Alternatively, models can be specified via the `--models` CLI flag as a
comma-separated list, which overrides the `models` field in the JSON input.
**Example:**
```bash
echo '{
"prompt": "Explain recursion in one sentence.",
"models": ["echo", "echo-json-native"],
"provider": "loopback"
}' | nxuskit-cli branch fork --input - --format json
```
**Using `--models` flag:**
```bash
echo '{"prompt": "Explain recursion.", "provider": "loopback"}' \
| nxuskit-cli branch fork --input - --models echo,echo-json-native --format json
```
**Common errors:**
- `Invalid fork input: missing field "prompt"` -- Fix: `prompt` is required.
- `Invalid fork input: missing field "models"` -- Fix: provide `models` in JSON or via `--models` flag.
---
### `branch compare`
Compare results from a previous `branch fork` invocation. Input is the JSON
output of `branch fork` (the `BranchForkResult` object).
**Input schema (`BranchForkResult`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `results` | array of `BranchModelResult` | **yes** | Results from `branch fork` |
**`BranchModelResult` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `model` | string | **yes** | Model identifier |
| `content` | string | **yes** | Model's response text |
| `usage` | `{input_tokens, output_tokens, total_tokens}` | no | Token usage |
| `elapsed_ms` | f64 | **yes** | Response latency in milliseconds |
**Output includes:**
- `comparison`: per-model length and optional quality score
- `diffs`: structural differences (content_length, word_count, sentence_count, elapsed_ms, content_similarity for 2-model comparisons)
**Example (piping fork output to compare):**
```bash
echo '{
"prompt": "Explain recursion.",
"models": ["echo", "echo-json-native"],
"provider": "loopback"
}' | nxuskit-cli branch fork --input - --format json \
| jq '.result' \
| nxuskit-cli branch compare --input - --format json
```
**Common errors:**
- `Invalid fork result input: missing field "results"` -- Fix: input must be a `BranchForkResult` object (the `result` field from a fork envelope, not the full envelope).
---
### `solver what-if`
What-if scenario analysis (Pro-gated). Accepts the same three input formats as
`solver solve`. With `--compare`, solves both a base problem and an assumed
variant, then outputs a diff of the results.
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--input` | string | **yes** | Base problem file or `-` for stdin (any solver format) |
| `--compare` | string | no | Assumed variant file (same format as `--input`). Enables diff output. |
| `--format` | string | no | Output format: `json` (default), `yaml`, `text` |
**Single what-if (no comparison):**
Returns the solution to the assumed scenario, identical in shape to `solver solve` output.
```bash
echo '{
"variables": [
{"name": "budget", "type": "integer", "bounds": [{"min": 0}, {"max": 100000}]},
{"name": "headcount", "type": "integer", "bounds": [{"min": 1}, {"max": 20}]}
],
"constraints": ["budget == headcount * 5000"],
"assumptions": [{"name": "assume_headcount", "constraint_type": "eq", "params": {"left": "headcount", "right": 12}}]
}' | nxuskit-cli solver what-if --input - --format json
```
**Comparison (`--compare`):**
Solves both the base (from `--input`) and the assumed variant (from `--compare`),
then emits a `diff` block showing changed variables and the objective delta.
```bash
nxuskit-cli solver what-if --input base.json --compare assumed.json --format json
```
**Output shape (comparison):**
```json
{
"base": { "status": "sat", "values": {"budget": 60000, "headcount": 12} },
"assumed": { "status": "sat", "values": {"budget": 75000, "headcount": 15} },
"diff": {
"changed": [
{"variable": "budget", "base": 60000, "assumed": 75000, "delta": 15000},
{"variable": "headcount", "base": 12, "assumed": 15, "delta": 3}
],
"objective_delta": 15000
}
}
```
**Common errors:**
- `Entitlement check failed: solver_what_if` -- Fix: requires Pro edition.
- `Cannot parse base input` -- Fix: ensure `--input` is a valid solver format.
- `Cannot parse assumed input` -- Fix: ensure `--compare` file uses the same solver format as `--input`.
---
### `clips session`
Persistent CLIPS sessions survive across multiple eval calls. Session count is
enforced per tier — exit code 4 when the limit is reached.
#### `clips session create`
Create a new CLIPS session, optionally pre-loading rules.
**Input schema (`ClipsSessionCreateInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `rules` | string | no | CLIPS rule definitions to load into the session |
| `label` | string | no | Human-readable label for the session |
**Example:**
```bash
echo '{
"rules": "(defrule greet (person (name ?n)) => (printout t (str-cat \"Hello \" ?n) crlf))",
"label": "greet-session"
}' | nxuskit-cli clips session create --input - --format json
```
**Output:**
```json
{
"session_id": "sess_abc12345",
"label": "greet-session",
"created_at": "2026-04-13T10:00:00Z",
"rule_count": 1
}
```
**Common errors:**
- `Entitlement check failed: clips_session_limit` (exit 4) -- Fix: destroy an existing session first, or upgrade edition.
- `Failed to load CLIPS rules: ...` (exit 1) -- Fix: check CLIPS syntax.
---
#### `clips session list`
List all active CLIPS sessions.
**No input required.** Pass `--format json` for machine-readable output.
```bash
nxuskit-cli clips session list --format json
```
**Output:**
```json
{
"sessions": [
{"session_id": "sess_abc12345", "label": "greet-session", "rule_count": 1, "created_at": "..."},
{"session_id": "sess_def67890", "label": null, "rule_count": 5, "created_at": "..."}
],
"count": 2
}
```
---
#### `clips session destroy`
Destroy a session and release its resources.
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--session-id` | string | **yes** | Session ID returned by `clips session create` |
```bash
nxuskit-cli clips session destroy --session-id sess_abc12345 --format json
```
**Output:**
```json
{"session_id": "sess_abc12345", "destroyed": true}
```
**Common errors:**
- `Unknown session ID: sess_abc12345` (exit 5) -- Fix: use `clips session list` to find valid IDs.
---
### `provider list`
List all registered providers with type, status, and capability metadata.
**No input required.**
```bash
nxuskit-cli provider list --format json
```
**Output shape:**
```json
{
"providers": [
{
"name": "openai",
"type": "llm",
"status": "available",
"capabilities": ["streaming", "vision", "tool_calling"],
"auth_required": true
},
{
"name": "loopback",
"type": "llm",
"status": "available",
"capabilities": ["streaming"],
"auth_required": false
},
{
"name": "clips",
"type": "rule_engine",
"status": "available",
"capabilities": [],
"auth_required": false
}
],
"count": 3
}
```
---
### `provider info`
Show detailed information for a single provider. Accepts fuzzy name matching —
if the name is close but not exact, suggestions are printed to stderr and the
command exits with code 5.
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `` | string | **yes** | Provider name (positional argument) |
```bash
nxuskit-cli provider info openai --format json
```
**Output shape:**
```json
{
"name": "openai",
"type": "llm",
"status": "available",
"capabilities": ["streaming", "vision", "tool_calling"],
"auth_required": true,
"auth_env_var": "OPENAI_API_KEY",
"default_model": "gpt-4o",
"supported_formats": ["json", "yaml", "jsonl", "text"],
"docs_url": "https://platform.openai.com/docs"
}
```
**Common errors:**
- `Unknown provider "opnai". Did you mean: openai?` (exit 5, stderr) -- Fix: use the exact provider name from `provider list`, or let the suggestion guide you.
---
### Error responses
All non-zero exits write a JSON `ErrorEnvelope` to **stderr**. Stdout may be
empty or contain partial output.
```json
{
"code": "entitlement_denied",
"message": "This command requires the pro edition",
"details": {
"feature": "solver",
"current_tier": "oss",
"required_tier": "pro"
},
"trace_id": "a1b2c3d4",
"timestamp": "2026-04-13T10:00:00Z"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `code` | string | Machine-readable error code |
| `message` | string | Human-readable description |
| `details` | object | Optional structured context (tier info, field names, session IDs, etc.) |
| `trace_id` | string | 8-character hex trace ID |
| `timestamp` | string | ISO 8601 UTC timestamp |
**Exit code -> `code` mapping (Level 1 and Level 2):**
| Exit | `code` values |
|------|--------------|
| 0 | (success - no `code`) |
| 1 | `internal_error`, `provider_error`, `engine_error`, `internal` |
| 2 | `timeout`, `idle_timeout` |
| 3 | `auth_failure`, `auth_failed`, `token_expired`, `token_missing` |
| 4 | `entitlement_denied`, `session_limit_reached` |
| 5 | `validation`, `validation_error`, `parse_error`, `unknown_provider`, `unknown_session`, `zen_validate_error`, `zen_test_mismatch`, `zen_test_eval_error` |
| 130 | `cancelled` (SIGINT) |
The exit-code set itself is frozen (FR-001 / Article IV): Level 2 commands like
`zen validate` / `zen test` introduce new `code` strings within exit 5, not new
exit codes.
---
# Cloud LLM Providers
URL: https://docs.nxus.systems/nxuskit/reference/providers/cloud-llms
## OpenAI
```json
{
"provider_type": "openai",
"api_key": "sk-...",
"base_url": "https://api.openai.com/v1",
"timeout_ms": 30000
}
```
**Environment variable:** `OPENAI_API_KEY`
**Supported models:** `gpt-4o`, `gpt-4o-mini`, `o1`, `o1-mini`, `o3-mini`, `gpt-4-turbo`
**Capabilities:** System messages, streaming, vision, tools/function calling, JSON mode, JSON schema, seed, logprobs, presence/frequency penalty, response format
## xAI Grok
```json
{
"provider_type": "xai",
"api_key": "xai-...",
"base_url": "https://api.x.ai/v1",
"timeout_ms": 30000
}
```
**Environment variable:** `XAI_API_KEY`
**Supported models:** `grok-4`, `grok-4-latest`, `grok-4-fast`
**Capabilities:** System messages, streaming, vision, tools/function calling, JSON mode, JSON schema
`xai` is the canonical provider id for xAI Grok. `groq` remains Groq, Inc.; there is no `grok` provider alias.
## Anthropic Claude
```json
{
"provider_type": "claude",
"api_key": "sk-ant-...",
"base_url": "https://api.anthropic.com",
"timeout_ms": 30000
}
```
**Environment variable:** `ANTHROPIC_API_KEY`
**Supported models:** `claude-sonnet-4-20250514`, `claude-opus-4-20250514`, `claude-haiku-4-5-20251001`, `claude-3-5-sonnet-20241022`
**Capabilities:** System messages, streaming, vision, tools/function calling, JSON mode, top-k sampling. Max stop sequences: 8192.
## Groq
```json
{
"provider_type": "groq",
"api_key": "gsk_...",
"timeout_ms": 30000
}
```
**Environment variable:** `GROQ_API_KEY`
**Supported models:** `llama-3.3-70b-versatile`, `llama-3.1-8b-instant`, `mixtral-8x7b-32768`, `gemma2-9b-it`
**Capabilities:** System messages, streaming, tools/function calling, JSON mode
## Fireworks
```json
{
"provider_type": "fireworks",
"api_key": "fw_...",
"timeout_ms": 30000
}
```
**Environment variable:** `FIREWORKS_API_KEY`
**Capabilities:** System messages, streaming
## Together
```json
{
"provider_type": "together",
"api_key": "...",
"timeout_ms": 30000
}
```
**Environment variable:** `TOGETHER_API_KEY`
**Capabilities:** System messages, streaming
## OpenRouter
```json
{
"provider_type": "openrouter",
"api_key": "sk-or-...",
"timeout_ms": 30000
}
```
**Environment variable:** `OPENROUTER_API_KEY`
**Capabilities:** System messages, streaming, vision, tools/function calling
## Perplexity
```json
{
"provider_type": "perplexity",
"api_key": "pplx-...",
"timeout_ms": 30000
}
```
**Environment variable:** `PERPLEXITY_API_KEY`
**Capabilities:** System messages, streaming
## Mistral
```json
{
"provider_type": "mistral",
"api_key": "...",
"timeout_ms": 30000
}
```
**Environment variable:** `MISTRAL_API_KEY`
**Supported models:** `mistral-large-latest`, `mistral-medium-latest`, `mistral-small-latest`, `codestral-latest`
**Capabilities:** System messages, streaming, tools/function calling, JSON mode
---
# Expert System & Utility Providers
URL: https://docs.nxus.systems/nxuskit/reference/providers/expert-systems
## CLIPS Rule Engine
The CLIPS provider runs rules against a CLIPS 6.4.2 expert system engine.
Unlike LLM providers, CLIPS uses deterministic rule-based reasoning.
A word about CLIPS: During its development at NASA from 1985 to 1996, the
primary CLIPS contributors were: Robert Savely, who conceived and championed
the project; Chris Culbert, who managed the project; Gary Riley and Brian
Dantes, who were the lead developers; and Frank Lopez, who developed the first
version. Since leaving NASA in 1996, Gary Riley has maintained CLIPS as public
domain software.
```json
{
"provider_type": "clips",
"model": "/path/to/rules/directory"
}
```
**Configuration:**
- `model` field is used for the rules directory path (contains `.clp` rule files or `.bin` binary images)
**Capabilities:** System messages
**Note:** No API key required. The CLIPS engine runs in-process.
For writing custom rules, see the [Rule Authoring Guide](/nxuskit/guides/clips-rule-authoring/).
## MCP (Model Context Protocol)
Connects to an MCP server for tool-augmented model interactions.
```json
{
"provider_type": "mcp",
"base_url": "http://localhost:3000",
"model": "model-name"
}
```
**Configuration:**
- `base_url` — MCP server URI (required)
- `model` — Model name to use on the server
**Capabilities:** System messages, streaming
## Mock (Testing)
Returns deterministic responses for unit testing.
```json
{
"provider_type": "mock"
}
```
**Capabilities:** System messages, streaming
**Note:** No API key or configuration required. Returns fixed responses.
## Loopback (Testing)
Echoes back the user's input for integration testing.
```json
{
"provider_type": "loopback"
}
```
**Capabilities:** System messages, streaming
**Note:** Use `"model": "echo"` in the chat request to echo back the user's
message content. Other model names return an empty response.
---
# Local LLM Providers
URL: https://docs.nxus.systems/nxuskit/reference/providers/local-llms
nxusKit supports two categories of local LLM providers:
- **In-Process Providers** — Load and run models directly in your application process. No external server required. Requires Cargo feature flags.
- **HTTP-Based Providers** — Connect to a locally running inference server (Ollama, LM Studio). No feature flags needed.
---
## In-Process Providers
In-process providers load GGUF model files directly into your application and run inference without any external server. This gives you the lowest possible latency, full control over model lifecycle, and zero network overhead.
### Backends
nxusKit provides two in-process inference backends:
| Backend | Feature Flag | Engine | Status |
|---------|-------------|--------|--------|
| llama.cpp | `provider-local-llama` | [llama-cpp-2](https://github.com/utilityai/llama-cpp-rs) (safe Rust bindings to llama.cpp) | Production-ready |
| mistral.rs | `provider-local-mistralrs` | [mistral.rs](https://github.com/EricLBuehler/mistral.rs) (pure-Rust inference on Candle) | Experimental |
Both backends load the same **GGUF** model format. If both features are enabled, you can select a backend explicitly or let nxusKit auto-select the first available one.
### Supported Model Format
**GGUF** (GPT-Generated Unified Format) is the only supported format. GGUF files are self-contained — they bundle weights, tokenizer, and metadata in a single file. Both backends read the same `.gguf` files.
You can obtain GGUF models from:
- [Hugging Face](https://huggingface.co/models?library=gguf) — Search for "GGUF" in model filters
- [Ollama](https://ollama.com/library) — Models pulled by Ollama are stored as GGUF blobs (nxusKit can discover these)
- [TheBloke on Hugging Face](https://huggingface.co/TheBloke) — Prolific quantizer of popular models
### Compatible Model Families
Any model published in GGUF format that is compatible with llama.cpp should work. The following model families are known to work:
| Model Family | Parameters | Example GGUF | Notes |
|---|---|---|---|
| **Llama 3.2** | 1B, 3B | `Llama-3.2-1B-Instruct-Q4_K_M.gguf` | Meta's latest small models. Great for CPU. |
| **Llama 3.1** | 8B, 70B, 405B | `Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf` | Excellent general-purpose. 8B runs well on 16GB RAM. |
| **Llama 3** | 8B, 70B | `Meta-Llama-3-8B-Instruct-Q4_K_M.gguf` | Predecessor to 3.1, widely available. |
| **Llama 2** | 7B, 13B, 70B | `llama-2-7b-chat.Q4_K_M.gguf` | Older but battle-tested. |
| **Mistral** | 7B | `mistral-7b-instruct-v0.3.Q4_K_M.gguf` | Strong performance relative to size. |
| **Mixtral** | 8x7B, 8x22B | `mixtral-8x7b-instruct-v0.1.Q4_K_M.gguf` | Mixture-of-experts. Needs more RAM. |
| **Phi-3 / Phi-3.5** | 3.8B, 14B | `Phi-3.5-mini-instruct-Q4_K_M.gguf` | Microsoft. Strong reasoning for size. |
| **Gemma 2** | 2B, 9B, 27B | `gemma-2-9b-it-Q4_K_M.gguf` | Google. Good coding and instruction following. |
| **Qwen 2.5** | 0.5B–72B | `Qwen2.5-7B-Instruct-Q4_K_M.gguf` | Alibaba. Multilingual, strong at math/code. |
| **DeepSeek-R1** | 1.5B–70B (distilled) | `DeepSeek-R1-Distill-Llama-8B-Q4_K_M.gguf` | Reasoning-focused distilled models. |
| **CodeLlama** | 7B, 13B, 34B | `codellama-7b-instruct.Q4_K_M.gguf` | Code-specialized Llama variant. |
| **TinyLlama** | 1.1B | `tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf` | Tiny. Useful for testing and CI. |
| **StableLM** | 1.6B, 3B | `stablelm-2-1_6b-chat.Q4_K_M.gguf` | Stability AI. Small and fast. |
| **Yi** | 6B, 9B, 34B | `Yi-1.5-9B-Chat-Q4_K_M.gguf` | 01.AI. Strong multilingual. |
| **Command R** | 35B, 104B | `c4ai-command-r-v01-Q4_K_M.gguf` | Cohere. RAG-optimized. |
| **Falcon** | 7B, 40B, 180B | `falcon-7b-instruct-Q4_K_M.gguf` | TII. |
> **Tip:** For testing and development, start with **TinyLlama 1.1B** (fast, tiny, runs anywhere) or **Llama 3.2 1B** (modern, instruction-tuned, still small enough for CPU).
### Quantization Levels
GGUF models come in different quantization levels that trade quality for size/speed. nxusKit auto-detects the quantization from the filename:
| Quantization | Bits/Weight | Relative Quality | Relative Size | Recommended For |
|---|---|---|---|---|
| `F32` | 32 | Best (reference) | Largest | Accuracy testing only |
| `F16` | 16 | Excellent | ~50% of F32 | GPU with sufficient VRAM |
| `Q8_0` | 8.5 | Near-lossless | ~50% of F16 | Quality-sensitive tasks |
| `Q6_K` | 6.6 | Very good | ~38% of F16 | Good quality/size balance |
| `Q5_K_M` | 5.7 | Good | ~33% of F16 | Balanced |
| `Q5_K_S` | 5.5 | Good | ~32% of F16 | Slightly smaller than K_M |
| `Q4_K_M` | 4.8 | Acceptable | ~27% of F16 | **Most popular**. Best quality/size tradeoff. |
| `Q4_K_S` | 4.5 | Acceptable | ~26% of F16 | Slightly smaller than K_M |
| `Q3_K_M` | 3.9 | Degraded | ~22% of F16 | Memory-constrained environments |
| `Q2_K` | 3.4 | Poor | ~18% of F16 | Extreme memory constraints only |
> **Recommendation:** Use **Q4_K_M** for most deployments. It provides the best balance of quality, speed, and memory usage.
### Memory Requirements
Approximate RAM needed to load a model (varies by quantization):
| Model Size | Q4_K_M | Q8_0 | F16 |
|---|---|---|---|
| 1B params | ~0.8 GB | ~1.2 GB | ~2 GB |
| 3B params | ~2 GB | ~3.5 GB | ~6 GB |
| 7-8B params | ~4.5 GB | ~8 GB | ~15 GB |
| 13B params | ~8 GB | ~14 GB | ~26 GB |
| 34B params | ~20 GB | ~36 GB | ~68 GB |
| 70B params | ~40 GB | ~72 GB | ~140 GB |
These are approximate. Actual usage depends on context window size, batch size, and KV cache.
### GPU Acceleration
GPU offloading is automatic when available:
| Platform | Acceleration | How to Enable |
|---|---|---|
| macOS (Apple Silicon) | Metal | Automatic — llama.cpp detects Metal at build time |
| Linux (NVIDIA) | CUDA | Install CUDA toolkit; llama-cpp-2 detects at build time |
| Linux (AMD) | ROCm/Vulkan | Vulkan support via llama.cpp build flags |
| Windows (NVIDIA) | CUDA | Install CUDA toolkit |
| All platforms | CPU (AVX2/NEON) | Always available as fallback |
Control GPU offloading with `n_gpu_layers`:
- `-1` — offload all layers to GPU (maximum acceleration)
- `0` — CPU only (default)
- `N` — offload first N layers (partial offloading for limited VRAM)
### Configuration
```json
{
"provider_type": "local",
"model": "/path/to/model.gguf",
"options": {
"backend": "llama-cpp",
"n_gpu_layers": -1,
"context_size": 4096,
"batch_size": 512,
"threads": 8
}
}
```
**Configuration options:**
| Option | Type | Default | Description |
|---|---|---|---|
| `backend` | string | auto-detect | `"llama-cpp"` or `"mistralrs"`. Auto-selects first available if omitted. |
| `n_gpu_layers` | integer | `0` | GPU layer offloading. `-1` = all, `0` = CPU only, `N` = first N layers. |
| `context_size` | integer | model default | Context window size in tokens. |
| `batch_size` | integer | backend default | Prompt processing batch size. Higher = faster prompt processing, more memory. |
| `threads` | integer | auto-detect | CPU thread count. Leave unset for optimal auto-detection. |
### Rust API
```rust
use nxuskit-engine::{LocalRuntimeProvider, ChatRequest, Message};
let provider = LocalRuntimeProvider::builder()
.model_path("/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf")
.n_gpu_layers(-1) // Use GPU
.context_size(4096)
.build()?;
let request = ChatRequest::new("Llama-3.2-1B-Instruct-Q4_K_M.gguf")
.with_message(Message::user("Explain quantum computing in one paragraph."))
.with_temperature(0.7)
.with_max_tokens(256);
let response = provider.chat(&request).await?;
println!("{}", response.content);
```
### Model Discovery
The provider can discover available models from multiple sources:
```rust
let models = provider.list_models().await?;
for model in &models {
println!("{}: {} ({})",
model.id,
model.name,
model.metadata.get("quantization").unwrap_or(&"unknown".into()));
}
```
**Discovery sources** (in priority order):
1. **Explicit path** — The model path in your configuration
2. **Search paths** — Directories you configure (scans for `.gguf` files)
3. **Ollama store** (opt-in) — Discovers models already pulled by Ollama
**Ollama store locations** (auto-detected):
- macOS: `~/.ollama/models`
- Linux: `/usr/share/ollama/.ollama/models` or `~/.ollama/models`
- Windows: `%USERPROFILE%\.ollama\models`
**Environment variables:**
- `NXUSKIT_MODELS` — Custom model search directory
- `OLLAMA_MODELS` — Override Ollama store location
### Model Cache Management
Models stay loaded in memory after first use. You can manage the cache explicitly:
```rust
// Pre-load a model (async, happens in background)
provider.preload_model("/models/llama-3.2-1b.Q4_K_M.gguf").await?;
// Check what's loaded
for info in provider.cached_models() {
println!("{}: {} bytes", info.path, info.memory_bytes.unwrap_or(0));
}
// Free memory
provider.unload_model("/models/llama-3.2-1b.Q4_K_M.gguf");
```
### Capabilities
| Capability | Supported |
|---|---|
| System messages | Yes |
| Streaming | Yes (token-by-token) |
| Vision/images | No |
| JSON mode | No (llama-cpp) / Yes (mistral.rs) |
| Seed (deterministic) | Yes |
| Stop sequences | Yes (up to 4) |
| Temperature | Yes |
| Top-p | Yes |
| Max tokens | Yes |
| Presence penalty | No |
| Frequency penalty | No |
| Tool calling | No |
### Backend Comparison
| Feature | llama.cpp (`provider-local-llama`) | mistral.rs (`provider-local-mistralrs`) |
|---|---|---|
| Maturity | Production-ready | Experimental |
| Language | C++ with Rust bindings | Pure Rust (Candle) |
| Build time | Fast (~30s) | Slow (~3-5 min, pulls Candle) |
| GPU support | Metal, CUDA, Vulkan | Metal, CUDA (via Candle) |
| JSON mode | No | Yes (ISQ support) |
| Chat templates | Manual | Auto-detected from GGUF metadata |
| PagedAttention | No | Yes (CUDA, Apple Silicon) |
| In-situ quantization | No | Yes (load unquantized, quantize at runtime) |
| Binary size impact | Small (~2 MB) | Large (~20 MB, Candle framework) |
---
## HTTP-Based Providers
HTTP-based local providers connect to a separately running inference server. No Cargo feature flags are needed — they use the standard HTTP transport.
### Ollama
Run models locally via [Ollama](https://ollama.com/).
```json
{
"provider_type": "ollama",
"base_url": "http://localhost:11434",
"timeout_ms": 120000
}
```
**Environment variable:** `OLLAMA_HOST` (optional, defaults to `http://localhost:11434`)
**Supported models:** Any model pulled via `ollama pull`, e.g., `llama3.1`, `codellama`, `mistral`, `phi3`
**Capabilities:** System messages, streaming
**Note:** No API key required. The provider connects to a locally running Ollama server. The default timeout is 120 seconds (longer than cloud providers) to accommodate model loading.
### LM Studio
Run models locally via [LM Studio](https://lmstudio.ai/).
```json
{
"provider_type": "lmstudio",
"base_url": "http://localhost:1234/v1",
"timeout_ms": 120000
}
```
**Environment variable:** `LMSTUDIO_HOST` (optional, defaults to `http://localhost:1234/v1`)
**Capabilities:** System messages, streaming
**Note:** No API key required. Start the LM Studio local server before using this provider.
---
## Choosing Between Local Providers
| Consideration | In-Process (local) | Ollama | LM Studio |
|---|---|---|---|
| Setup complexity | Download a GGUF file | Install Ollama + pull model | Install LM Studio + download model |
| External server | None required | Must be running | Must be running |
| Latency | Lowest (no HTTP overhead) | Low (localhost HTTP) | Low (localhost HTTP) |
| Model lifecycle control | Full (preload/unload API) | Managed by Ollama | Managed by LM Studio |
| Memory management | Direct (cache API) | Managed by Ollama | Managed by LM Studio |
| Feature flags needed | Yes (`provider-local-llama`) | No | No |
| Build dependencies | C++ compiler (llama.cpp) | None | None |
| Best for | Embedded/library use, max control | Quick experimentation | GUI-based development |
---
# Z3 Constraint Satisfaction Provider
URL: https://docs.nxus.systems/nxuskit/reference/providers/z3-solver
The Z3 provider integrates [Microsoft Z3](https://github.com/Z3Prover/z3), an industry-grade SMT (Satisfiability Modulo Theories) solver, into the nxusKit provider interface. It enables constraint satisfaction, optimization, and formal verification problems to be expressed and solved using the same `chat()` / `chat_stream()` API as LLM providers.
Unlike LLM providers, Z3 is deterministic — the same input always produces the same output.
## Configuration
```json
{
"provider_type": "z3",
"timeout_ms": 30000,
"random_seed": 42,
"produce_unsat_core": true,
"logic": "QF_LIA"
}
```
**Configuration options:**
| Option | Type | Default | Description |
|---|---|---|---|
| `timeout_ms` | integer | 30000 | Solver timeout in milliseconds |
| `random_seed` | integer | none | Seed for search heuristics (for reproducibility) |
| `produce_unsat_core` | boolean | false | Extract conflicting constraints when problem is unsatisfiable |
| `logic` | string | auto | SMT logic preset (e.g., `"QF_LIA"`, `"QF_LRA"`, `"QF_BV"`) |
| `max_conflicts` | integer | none | Maximum conflict (branch) limit for search |
| `model_paths` | string[] | none | Directories to scan for `.smt2` and `.z3` model files |
**Capabilities:** System messages, streaming, JSON mode, seed
## Input Format
The Z3 provider accepts structured JSON as the user message content. The JSON describes variables, constraints, and optionally an optimization objective.
### Variables
```json
{
"variables": [
{"name": "x", "var_type": "integer"},
{"name": "y", "var_type": "integer", "domain": {"min": 1, "max": 100}},
{"name": "flag", "var_type": "boolean"},
{"name": "ratio", "var_type": "real", "domain": {"min": 0.0, "max": 1.0}}
]
}
```
**Variable types:** `integer`, `real`, `boolean`
**Domain constraints** (optional): `min`, `max` for numeric types.
### Constraints
```json
{
"constraints": [
{"constraint_type": "eq", "params": {"left": "x", "right": 42}},
{"constraint_type": "gt", "params": {"left": "y", "right": "x"}},
{"constraint_type": "all_different", "params": {"variables": ["x", "y", "z"]}},
{"constraint_type": "in_range", "params": {"variable": "x", "min": 1, "max": 10}}
]
}
```
**Supported constraint types:**
| Type | Description | Parameters |
|---|---|---|
| `eq` | Equal | `left`, `right` |
| `neq` | Not equal | `left`, `right` |
| `lt` | Less than | `left`, `right` |
| `gt` | Greater than | `left`, `right` |
| `le` | Less than or equal | `left`, `right` |
| `ge` | Greater than or equal | `left`, `right` |
| `add` | Addition expression | `left`, `right` (or `operands` list) |
| `sub` | Subtraction expression | `left`, `right` |
| `mul` | Multiplication expression | `left`, `right` |
| `div` | Division expression | `left`, `right` |
| `and` | Logical AND | `operands` list |
| `or` | Logical OR | `operands` list |
| `not` | Logical NOT | `operand` |
| `implies` | Logical implication | `left`, `right` |
| `iff` | If and only if | `left`, `right` |
| `all_different` | All variables must differ | `variables` list |
| `at_most` | At most N true | `variables`, `n` |
| `at_least` | At least N true | `variables`, `n` |
| `exactly` | Exactly N true | `variables`, `n` |
| `in_range` | Value within range | `variable`, `min`, `max` |
Parameters can reference variable names (strings), literal values (numbers, booleans), or nested expressions.
### Optimization
Add an `objective` field to minimize or maximize a variable:
```json
{
"variables": [...],
"constraints": [...],
"objective": {
"direction": "minimize",
"expression": "cost"
}
}
```
**Directions:** `"minimize"` or `"maximize"`
### Named Constraints
Constraints can be named for unsat core extraction:
```json
{
"constraints": [
{"name": "budget_limit", "constraint_type": "le", "params": {"left": "cost", "right": 1000}},
{"name": "quality_req", "constraint_type": "ge", "params": {"left": "quality", "right": 8}}
]
}
```
When the problem is unsatisfiable and `produce_unsat_core` is enabled, the response includes the names of conflicting constraints.
## Output Format
The response `content` field contains JSON:
### Satisfiable (SAT)
```json
{
"status": "sat",
"assignments": {
"x": 42,
"y": 58,
"flag": true
},
"stats": {
"solve_time_ms": 2,
"num_conflicts": 0,
"num_decisions": 5
}
}
```
### Unsatisfiable (UNSAT)
```json
{
"status": "unsat",
"unsat_core": ["budget_limit", "quality_req"],
"stats": {
"solve_time_ms": 1,
"num_conflicts": 3
}
}
```
### Optimal (Optimization)
```json
{
"status": "optimal",
"assignments": {
"cost": 150,
"quality": 8
},
"objective_value": 150.0,
"stats": {
"solve_time_ms": 15,
"num_solutions_found": 4
}
}
```
## Streaming
- **Satisfaction problems**: Single result chunk (solve is typically < 1ms).
- **Optimization problems**: Progressive improvement — each improving solution is emitted as a `StreamChunk`, with the final chunk containing `finish_reason` and complete stats.
## Examples
### Basic Satisfaction
```rust
use nxuskit-engine::{Z3Provider, ChatRequest, Message};
let provider = Z3Provider::builder()
.timeout_ms(5_000)
.build()?;
let problem = r#"{
"variables": [
{"name": "x", "var_type": "integer", "domain": {"min": 1, "max": 9}},
{"name": "y", "var_type": "integer", "domain": {"min": 1, "max": 9}},
{"name": "z", "var_type": "integer", "domain": {"min": 1, "max": 9}}
],
"constraints": [
{"constraint_type": "all_different", "params": {"variables": ["x", "y", "z"]}},
{"constraint_type": "eq", "params": {"left": {"add": ["x", "y", "z"]}, "right": 15}}
]
}"#;
let request = ChatRequest::new("z3-solver")
.with_message(Message::user(problem));
let response = provider.chat(&request).await?;
let output: serde_json::Value = serde_json::from_str(&response.content)?;
assert_eq!(output["status"], "sat");
```
### Via C ABI (Go)
```go
provider, err := nxuskit-go.NewZ3FFIProvider(
nxuskit-go.WithZ3Timeout(5000),
nxuskit-go.WithZ3UnsatCore(true),
)
response, err := provider.Chat(ctx, &nxuskit-go.ChatRequest{
Model: "z3-solver",
Messages: []nxuskit-go.Message{
{Role: "user", Content: problemJSON},
},
})
```
### Via C ABI (Python)
```python
from nxuskit-py._ffi_provider import create_ffi_provider
provider = create_ffi_provider({
"provider_type": "z3",
"timeout_ms": 5000,
"produce_unsat_core": True,
})
response = provider.chat(model="z3-solver", messages=[
{"role": "user", "content": problem_json}
])
```
## Model Discovery
The Z3 provider can discover pre-defined constraint model files:
```rust
let models = provider.list_models().await?;
// Returns built-in models ("z3-solver", "z3-optimizer") plus
// any .smt2 and .z3 files found in configured model_paths
```
## Use Cases
- **Scheduling**: Resource allocation, timetabling, shift planning
- **Configuration**: Product configuration with constraints, compatibility checking
- **Puzzles**: Sudoku, N-Queens, logic puzzles
- **Verification**: Property checking, invariant validation
- **Optimization**: Cost minimization, resource optimization with constraints
- **Planning**: Task sequencing with dependency and resource constraints
---
# nxus.SYSTEMS Documentation
URL: https://docs.nxus.systems/v0.9.2
import { CardGrid, LinkCard } from '@astrojs/starlight/components';
---
# GitHub Repositories
URL: https://docs.nxus.systems/v0.9.2/github
The public nxus.SYSTEMS GitHub organization is
[github.com/nxus-SYSTEMS](https://github.com/nxus-SYSTEMS).
## Public Repositories
| Repository | What to use it for |
| --- | --- |
| [nxusKit SDK](https://github.com/nxus-SYSTEMS/nxusKit) | Source for the multi-language SDK covering LLM providers, rule engines, constraint solving, Bayesian networks, decision tables, the C ABI, and CLI/Bash workflows. |
| [nxusKit Examples](https://github.com/nxus-SYSTEMS/nxusKit-examples) | Runnable Rust, Go, Python, and CLI/Bash examples for common nxusKit integration patterns. |
| [nxus Docs](https://github.com/nxus-SYSTEMS/nxus-docs) | Source for this public documentation site, hosted at [docs.nxus.systems](https://docs.nxus.systems/). |
## Related Links
- [nxusKit documentation](/nxuskit/)
- [nxusKit examples documentation](/nxuskit/examples/)
- [Commercial website](https://nxus.systems)
- [Plans](https://nxus.systems/pricing)
---
# nxusKit SDK
URL: https://docs.nxus.systems/v0.9.2/nxuskit
nxusKit is a unified, type-safe SDK for calling LLM providers (Claude, OpenAI, Ollama, and more),
CLIPS rule engines, Z3 constraint solvers, Bayesian networks, and ZEN decision tables — from Rust, Go, Python, and the C ABI.
## Start Here
Install the SDK, configure credentials, and run your first request:
- [Installation](/v0.9.2/nxuskit/getting-started/installation/)
- [First Call](/v0.9.2/nxuskit/getting-started/first-call/)
- [Authentication](/v0.9.2/nxuskit/getting-started/authentication/)
## Browse by Task
- **Build an integration** — Start with [installation](/v0.9.2/nxuskit/getting-started/installation/), then use the [provider model](/v0.9.2/nxuskit/concepts/provider-model/) to choose the right backend.
- **Explore working code** — Browse [examples](/v0.9.2/nxuskit/examples/) for reusable patterns, local model setup, solver workflows, and complete applications.
- **Author rules** — Use the [CLIPS rule authoring guide](/v0.9.2/nxuskit/guides/clips-rule-authoring/) and the [CLIPS session API](/v0.9.2/nxuskit/reference/api-reference/#clips-session-api).
- **Look up contracts** — Use the [API reference](/v0.9.2/nxuskit/reference/api/), [CLI reference](/v0.9.2/nxuskit/reference/cli-reference/), and [provider references](/v0.9.2/nxuskit/reference/providers/cloud-llms/).
- **Manage editions** — Review [feature tiers](/v0.9.2/nxuskit/concepts/tier-system/) and [license activation](/v0.9.2/nxuskit/concepts/licensing/).
---
# Architecture
URL: https://docs.nxus.systems/v0.9.2/nxuskit/concepts/architecture
## Overview
nxusKit is organized around a shared provider model with language-specific
wrappers for Rust, Go, and Python, plus a stable C ABI. Each wrapper exposes
native types while keeping the same core concepts: provider configuration, chat
requests, chat responses, streaming chunks, and structured error handling.
The architecture has four practical layers:
1. **Language wrappers** — Idiomatic SDK surfaces for application code.
2. **Provider abstraction** — A common contract for chat, streaming, capability
discovery, and provider metadata.
3. **Provider implementations** — Cloud LLMs, local LLMs, CLIPS, Z3, Mock,
Loopback, and MCP adapters.
4. **Native boundary** — C ABI functions and ownership rules for embedding and
cross-language integration.
## Component Map
| Component | Role |
|-----------|------|
| Rust SDK | Reference implementation, async provider interface, CLI, and native engine integrations. |
| Go SDK | Go-native provider interface with context cancellation and channel-based streaming. |
| Python SDK | Python-friendly provider creation, chat calls, and FFI access. |
| C ABI | Stable native boundary for providers, responses, streams, errors, and CLIPS sessions. |
| CLI | Shell interface for chat, provider checks, structured JSON workflows, and Pro features. |
| Examples | Runnable patterns and applications that demonstrate cross-language usage. |
## Provider Families
nxusKit providers fall into four broad groups:
| Family | Examples | Behavior |
|--------|----------|----------|
| Cloud LLMs | OpenAI, Anthropic, Groq, Mistral, Fireworks, Together, OpenRouter, Perplexity | Hosted model APIs with provider-specific capabilities. |
| Local LLMs | Ollama, LM Studio, in-process GGUF backends | Local inference for development, privacy, or low-latency use cases. |
| Deterministic engines | CLIPS, Z3 | Repeatable rule evaluation, inference, constraint solving, and optimization. |
| Utility providers | Mock, Loopback, MCP | Testing, integration checks, and tool-oriented workflows. |
See the [Provider Model](/v0.9.2/nxuskit/concepts/provider-model/) for the shared
configuration and request flow.
## Cross-Language Design
The SDK keeps concepts aligned across languages:
| Concept | Rust | Go | C ABI |
|---------|------|----|-------|
| Provider configuration | `ProviderConfig` | `ProviderConfig` | provider config JSON |
| Chat request | `ChatRequest` | `ChatRequest` | request JSON |
| Chat response | `ChatResponse` | `ChatResponse` | response handle + JSON |
| Streaming | async stream | channel stream | callback stream |
| Errors | typed errors | typed errors | `nxuskit_last_error()` |
This lets teams choose a language per service without redesigning provider
selection, request structure, credentials, or feature-gating behavior.
## Native Boundary
The C ABI is the stable integration point for native consumers and higher-level
FFI wrappers. It uses opaque handles for providers, responses, and streams. Any
memory returned across the boundary has a matching free function.
Read the [C ABI Reference](/v0.9.2/nxuskit/reference/api-reference/) before
embedding nxusKit in C, C++, Go FFI, Python FFI, or another native runtime.
## Operational Flow
```text
Application code
-> language wrapper or C ABI
-> provider configuration
-> chat or streaming request
-> provider implementation
-> response, chunks, metadata, or typed error
```
For Pro features, the same call path also checks license state before executing
the feature. Community-tier features continue to run without a license token.
## What to Read Next
- [Installation](/v0.9.2/nxuskit/getting-started/installation/)
- [Provider Model](/v0.9.2/nxuskit/concepts/provider-model/)
- [Streaming](/v0.9.2/nxuskit/guides/streaming/)
- [C ABI Reference](/v0.9.2/nxuskit/reference/api-reference/)
- [CLI Input Format Reference](/v0.9.2/nxuskit/reference/cli-reference/)
- [Examples](/v0.9.2/nxuskit/examples/)
---
# Licensing
URL: https://docs.nxus.systems/v0.9.2/nxuskit/concepts/licensing
## Overview
nxusKit Pro features require a valid license token. This guide covers the
full lifecycle: authentication, activation, deployment, renewal, and
deactivation.
## Quick Start
```bash
# 1. Authenticate with your nxus.systems account
nxuskit-cli license login
# 2. Activate with your purchase ID (received via email)
nxuskit-cli license activate --key
# 3. Verify activation
nxuskit-cli license status
# 4. Use Pro features — they just work
```
## Token Types
The SDK manages three types of tokens:
| Token | Storage | Purpose | Expiry | Machine-bound? |
|-------|---------|---------|--------|----------------|
| **Auth** | `~/.config/nxuskit/auth.json` | Authenticates you with the licensing service | 30 days | No |
| **Developer** | `~/.nxuskit/license.token` | Authorizes Pro features for local development | Subscription period | Yes (up to 3 machines) |
| **Deployment** | `NXUSKIT_LICENSE_TOKEN` env var | Authorizes Pro features in CI/CD and production | Never expires | No (org-scoped) |
## Step-by-Step Activation
### 1. Authenticate
Before activating a license, you must authenticate with your nxus.systems
account:
```bash
nxuskit-cli license login
```
This opens your browser to the nxus.systems login page. After logging in,
enter the code shown in your terminal. The auth token is stored at
`~/.config/nxuskit/auth.json` and used automatically for subsequent commands.
Check auth status:
```bash
nxuskit-cli license status
```
### 2. Activate
With authentication complete, activate your license:
```bash
nxuskit-cli license activate --key
```
On success you will see:
```
Activated. 1/3 machines used.
Token stored: ~/.nxuskit/license.token
```
The developer token is stored locally and validated on each SDK initialization.
### 3. Verify
Check your license status at any time:
```bash
nxuskit-cli license status
```
Output includes token type, edition, expiry date, and machine count.
For JSON output (useful in scripts):
```bash
nxuskit-cli license status --json
```
### 4. Use Pro Features
Once activated, Pro features work transparently:
```python
# Python — ZEN decision tables (Pro)
from nxuskit import zen_evaluate
result = zen_evaluate(table_path, input_data)
# Python — Solver (Pro)
from nxuskit import SolverConfig
```
```rust
// Rust — ZEN evaluation (Pro)
let result = nxuskit::zen_evaluate(&table, &input)?;
```
```go
// Go — Solver (Pro)
session, err := nxuskit.NewSolverSession(config)
```
## Trial Activation
To start a 30-day Pro trial, first register for an account and authenticate:
```bash
nxuskit-cli license login
nxuskit-cli license activate --trial
```
The trial provides full Pro-tier access for 30 days.
## Deployment Tokens
Deployment tokens are designed for production, CI/CD, and containerized
environments. They have no expiry and no machine binding.
### Setup
Set the deployment token as an environment variable:
```bash
export NXUSKIT_LICENSE_TOKEN=""
```
This works for:
* CI/CD pipelines (GitHub Actions, GitLab CI, Jenkins)
* Docker containers
* Kubernetes pods
* Production servers
* Serverless functions
### Version Ceiling
Deployment tokens include a **version ceiling** (e.g., `0.9`). The token
is valid for any SDK version at or below that ceiling:
* Token ceiling `0.9` → works with v0.9.0, v0.9.1, v0.9.5
* Token ceiling `0.9` → does NOT work with v0.10.0+
When you upgrade the SDK past the ceiling, you will see:
```
Deployment token covers up to v0.9.x. Update your deployment token for v0.10+ support.
```
Organizations with active support subscriptions receive updated deployment
tokens when new major.minor versions are released.
## Token Resolution Chain
The SDK resolves tokens from multiple sources in this precedence order:
| Priority | Source | Use Case |
|----------|--------|----------|
| 1 (highest) | `NXUSKIT_LICENSE_TOKEN` env var | CI/CD, containers |
| 2 | `~/.nxuskit/license.token` file | Local development |
| 3 (lowest) | API parameter | Embedded / programmatic |
The first valid token found is used. This order is the same for static and
dynamic linking modes.
## Multiple Machines
Each developer license supports up to 3 machine activations:
```bash
# Activate on machine 1
nxuskit-cli license activate --key
# → Activated. 1/3 machines used.
# Activate on machine 2
nxuskit-cli license activate --key
# → Activated. 2/3 machines used.
# If all 3 slots are used, deactivate one first:
nxuskit-cli deactivate
# → Deactivated. 2/3 machines used.
```
## Renewal
When your subscription approaches expiry (7 days out), the SDK logs a
once-per-session reminder:
```
Pro license expires in 7 days. Renew at your account dashboard.
```
After expiry, Pro features return:
```
License installation required.
```
Community features continue working without interruption.
## Deactivation
To free a machine activation slot:
```bash
nxuskit-cli deactivate
```
The local token file is removed and the activation count is decremented.
To revoke your auth session:
```bash
nxuskit-cli license logout
```
## Troubleshooting
| Symptom | Cause | Fix |
|---------|-------|-----|
| `License installation required.` | No valid license token found | Run `nxuskit-cli license login`, then `nxuskit-cli license activate --key ` |
| `LicenseExpired` | Subscription lapsed | Renew at your account dashboard |
| `EditionInsufficient` | Community binary | Download Pro binary |
| `VersionCeilingExceeded` | SDK upgraded past token ceiling | Request updated deployment token |
| `FeatureUnavailable` | Multiple possible causes | Run `nxuskit-cli license status` for details |
| Auth token expired | 30-day auth session ended | Run `nxuskit-cli license login` again |
---
# Provider Model
URL: https://docs.nxus.systems/v0.9.2/nxuskit/concepts/provider-model
## Overview
nxusKit presents LLMs, local inference servers, rule engines, solvers, and test
adapters through one provider interface. Your application chooses a
`provider_type`, sends a `ChatRequest`, and receives a structured response. The
same request/response pattern works whether the backend is OpenAI, Anthropic,
Ollama, CLIPS, Z3, Mock, or Loopback.
The goal is portability: application code can switch providers without changing
its surrounding orchestration, logging, retry, or licensing logic.
## Provider Types
| Category | Provider types | Use when |
|----------|----------------|----------|
| Cloud LLMs | `openai`, `claude`, `groq`, `mistral`, `fireworks`, `together`, `openrouter`, `perplexity` | You need hosted models, managed scaling, or provider-specific model quality. |
| Local LLMs | `ollama`, `lmstudio`, `local` | You need local inference, data locality, lower latency, or offline development. |
| Reasoning engines | `clips`, `z3` | You need deterministic rule evaluation, constraint solving, or explainable decisions. |
| Utility providers | `mock`, `loopback`, `mcp` | You need tests, integration checks, or model-context tooling. |
## Configuration Shape
All providers use the same high-level configuration fields:
```json
{
"provider_type": "openai",
"model": "gpt-4o",
"api_key": "sk-...",
"base_url": "https://api.openai.com/v1",
"timeout_ms": 30000,
"options": {}
}
```
Only `provider_type` is always required. API keys can come from explicit
configuration, environment variables, or the credential store. See
[Authentication](/v0.9.2/nxuskit/getting-started/authentication/) for the
precedence rules.
## Request Flow
1. Create a provider from configuration.
2. Build a chat request with a model name and messages.
3. Call `chat()` for a complete response or `chat_stream()` for incremental chunks.
4. Read response content and provider metadata.
```rust
use nxuskit::{ChatRequest, Message, NxuskitProvider, ProviderConfig};
let provider = NxuskitProvider::new(ProviderConfig {
provider_type: "openai".into(),
..Default::default()
})?;
let request = ChatRequest::new("gpt-4o")
.with_message(Message::user("Summarize the provider model."));
let response = provider.chat(request)?;
println!("{}", response.content);
```
## Capabilities
Providers advertise capabilities such as streaming, vision, JSON mode, tool
calling, deterministic seeds, and local model discovery. Use the capability
metadata to choose a provider at runtime instead of hard-coding assumptions.
For provider-specific details, see:
- [Cloud LLM Providers](/v0.9.2/nxuskit/reference/providers/cloud-llms/)
- [Local LLM Providers](/v0.9.2/nxuskit/reference/providers/local-llms/)
- [Expert System & Utility Providers](/v0.9.2/nxuskit/reference/providers/expert-systems/)
- [Z3 Constraint Satisfaction Provider](/v0.9.2/nxuskit/reference/providers/z3-solver/)
## Choosing a Provider
| Need | Start with |
|------|------------|
| General hosted chat, tools, and JSON output | Cloud LLM provider |
| Local development without external API calls | Ollama or LM Studio |
| Embedded local inference with direct model lifecycle control | In-process local provider |
| Deterministic business rules | CLIPS |
| Constraint solving and optimization | Z3 |
| Unit tests with predictable responses | Mock or Loopback |
---
# Tier System
URL: https://docs.nxus.systems/v0.9.2/nxuskit/concepts/tier-system
## Overview
nxusKit ships in three editions. **Community** is free and open-source.
**Pro** unlocks advanced reasoning engines, plugin infrastructure, and
deployment-ready licensing for commercial applications. **Enterprise**
adds delegated trust and custom plugin configuration for large organizations.
## Feature Matrix
| Feature Domain | Community | Pro | Enterprise |
|----------------|:---------:|:---:|:----------:|
| LLM Cloud Providers (OpenAI, Claude, Groq, Mistral, Fireworks, Together, OpenRouter, Perplexity) | Yes | Yes | Yes |
| LLM Local Providers (Ollama, LM Studio) | Yes | Yes | Yes |
| CLIPS Rule Engine (ClipsSession API) | Yes | Yes | Yes |
| Bayesian Network Inference | Yes | Yes | Yes |
| Auth Helper (API-key management, credential store) | Yes | Yes | Yes |
| Tool Calling / Function Calling | Yes | Yes | Yes |
| Streaming & Token Usage | Yes | Yes | Yes |
| Retry & Adaptive Rate Limiting | Yes | Yes | Yes |
| Vision / Image Support | Yes | Yes | Yes |
| OAuth Authentication Infrastructure | Yes | Yes | Yes |
| Cross-language Parity (Rust, Go, Python) | Yes | Yes | Yes |
| Static + Dynamic Linking | Yes | Yes | Yes |
| **ZEN Decision Tables** | — | Yes | Yes |
| **Constraint Solver (Z3-backed)** | — | Yes | Yes |
| **Plugin Loading & Trust Policy** | — | Yes | Yes |
| **MCP (Model Context Protocol)** | — | Yes | Yes |
| **CLIPS Advanced (programmatic rules, session persistence)** | — | Yes | Yes |
| **Custom Plugin Configuration Paths** | — | — | Yes |
| **Delegated Trust Roots** | — | — | Yes |
| **Priority Support** | — | — | Yes |
## Numerical Limits
| Limit | Community | Pro | Enterprise |
|-------|:---------:|:---:|:----------:|
| Max concurrent CLIPS sessions | 16 | 64 | 256 |
| Max cached rulebases | 8 | 32 | 128 |
| Max rules per session | 500 | 5,000 | 50,000 |
| Max facts per session | 10,000 | 100,000 | 1,000,000 |
| Max Bayesian network nodes | 50 | 500 | 5,000 |
| Max solver constraints | — | 10,000 | 100,000 |
| Machine activations (developer tokens) | — | 3 | Unlimited |
## SDK Wrapper Availability
All editions provide wrappers for all three languages:
| Language | Package | Install |
|----------|---------|---------|
| Rust | `nxuskit` | `cargo add nxuskit` |
| Go | `nxuskit` | `go get github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go` |
| Python | `nxuskit-py` | `pip install nxuskit-py` |
## Example Tier Assignments
| Example | Tier | Reason |
|---------|------|--------|
| LLM basics, streaming, tool calling | Community | Uses cloud/local LLM providers |
| CLIPS basics, CLIPS-LLM hybrid | Community | CLIPS engine is Community-tier |
| Bayesian network inference | Community | BN inference is Community-tier |
| Solver examples | **Pro** | Use the Z3 constraint solver |
| Solver what-if examples | **Pro** | Use scoped Z3 optimization |
| LLM-solver hybrid examples | **Pro** | Combine LLM reasoning with Z3 solving |
| ZEN decision examples | **Pro** | Use ZEN decision tables |
## Licensing
| Aspect | Community | Pro | Enterprise |
|--------|-----------|-----|------------|
| License type | Open-source | Commercial subscription | Commercial subscription |
| Token required | No | Yes (developer or deployment) | Yes |
| Machine activations | N/A | Up to 3 per license | Unlimited |
| Deployment tokens | N/A | Unlimited instances, no per-seat fees | Unlimited |
| Version ceiling | N/A | Locked to major.minor at purchase time | Locked to major.minor |
| Trial | N/A | 30-day trial (registration required) | Contact sales |
## Getting Started with Pro
1. Create an account and register for a trial or purchase a license
2. Authenticate: `nxuskit-cli license login`
3. Activate on your machine: `nxuskit-cli license activate --key `
4. For CI/CD: set `NXUSKIT_LICENSE_TOKEN` with your deployment token
See [Licensing](/v0.9.2/nxuskit/concepts/licensing/) for the full activation workflow.
---
# Examples
URL: https://docs.nxus.systems/v0.9.2/nxuskit/examples
**[nxus.SYSTEMS](https://nxus.systems)** · **[Examples Portfolio](https://nxus.systems/examples)** · **[nxusKit SDK](https://github.com/nxus-SYSTEMS/nxusKit)**
32 production examples for the nxusKit SDK in Rust, Go, and Python — covering LLM patterns, CLIPS rule engines, Z3 constraint solvers, Bayesian networks, and ZEN decision tables.
## Quick Start
```bash
# 1. Install the SDK (see nxusKit Getting Started guide)
# 2. Set up this project
source ~/.nxuskit/sdk/current/scripts/setup-sdk.sh
# 3. Run an example
cargo run --manifest-path examples/patterns/basic-chat/rust/Cargo.toml # Rust
go run -tags nxuskit ./examples/patterns/basic-chat/go # Go
python examples/patterns/basic-chat/python/main.py # Python
```
## Examples
### Patterns — Reusable SDK integration patterns
| Example | Description | Languages |
|---------|-------------|-----------|
| [basic-chat](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/basic-chat/) | Simple chat with any LLM provider | Rust, Go, Python |
| [streaming](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/streaming/) | Streaming responses | Rust, Go, Python |
| [multi-provider](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/multi-provider/) | Switch between providers | Rust, Go, Python |
| [auth-helper](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/auth-helper/) | OAuth and credential management | Rust (CLI + GUI), Go |
| [vision](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/vision/) | Image/vision capabilities | Rust, Go, Python |
| [solver](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/solver/) | Z3 constraint solving | Rust, Go, Python |
| [cost-routing](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/cost-routing/) | Route requests by cost/capability | Rust, Go |
| [retry-fallback](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/retry-fallback/) | Retry with provider fallback | Rust, Go |
### Integrations — Combining SDK features
| Example | Description | Languages |
|---------|-------------|-----------|
| [clips-basics](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/integrations/clips-basics/) | CLIPS expert system fundamentals | Rust, Go |
| [clips-llm-hybrid](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/integrations/clips-llm-hybrid/) | CLIPS rules + LLM reasoning | Rust, Go |
| [zen-decisions](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/integrations/zen-decisions/) | ZEN decision table evaluation | Rust, Go |
| [bn-solver-clips-pipeline](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/integrations/bn-solver-clips-pipeline/) | Bayesian → Solver → CLIPS pipeline | Rust, Go |
| [ollama](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/integrations/ollama/) | Local LLM via Ollama | Rust, Go |
### Apps — Complete applications
| Example | Description | Languages |
|---------|-------------|-----------|
| [racer](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/apps/racer/) | CLIPS vs LLM head-to-head race | Rust, Go |
| [arbiter](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/apps/arbiter/) | Auto-retry LLM with CLIPS validation | Rust, Go |
| [puzzler](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/apps/puzzler/) | Sudoku and Set Game solving via CLIPS | Rust, Go |
| [ruler](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/apps/ruler/) | LLM-generated CLIPS rules | Rust, Go |
| [riffer](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/apps/riffer/) | Music analysis with CLIPS + LLM | Rust, Go |
## SDK Editions
| Badge | Meaning |
|-------|---------|
| **Community** | Runs with the free OSS SDK |
| **Pro** | Requires a Pro license ([activation guide](https://github.com/nxus-SYSTEMS/nxusKit)) |
See `conformance/example-tiers.json` for the full tier map.
## Project Structure
```
examples/
├── patterns/ Community-tier reusable patterns
├── integrations/ SDK feature combinations
├── apps/ Complete applications (mostly Pro tier)
└── shared/ Shared libraries (Rust, Go, interactive utilities)
conformance/ Example manifest and tier definitions
scripts/ Build and test helpers
```
## Building
All examples require the nxusKit SDK. Run `setup-sdk.sh` once after cloning:
```bash
source ~/.nxuskit/sdk/current/scripts/setup-sdk.sh
```
This creates the necessary symlinks and sets environment variables for Rust (`packages/nxuskit`), Go (`go.work`), and native library paths.
### Rust
```bash
export NXUSKIT_SDK_DIR=~/.nxuskit/sdk/current
cargo run --manifest-path examples///rust/Cargo.toml
```
### Go
```bash
go run -tags nxuskit ./examples///go/cmd
```
### Python
```bash
python examples///python/main.py
```
## License
Dual-licensed under [MIT](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE-MIT) or [Apache-2.0](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE-APACHE).
---
# Authentication
URL: https://docs.nxus.systems/v0.9.2/nxuskit/getting-started/authentication
## Overview
nxusKit supports multiple authentication methods depending on the provider.
This matrix shows which methods are available for each provider and how to
configure them.
## Provider Matrix
| Provider | Auth Required | API Key | OAuth | Env Variable | Dashboard |
|----------|:------------:|:-------:|:-----:|--------------|-----------|
| OpenAI / GPT | Yes | Yes | — | `OPENAI_API_KEY` | [platform.openai.com/api-keys](https://platform.openai.com/api-keys) |
| Anthropic / Claude | Yes | Yes | — | `ANTHROPIC_API_KEY` | [console.anthropic.com/settings/keys](https://console.anthropic.com/settings/keys) |
| Groq | Yes | Yes | — | `GROQ_API_KEY` | [console.groq.com/keys](https://console.groq.com/keys) |
| Mistral AI | Yes | Yes | — | `MISTRAL_API_KEY` | [console.mistral.ai/api-keys](https://console.mistral.ai/api-keys) |
| Fireworks AI | Yes | Yes | — | `FIREWORKS_API_KEY` | [fireworks.ai/account/api-keys](https://fireworks.ai/account/api-keys) |
| Together AI | Yes | Yes | — | `TOGETHER_API_KEY` | [api.together.ai/settings/api-keys](https://api.together.ai/settings/api-keys) |
| OpenRouter | Yes | Yes | — | `OPENROUTER_API_KEY` | [openrouter.ai/settings/keys](https://openrouter.ai/settings/keys) |
| Perplexity | Yes | Yes | — | `PERPLEXITY_API_KEY` | [perplexity.ai/settings/api](https://www.perplexity.ai/settings/api) |
| Ollama | No | — | — | `OLLAMA_HOST` | — |
| LM Studio | No | — | — | `LMSTUDIO_HOST` | — |
**Legend**: Yes = supported, — = not applicable
## Authentication Methods
### API Key
The standard authentication method for cloud providers. Obtain a key from
the provider's dashboard, then configure via any of these methods:
**Environment variable** (recommended for development and CI/CD):
```bash
export OPENAI_API_KEY="sk-..."
```
**Credential store** (recommended for persistent local development):
```bash
nxuskit-cli provider set openai sk-...
```
This stores the key in the OS credential store (macOS Keychain, Windows
Credential Manager, or Linux secret-service). Falls back to a file-based
store with 0600 permissions if no system store is available.
**Explicit parameter** (for programmatic use):
```python
provider = Provider.create("openai", api_key="sk-...")
```
### OAuth
OAuth support is available for providers that require browser-based
authorization. The current cloud providers use API keys, so most projects will
not need this flow. When a provider requires OAuth, use:
```bash
# Start OAuth login
nxuskit-cli provider login
# Check auth status
nxuskit-cli provider status
```
The OAuth flow uses:
* PKCE (SHA-256 code challenge) for security
* Localhost callback on an ephemeral port
* State/CSRF validation
* Automatic browser launch
### No Authentication
Local providers (Ollama, LM Studio) run on the local machine and do not
require authentication. The host env variable is optional and defaults to
`localhost` on the provider's default port.
## Credential Precedence
When multiple credential sources exist, the SDK uses this precedence order:
| Priority | Source | Example |
|----------|--------|---------|
| 1 (highest) | Explicit API parameter | `Provider.create("openai", api_key="sk-...")` |
| 2 | Environment variable | `OPENAI_API_KEY=sk-...` |
| 3 (lowest) | OS credential store | Via `nxuskit-cli provider set` |
## Checking Auth Status
View authentication status for all providers:
```bash
nxuskit-cli provider status
```
For a specific provider:
```bash
nxuskit-cli provider status openai
```
JSON output (for scripts):
```bash
nxuskit-cli provider status --json
```
Example output:
```
Provider Status Source Auth Methods
─────────────────────────────────────────────────────────────
openai Authenticated env api_key
claude Authenticated store api_key
groq Not authenticated — api_key
ollama Not required — —
lm-studio Not required — —
```
## Managing Credentials
```bash
# Store a credential
nxuskit-cli provider set
# Remove a stored credential
nxuskit-cli provider remove
# View status
nxuskit-cli provider status [provider]
```
## Per-Language Configuration
### Rust
```rust
use nxuskit::{auth_status, auth_set_credential, auth_resolve};
// Check status
let status = auth_status("openai")?;
// Store credential
auth_set_credential("openai", "sk-...")?;
// Resolve credential (follows precedence chain)
let resolution = auth_resolve("openai", None)?;
```
### Go
```go
import "github.com/nxus-SYSTEMS/nxuskit-go"
// Check status
status, err := nxuskit.AuthStatus("openai")
// Store credential
err = nxuskit.AuthSetCredential("openai", "sk-...")
// Resolve credential
resolution, err := nxuskit.AuthResolve("openai", "")
```
### Python
```python
from nxuskit import auth_status, auth_set_credential, auth_resolve
# Check status
status = auth_status("openai")
# Store credential
auth_set_credential("openai", "sk-...")
# Resolve credential
resolution = auth_resolve("openai")
```
---
# First Call
URL: https://docs.nxus.systems/v0.9.2/nxuskit/getting-started/first-call
This guide assumes you have installed the SDK and configured at least one
provider credential. If you have not done that yet, start with
[Installation](/v0.9.2/nxuskit/getting-started/installation/) and
[Authentication](/v0.9.2/nxuskit/getting-started/authentication/).
## Fastest Path: CLI
Set a provider API key, then send a single chat request:
```bash
export OPENAI_API_KEY="sk-..."
nxuskit-cli chat \
--provider openai \
--model gpt-4o \
"Say hello from nxusKit in one sentence."
```
For structured shell workflows, use the Level 1 `call` command:
```bash
echo '{"provider":"openai","model":"gpt-4o","prompt":"Say hello from nxusKit."}' \
| nxuskit-cli call --input - --format json
```
## Rust
Use the Rust wrapper bundled with the SDK as a path dependency:
```toml
# Cargo.toml
[dependencies]
nxuskit = { path = "/absolute/path/to/nxuskit-sdk-{version}-{platform}/rust" }
```
```rust
use nxuskit::{ChatRequest, Message, NxuskitProvider, ProviderConfig};
fn main() -> Result<(), nxuskit::NxuskitError> {
let provider = NxuskitProvider::new(ProviderConfig {
provider_type: "openai".into(),
..Default::default()
})?;
let request = ChatRequest::new("gpt-4o")
.with_message(Message::user("Say hello from Rust."))
.with_max_tokens(100);
let response = provider.chat(request)?;
println!("{}", response.content);
Ok(())
}
```
## Go
Add the Go wrapper and alias the package as `nxuskit` in your import block:
```bash
go get github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go
```
```go
package main
import (
"context"
"fmt"
"os"
nxuskit "github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go"
)
func main() {
provider, err := nxuskit.NewOpenAIProvider(
nxuskit.WithAPIKey(os.Getenv("OPENAI_API_KEY")),
)
if err != nil {
panic(err)
}
req := nxuskit.ChatRequest{
Model: "gpt-4o",
Messages: []nxuskit.Message{
{Role: nxuskit.RoleUser, Content: "Say hello from Go."},
},
}
resp, err := provider.Chat(context.Background(), req)
if err != nil {
panic(err)
}
fmt.Println(resp.Content)
}
```
## Python
Install the Python wrapper, then create a provider and call it:
```bash
pip install nxuskit-py
```
```python
from nxuskit import Provider
provider = Provider.create("openai")
response = provider.chat(
model="gpt-4o",
messages=[{"role": "user", "content": "Say hello from Python."}],
max_tokens=100,
)
print(response.content)
```
## C
The SDK bundle includes `include/nxuskit.h` and platform libraries under
`lib/`. Compile against those files and set the provider API key in the
environment:
```bash
export OPENAI_API_KEY="sk-..."
cc -I "$NXUSKIT_SDK_DIR/include" \
-o basic_chat basic_chat.c \
-L "$NXUSKIT_SDK_DIR/lib" \
-lnxuskit \
-Wl,-rpath,"$NXUSKIT_SDK_DIR/lib"
```
Use the [C ABI Reference](/v0.9.2/nxuskit/reference/api-reference/) for function,
ownership, and error-handling details.
## Local Providers
Local providers do not require API keys:
```bash
# Ollama default
export OLLAMA_HOST="http://localhost:11434"
# LM Studio default
export LMSTUDIO_HOST="http://localhost:1234/v1"
```
Use [Local LLM Providers](/v0.9.2/nxuskit/reference/providers/local-llms/) for
model setup and provider-specific options.
## Next Steps
| Goal | Read |
|------|------|
| Configure credentials | [Authentication](/v0.9.2/nxuskit/getting-started/authentication/) |
| Browse runnable projects | [Examples](/v0.9.2/nxuskit/examples/) |
| Stream responses | [Streaming](/v0.9.2/nxuskit/guides/streaming/) |
| Choose a provider | [Provider Model](/v0.9.2/nxuskit/concepts/provider-model/) |
| Use CLI JSON contracts | [CLI Input Format Reference](/v0.9.2/nxuskit/reference/cli-reference/) |
| Integrate through native boundaries | [C ABI Reference](/v0.9.2/nxuskit/reference/api-reference/) |
---
# Installation
URL: https://docs.nxus.systems/v0.9.2/nxuskit/getting-started/installation
This guide walks you through downloading, installing, and using the nxuskit SDK
to call LLM providers from Rust, Go, Python, or the C ABI.
## Prerequisites
* GitHub account with access to nxusKit SDK releases
* [GitHub CLI](https://cli.github.com/) (`gh`) installed and authenticated
## 1. Download and Install the SDK
### macOS (Apple Silicon)
```bash
# Download, extract, and remove macOS quarantine in one go
gh release download --repo nxus-SYSTEMS/nxusKit \
--pattern "nxuskit-sdk-*-macos-arm64.tar.gz" \
--pattern "nxuskit-sdk-*-macos-arm64.tar.gz.sha256"
shasum -a 256 -c nxuskit-sdk-*-macos-arm64.tar.gz.sha256
tar xzf nxuskit-sdk-*-macos-arm64.tar.gz
xattr -dr com.apple.quarantine nxuskit-sdk-*/
```
The `xattr` step removes the Gatekeeper quarantine flag that macOS applies to
downloaded files. Without it you'll get "can't be opened because Apple cannot
check it for malicious software" when loading the dylib.
### Linux (x86\_64)
```bash
gh release download --repo nxus-SYSTEMS/nxusKit \
--pattern "nxuskit-sdk-*-linux-x86_64.tar.gz" \
--pattern "nxuskit-sdk-*-linux-x86_64.tar.gz.sha256"
sha256sum -c nxuskit-sdk-*-linux-x86_64.tar.gz.sha256
tar xzf nxuskit-sdk-*-linux-x86_64.tar.gz
```
### Windows (x86\_64)
```powershell
gh release download --repo nxus-SYSTEMS/nxusKit `
--pattern "nxuskit-sdk-*-windows-x86_64.zip" `
--pattern "nxuskit-sdk-*-windows-x86_64.zip.sha256"
# Extract
Expand-Archive nxuskit-sdk-*-windows-x86_64.zip -DestinationPath .
```
### Set SDK Path
After extracting, set the SDK path. **Use an absolute path** — relative paths
can fail because `cargo` and other tools may change the working directory during
builds.
```bash
# Get the absolute path to the extracted SDK directory
export NXUSKIT_SDK_DIR="$(cd nxuskit-sdk-*/ && pwd)"
echo "NXUSKIT_SDK_DIR=${NXUSKIT_SDK_DIR}"
```
To persist across sessions, add to your shell profile (`~/.bashrc`, `~/.zshrc`,
etc.):
```bash
export NXUSKIT_SDK_DIR="/absolute/path/to/nxuskit-sdk-{version}-{platform}"
```
For CI systems, see [Download via PAT](#download-via-pat) below.
## 2. SDK Bundle Contents
```
nxuskit-sdk-{version}-{platform}/
├── include/
│ └── nxuskit.h # C header — all API declarations
├── lib/
│ ├── libnxuskit.so # Shared library (Linux)
│ │ libnxuskit.dylib # Shared library (macOS)
│ │ nxuskit.dll # Shared library (Windows)
│ ├── libnxuskit.a # Static library (Linux/macOS)
│ │ nxuskit.lib # Static library (Windows)
│ └── nxuskit.dll.lib # Import library (Windows only)
├── rust/ # nxuskit Rust SDK wrapper (use as path dependency)
├── docs/ # This documentation
└── examples/ # Working examples in C, Rust, Go, Python
```
## 3. First Example — C
Set your provider API key, then compile and run:
```bash
export OPENAI_API_KEY="sk-..." # or ANTHROPIC_API_KEY, etc.
cd nxuskit-sdk-*/examples/c
make basic_chat
./bin/basic_chat
```
The SDK bundle includes this source at `examples/c/basic_chat.c`.
## 4. First Example — Go
```bash
export OPENAI_API_KEY="sk-..."
cd nxuskit-sdk-*/examples/go
go run basic_chat.go
```
The SDK bundle includes this source at `examples/go/basic_chat.go`.
## 5. First Example — Rust
The SDK bundles `nxuskit`, a safe Rust wrapper. Add it as a path dependency
in your `Cargo.toml` using the **absolute path** to the SDK's `rust/` directory:
```toml
# Cargo.toml
[dependencies]
nxuskit = { path = "/Users/you/nxuskit-sdk-{version}-{platform}/rust" }
```
Then set your environment and run:
```bash
# NXUSKIT_SDK_DIR tells the wrapper where to find libnxuskit at runtime.
# Must be an absolute path (relative paths are unreliable across tools).
export NXUSKIT_SDK_DIR="/Users/you/nxuskit-sdk-{version}-{platform}"
export OPENAI_API_KEY="sk-..."
cargo run
```
```rust
use nxuskit::{ChatRequest, Message, NxuskitProvider, ProviderConfig};
fn main() -> Result<(), nxuskit::NxuskitError> {
let provider = NxuskitProvider::new(ProviderConfig {
provider_type: "openai".into(),
..Default::default()
})?;
let request = ChatRequest::new("gpt-4o")
.with_message(Message::user("Hello from Rust!"))
.with_max_tokens(100);
let response = provider.chat(request)?;
println!("{}", response.content);
Ok(())
}
```
**Path troubleshooting:** If you see `LibraryNotFound`, verify:
1. `NXUSKIT_SDK_DIR` is set and is an absolute path (check with `echo $NXUSKIT_SDK_DIR`)
2. The `lib/` subdirectory exists: `ls $NXUSKIT_SDK_DIR/lib/`
3. On macOS: quarantine was removed (see Step 1 above)
The SDK bundle includes a runnable Rust project under `examples/rust/` and
wrapper documentation under `rust/`.
## 6. First Example — Python
```bash
pip install nxuskit-py
export OPENAI_API_KEY="sk-..."
python examples/python/basic_chat.py
```
The SDK bundle includes this source at `examples/python/basic_chat.py`.
## Core Concepts
### JSON-in / JSON-out
All data crosses the FFI boundary as JSON strings. You send a JSON config to
create a provider, send a JSON request for chat, and receive a JSON response.
### Provider Lifecycle
```
create_provider(config_json) → provider handle
↓
chat(provider, request_json) → response handle → response_json(response) → JSON
↓
free_response(response)
free_provider(provider)
```
### Streaming
```
chat_stream(provider, request_json, on_chunk, on_done, user_data) → stream handle
↓ (callbacks fire from background thread)
on_chunk(chunk_json, user_data) ← called per chunk
on_done(final_json, user_data) ← called once at end
↓
free_stream(stream)
```
### Thread Safety
* All `nxuskit_*` functions are thread-safe
* Provider handles can be shared across threads
* Error messages are thread-local (`nxuskit_last_error()`)
### Supported Providers
| Provider | Config `provider_type` | Required Env Var |
|----------|----------------------|------------------|
| OpenAI | `openai` | `OPENAI_API_KEY` |
| Anthropic Claude | `claude` | `ANTHROPIC_API_KEY` |
| Ollama | `ollama` | `OLLAMA_HOST` (optional) |
| LM Studio | `lmstudio` | — |
| Groq | `groq` | `GROQ_API_KEY` |
| Fireworks | `fireworks` | `FIREWORKS_API_KEY` |
| Together | `together` | `TOGETHER_API_KEY` |
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` |
| Perplexity | `perplexity` | `PERPLEXITY_API_KEY` |
| Mistral | `mistral` | `MISTRAL_API_KEY` |
| CLIPS | `clips` | — |
| MCP | `mcp` | — |
| Mock (testing) | `mock` | — |
| Loopback (testing) | `loopback` | — |
### CLIPS Quick Start
CLIPS runs in-process (no API key needed). Create a provider with
`provider_type: "clips"` and `model` pointing to your rules directory. Send
facts as JSON in the user message:
```c
const char *input = "{\"facts\": [{\"template\": \"sensor\", \"values\": {\"name\": \"temp\", \"value\": 150}}]}";
// ... create provider, build request with input as user message, call nxuskit_chat()
```
The user message must conform to the `ClipsInput` schema — see the
[Rule Authoring Guide](/v0.9.2/nxuskit/guides/clips-rule-authoring/#clipsinput-json-reference) for the full
field reference. CLIPS also provides a session API for direct engine access; see
the [C ABI Reference](/v0.9.2/nxuskit/reference/api-reference/#clips-session-api).
## Linking Reference
### GCC / Clang (dynamic)
```bash
cc -I sdk/include -o myapp myapp.c -L sdk/lib -lnxuskit -Wl,-rpath,sdk/lib
```
### GCC / Clang (static)
```bash
cc -I sdk/include -o myapp myapp.c sdk/lib/libnxuskit.a -lpthread -ldl -lm
```
### MSVC (dynamic — recommended)
```
cl /I sdk\include myapp.c /link sdk\lib\nxuskit.dll.lib
```
### MSVC (static)
```
cl /I sdk\include myapp.c /link sdk\lib\nxuskit.lib ucrt.lib userenv.lib ntdll.lib ws2_32.lib bcrypt.lib advapi32.lib
```
### CGo
```go
// #cgo CFLAGS: -I${SRCDIR}/sdk/include
// #cgo linux LDFLAGS: -L${SRCDIR}/sdk/lib -lnxuskit -Wl,-rpath,${SRCDIR}/sdk/lib
// #cgo darwin LDFLAGS: -L${SRCDIR}/sdk/lib -lnxuskit -Wl,-rpath,${SRCDIR}/sdk/lib
// #cgo windows LDFLAGS: -L${SRCDIR}/sdk/lib -lnxuskit
// #include "nxuskit.h"
import "C"
```
### Python (cffi)
```python
from cffi import FFI
ffi = FFI()
ffi.cdef(open("sdk/include/nxuskit.h").read())
lib = ffi.dlopen("sdk/lib/libnxuskit.so") # or .dylib / .dll
```
## Download via PAT
For CI systems that can't use `gh`:
1. Create a fine-grained PAT at https://github.com/settings/personal-access-tokens
* **Repository access**: Select `nxus-SYSTEMS/nxusKit`
* **Permissions**: Contents → Read-only
2. Use the token:
```bash
export GH_TOKEN="github_pat_..."
# List available SDK releases
curl -H "Authorization: Bearer $GH_TOKEN" \
"https://api.github.com/repos/nxus-SYSTEMS/nxusKit/releases?per_page=5" \
| jq '.[].tag_name'
# Download a specific asset
curl -L -H "Authorization: Bearer $GH_TOKEN" \
-H "Accept: application/octet-stream" \
"https://api.github.com/repos/nxus-SYSTEMS/nxusKit/releases/assets/{ASSET_ID}" \
-o nxuskit-sdk.tar.gz
```
## Next Steps
* [C ABI Reference](/v0.9.2/nxuskit/reference/api-reference/) — full C ABI documentation
* [Cloud Provider Reference](/v0.9.2/nxuskit/reference/providers/cloud-llms/) — hosted LLM configuration
* [Local Provider Reference](/v0.9.2/nxuskit/reference/providers/local-llms/) — local inference configuration
* [Rule Authoring Guide](/v0.9.2/nxuskit/guides/clips-rule-authoring/) — writing, testing, and deploying custom CLIPS rules
* [Examples](/v0.9.2/nxuskit/examples/) — working code for SDK languages and CLI/Bash workflows
---
# CLIPS Rule Authoring Guide
URL: https://docs.nxus.systems/v0.9.2/nxuskit/guides/clips-rule-authoring
This guide explains how to write, test, and deploy custom CLIPS rules with the nxusKit SDK.
## CLIPS Rule Syntax
nxusKit uses CLIPS 6.4, a forward-chaining inference engine. Rules follow the pattern:
```text
(defrule rule-name
"Documentation string"
;; LHS: conditions (pattern matching)
(template-name (slot-name ?variable))
(test (< ?variable 100))
=>
;; RHS: actions (assertions, side effects)
(assert (alert
(alert-type "threshold_exceeded")
(severity "warning")
(message (str-cat "Value " ?variable " is out of range"))
(recommendation "Check your input data")
(entity-id ?id)
(rule-name "rule-name")
(module-name "data-qc"))))
```
## Defining Templates
Templates define the fact schemas your rules operate on. Define them in shared template files loaded before any module rules:
```text
;;; shared/000-core.clp — Core templates
(deftemplate input-data
"A single data record to evaluate"
(slot record-id (type INTEGER))
(slot value (type FLOAT))
(slot category (type STRING))
(slot confidence (type FLOAT) (range 0.0 1.0)))
(deftemplate threshold-config
"Configurable thresholds for QC checks"
(slot value-min (type FLOAT))
(slot value-max (type FLOAT))
(slot confidence-min (type FLOAT) (default 0.5)))
(deftemplate alert
"Output: a raised alert from rule inference"
(slot alert-type (type STRING))
(slot severity (type STRING)) ;; "critical", "high", "warning", "info"
(slot message (type STRING))
(slot recommendation (type STRING))
(slot entity-id (type INTEGER))
(slot rule-name (type STRING))
(slot module-name (type STRING)))
```
## Modules
CLIPS modules provide namespace isolation for rules. Each module groups related rules:
```text
;;; In data-qc/bounds-check.clp
(defmodule data-qc (export ?ALL))
(defrule bounds-check
"Flag records outside configured bounds"
(threshold-config (value-min ?vmin) (value-max ?vmax))
(input-data (record-id ?rid) (value ?v&:(or (< ?v ?vmin) (> ?v ?vmax))))
=>
(assert (alert
(alert-type "out_of_bounds")
(severity "high")
(message (str-cat "Record " ?rid " value " ?v " outside [" ?vmin "-" ?vmax "]"))
(recommendation "Verify input data or adjust thresholds")
(entity-id ?rid)
(rule-name "bounds-check")
(module-name "data-qc"))))
```
## Directory Structure
Organize rules with shared templates loaded first, then per-module rule files:
```
rules/
shared/ # Shared templates (loaded first, alphabetically)
000-core.clp # input-data, threshold-config, alert
010-domain.clp # Additional domain-specific templates
data-qc/ # Data quality checks
bounds-check.clp
confidence-check.clp
classification/ # Classification rules
category-classifier.clp
custom/ # User-defined rules
my-custom-check.clp
```
## CLIPS Integration Paths
nxusKit provides two ways to use CLIPS:
* **Provider chat** — CLIPS as a standard chat provider. Send `ClipsInput` JSON
as the user message; receive `ClipsOutput` JSON in the response content.
Best for request/response workflows and cross-language portability.
* **Session API** — Direct engine access via `ClipsSession` (Rust, Go, Python)
or the C ABI (`nxuskit_clips_session_*`). Best for interactive, multi-step
rule authoring, debugging, and fine-grained fact manipulation.
This guide focuses on the **provider chat** path. For the session API, see the
[C ABI Reference](/v0.9.2/nxuskit/reference/api-reference/#clips-session-api).
## ClipsInput JSON Reference
The user message JSON must conform to the `ClipsInput` schema. Unknown fields
are rejected (the engine uses strict deserialization).
```json
{
"facts": [
{"template": "sensor", "values": {"name": "temp-1", "value": 150}}
],
"templates": [
{"name": "alert", "slots": [{"name": "type", "type": "STRING"}, {"name": "severity", "type": "STRING"}]}
],
"rules": [
{"name": "high-temp", "source": "(defrule high-temp (sensor (value ?v&:(> ?v 100))) => (assert (alert (type \"over-threshold\") (severity \"high\"))))"}
],
"config": {
"max_rules": 1000,
"include_trace": true,
"derived_only_new": true
},
"focus": ["data-qc"],
"globals": {"*threshold*": 100}
}
```
All fields are optional. The minimal valid input is `{}` (empty object).
| Field | Type | Description |
|-------|------|-------------|
| `facts` | array of `{template, values}` | Facts to assert before running inference |
| `templates` | array of `{name, slots}` | Templates to create (if not in rule base) |
| `rules` | array of `{name, source}` or `{name, conditions, actions}` | Rules to create programmatically |
| `config` | object | Request-level overrides (see below) |
| `focus` | array of strings | Module focus stack (controls which rules fire) |
| `globals` | object | Global variable values to set |
| `command` | string | Special command: `"reset"`, `"clear"`, `"retract"` |
| `modules` | array of `{name, doc, imports}` | Modules to create |
| `policy_id` | string | Cache key for session reuse |
**Config fields:**
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `max_rules` | integer | -1 (unlimited) | Maximum rules to fire |
| `include_trace` | boolean | false | Include rule firing trace in output |
| `derived_only_new` | boolean | false | Only return newly derived facts |
| `output_templates` | array of strings | all | Only return facts matching these templates |
## Rule Loading
nxusKit's CLIPS provider loads rules through the `ClipsInput` configuration. Rules can be loaded from:
1. **Text strings** — CLIPS source passed directly via `rules_text`
2. **File paths** — `.clp` files loaded at runtime via `rules` array
3. **Binary images** — Pre-compiled `.bin` files via `binary_rules`
### Loading Order
1. Shared templates are loaded first (alphabetically by filename)
2. Module rules are loaded next, in the order specified by the `focus` configuration
3. User override rules are loaded last (taking precedence)
### Rust Example
```rust
use nxuskit::{AsyncProvider, ChatRequest, Message, NxuskitProvider, ProviderConfig};
let config = ProviderConfig {
provider_type: "clips".into(),
model: Some("/path/to/rules".into()),
..Default::default()
};
let provider = NxuskitProvider::new(config)?;
let request = ChatRequest::new("clips")
.with_message(Message::user(r#"{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 150.0}}]}"#))
.with_provider_options(serde_json::json!({
"focus": ["data-qc"],
"derived_only_new": true
}));
let response = provider.chat(request).await?;
println!("Alerts: {}", response.content);
```
### Go Example
```go
import nxuskit "github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go"
config := nxuskit.ProviderConfig{
ProviderType: "clips",
Model: strPtr("/path/to/rules"),
}
provider, _ := nxuskit.NewProvider(config)
request := nxuskit.NewChatRequest("clips").
AddMessage(nxuskit.UserMessage(`{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 150.0}}]}`))
request.ProviderOptions = map[string]interface{}{
"focus": []string{"data-qc"},
"derived_only_new": true,
}
response, _ := provider.Chat(ctx, request)
fmt.Println("Alerts:", response.Content)
```
### Python Example
```python
from nxuskit-py import create_provider, Message
provider = create_provider("clips", model="/path/to/rules")
response = provider.chat(
model="clips",
messages=[Message.user('{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 150.0}}]}')],
provider_options={
"focus": ["data-qc"],
"derived_only_new": True,
},
)
print("Alerts:", response.content)
```
## Writing Custom Rules
### 1. Create a Rule File
Place your `.clp` file in the appropriate module directory:
```
/path/to/my-rules/data-qc/my-custom-check.clp
```
### 2. Reference Shared Templates
Do NOT redefine templates. Use templates from the shared `shared/*.clp` files:
```text
;;; my-custom-check.clp
;;; Custom confidence check for strict environments
(defrule strict-confidence-check
"Flag records with confidence below 0.8"
(input-data (record-id ?rid) (confidence ?c&:(< ?c 0.8)))
=>
(assert (alert
(alert-type "low_confidence")
(severity "warning")
(message (str-cat "Record " ?rid " confidence " ?c " below threshold 0.8"))
(recommendation "Review data source quality")
(entity-id ?rid)
(rule-name "strict-confidence-check")
(module-name "data-qc"))))
```
### 3. Use Configurable Thresholds
Reference the `threshold-config` fact instead of hard-coding values:
```text
(defrule configurable-bounds-check
"Flag records outside configured bounds"
(threshold-config (value-min ?vmin) (value-max ?vmax))
(input-data (record-id ?rid) (value ?v&:(or (< ?v ?vmin) (> ?v ?vmax))))
=>
(assert (alert
(alert-type "value_out_of_bounds")
(severity "high")
(message (str-cat "Record " ?rid " value " ?v " outside [" ?vmin "-" ?vmax "]"))
(recommendation "Check data or adjust threshold configuration")
(entity-id ?rid)
(rule-name "configurable-bounds-check")
(module-name "data-qc"))))
```
### 4. Naming Conventions
* **File names**: `NNN-descriptive-name.clp` (NNN = numeric prefix for load order)
* **Rule names**: `kebab-case`, descriptive of what is being checked
* **Alert types**: `snake_case`, machine-readable identifiers
* **Module names**: `kebab-case`, matching the directory name
## Testing Custom Rules
### Rust
```rust
use nxuskit::{AsyncProvider, ChatRequest, Message, MockProvider};
// Unit test with MockProvider (no SDK binary required)
#[tokio::test]
async fn test_with_mock() {
let provider = MockProvider::new(r#"{"alerts": [{"type": "low_confidence"}]}"#);
let request = ChatRequest::new("clips")
.with_message(Message::user("test input"));
let response = provider.chat(request).await.unwrap();
assert!(response.content.contains("low_confidence"));
}
// Integration test with real CLIPS engine (requires SDK binary)
#[tokio::test]
#[ignore = "requires libnxuskit runtime"]
async fn test_with_clips_engine() {
use nxuskit::{NxuskitProvider, ProviderConfig};
let config = ProviderConfig {
provider_type: "clips".into(),
model: Some("tests/rules".into()),
..Default::default()
};
let provider = NxuskitProvider::new(config).unwrap();
let request = ChatRequest::new("clips")
.with_message(Message::user(r#"{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 999.0}}]}"#));
let response = provider.chat(request).await.unwrap();
assert!(response.content.contains("out_of_bounds"));
}
```
### Go
```go
func TestRulesWithMock(t *testing.T) {
provider := nxuskit.NewMockProvider(
nxuskit.WithResponse(`{"alerts": [{"type": "low_confidence"}]}`),
)
req := nxuskit.NewChatRequest("clips").
AddMessage(nxuskit.UserMessage("test input"))
resp, err := provider.Chat(context.Background(), req)
require.NoError(t, err)
assert.Contains(t, resp.Content, "low_confidence")
}
```
### Python
```python
import pytest
from nxuskit-py import create_provider, Message
def test_rules_with_mock():
provider = create_provider("mock", responses=["low_confidence alert fired"])
response = provider.chat(
model="clips",
messages=[Message.user("test input")],
)
assert "low_confidence" in response.content
```
## Debugging Rules
### Enable Tracing
Set the `RUST_LOG` environment variable when using the Rust SDK:
```bash
RUST_LOG=nxuskit=debug cargo test -- --nocapture
```
This shows:
* Which rule files are loaded
* Module loading order and file counts
* Warnings for syntax errors
### Inspect CLIPS Facts
Access the CLIPS session API directly (Rust SDK):
```rust
use nxuskit::ClipsSession;
let session = ClipsSession::create()?;
session.load_string("(deftemplate input-data (slot record-id (type INTEGER)) (slot value (type FLOAT)))")?;
session.load_string("(deftemplate alert (slot alert-type (type STRING)) (slot severity (type STRING)))")?;
session.load_string(r#"(defrule check (input-data (record-id ?rid) (value ?v&:(> ?v 100.0))) =>
(assert (alert (alert-type "over-threshold") (severity "high"))))"#)?;
session.reset()?;
session.assert_string(r#"(input-data (record-id 1) (value 150.0))"#)?;
session.run(-1)?;
// List facts by template
let facts_json = session.facts_by_template("alert")?;
println!("Alert facts: {}", facts_json);
// Drop destroys the session automatically
```
### Step Limit Debugging
If inference hits the step limit, check for rule cycles. Common causes:
* Rules that assert facts matching their own LHS (infinite loop)
* Missing `not` patterns allowing rules to fire repeatedly
* Very large fact sets with cross-product patterns
Increase the step limit if needed:
```rust
session.run(500000)?; // Pass -1 to run until agenda exhausted
```
## Best Practices
1. **Keep rules simple** — One check per rule. Complex logic should be split across multiple rules.
2. **Use configurable thresholds** — Reference threshold facts instead of hard-coding values.
3. **Document every rule** — Use the CLIPS documentation string for a brief description.
4. **Test in isolation** — Load only shared templates and the single rule file under test.
5. **Use meaningful names** — Rule names should describe what is checked, not how.
6. **Set appropriate salience** — Use `(declare (salience N))` to control firing order when needed.
---
# CLIPS Excluded Capabilities & Workarounds
URL: https://docs.nxus.systems/v0.9.2/nxuskit/guides/clips-workarounds
Four CLIPS capabilities are intentionally excluded from the Session API.
This document explains why and provides working alternatives.
## 1. User-Defined Functions (UDFs)
**What it is:** CLIPS allows registering C functions callable from rule RHS actions
(`(my-custom-fn ?arg)`).
**Why excluded:** UDFs require raw C function pointers — exposing this through the
session-based FFI would bypass safety guarantees and create ABI fragility.
**Workaround:** Use `nxuskit_clips_eval()` to call built-in CLIPS functions, or
encode custom logic as rules:
```c
// Instead of a UDF that computes weighted score:
// (my-weighted-score ?base ?multiplier)
// Use a rule that computes and asserts the result:
nxuskit_clips_session_load_string(s,
"(defrule compute-weighted-score"
" (input (base ?b) (multiplier ?m))"
" =>"
" (assert (result (score (* ?b ?m)))))");
```
For complex custom functions, pre-compute values in your host language and assert
them as facts:
```c
// Compute in C, assert as fact
double score = my_complex_calculation(base, mult);
char buf[256];
snprintf(buf, sizeof(buf), "(result (score %f))", score);
nxuskit_clips_fact_assert_string(s, buf);
```
## 2. I/O Routers
**What it is:** CLIPS uses I/O routers to redirect `printout`, `read`, and other
I/O operations to custom handlers.
**Why excluded:** Router registration requires persistent C callbacks with
environment-specific state — incompatible with the session handle model.
**Workaround:** Use dribble logging to capture output:
```c
// Capture all CLIPS output to a file
nxuskit_clips_dribble_on(s, "/tmp/clips-output.log");
nxuskit_clips_session_run(s, -1);
nxuskit_clips_dribble_off(s);
// Read /tmp/clips-output.log for captured output
```
For structured output, use facts instead of `printout`:
```c
// Instead of: (printout t "Result: " ?value crlf)
// Use: (assert (output (message (str-cat "Result: " ?value))))
// Then query output facts:
char *outputs = nxuskit_clips_facts_by_template(s, "output");
// Parse JSON array of output facts
nxuskit_free_string(outputs);
```
## 3. Periodic Functions
**What it is:** CLIPS supports registering functions that execute between rule
firings (e.g., for progress callbacks or heartbeat checks).
**Why excluded:** Requires raw function pointers called from within the CLIPS
engine loop — cannot be safely exposed through FFI session handles.
**Workaround:** Use batch `run()` with a step limit and poll between batches:
```c
// Instead of a periodic callback, run in controlled batches
int64_t total_fired = 0;
while (true) {
int64_t fired = nxuskit_clips_session_run(s, 100); // 100 rules per batch
if (fired <= 0) break;
total_fired += fired;
// Your "periodic" logic here:
printf("Progress: %lld rules fired\n", total_fired);
// Check if we should halt
if (should_stop()) {
nxuskit_clips_session_halt(s);
break;
}
}
```
For thread-safe cancellation from another thread:
```c
// Thread 1: run inference
int64_t fired = nxuskit_clips_session_run(s, -1);
// Thread 2: signal halt after timeout
sleep(5);
nxuskit_clips_session_halt(s); // Thread-safe
```
## 4. External Addresses
**What it is:** CLIPS external addresses allow storing opaque C pointers as slot
values, enabling rules to reference host-language objects.
**Why excluded:** External address values are raw `void*` pointers — they cannot
be safely serialized through JSON and would create dangling pointer risks across
session boundaries.
**Workaround:** Use string or integer keys as indirect references:
```c
// Instead of storing a pointer to a connection object:
// (connection (handle ))
// Store an integer key and maintain a lookup table in your host code:
nxuskit_clips_session_load_string(s,
"(deftemplate connection (slot handle (type INTEGER)) (slot status (type SYMBOL)))");
// In C: maintain a mapping
int handle_id = register_connection(conn); // Your lookup table
char buf[128];
snprintf(buf, sizeof(buf), "(connection (handle %d) (status active))", handle_id);
nxuskit_clips_fact_assert_string(s, buf);
// When a rule fires referencing the handle, look up the real object:
// (defrule process-connection
// (connection (handle ?h) (status active))
// =>
// (assert (connection-result (handle ?h) (processed TRUE))))
```
## Summary
| Capability | Status | Workaround Pattern |
|------------|--------|-------------------|
| User-Defined Functions | Excluded | Encode as rules or pre-compute in host language |
| I/O Routers | Excluded | Dribble logging or output facts |
| Periodic Functions | Excluded | Batch `run()` with step limit + polling |
| External Addresses | Excluded | Integer/string keys with host-side lookup table |
All four exclusions are by design — they involve raw C pointers or callbacks that
cannot be safely exposed through the session-handle FFI boundary. The workarounds
provide equivalent functionality using the session API's safe data exchange patterns.
---
# Streaming
URL: https://docs.nxus.systems/v0.9.2/nxuskit/guides/streaming
## Overview
Streaming lets your application receive partial model output as it is produced.
Use it for chat UIs, long-running responses, progress reporting, and command-line
tools that should show output immediately instead of waiting for the final
message.
Most LLM providers support token-by-token streaming. Deterministic providers
such as CLIPS and Z3 may emit a single result chunk or a small number of status
updates, depending on the operation.
## When to Use Streaming
| Use streaming when | Use a regular call when |
|--------------------|-------------------------|
| Users should see output immediately | You need one complete JSON response |
| Responses may be long | Responses are small and predictable |
| You want progress or partial results | You need simpler error handling |
| You are building CLI or chat interfaces | You are running batch jobs |
## Rust
```rust
use futures::StreamExt;
use nxuskit::{completion_stream, NxuskitError};
#[tokio::main]
async fn main() -> Result<(), NxuskitError> {
let mut stream = completion_stream("gpt-4o", "Count from one to five.").await?;
while let Some(chunk) = stream.next().await {
print!("{}", chunk?);
}
Ok(())
}
```
## CLI
```bash
nxuskit-cli chat \
--provider openai \
--model gpt-4o \
--stream \
"Explain streaming responses in one paragraph."
```
For machine-readable output, use the Level 1 `call` command with JSONL:
```bash
echo '{"provider":"openai","model":"gpt-4o","prompt":"Count to five."}' \
| nxuskit-cli call --input - --format jsonl --stream
```
## Stream Events
Streaming APIs generally emit:
- **Content chunks** — Partial text or structured deltas.
- **Metadata** — Provider, model, token usage, timing, or trace information when available.
- **Completion** — Final status, finish reason, or terminal error.
The exact fields vary by provider. Code that handles multiple providers should
append content chunks as they arrive and treat metadata as optional.
## Error Handling
Handle errors in the stream loop, not only at stream creation time. A provider
can accept a request and still fail later because of rate limits, network
interruptions, token limits, or a cancelled operation.
## Related Reference
- [Provider Model](/v0.9.2/nxuskit/concepts/provider-model/)
- [Cloud LLM Providers](/v0.9.2/nxuskit/reference/providers/cloud-llms/)
- [Local LLM Providers](/v0.9.2/nxuskit/reference/providers/local-llms/)
- [CLI Input Format Reference](/v0.9.2/nxuskit/reference/cli-reference/)
---
# CLIPS Session Migration
URL: https://docs.nxus.systems/v0.9.2/nxuskit/migration/clips-session-migration
This guide covers migrating from the legacy `ClipsEnvironment` / `nxuskit_clips_env_*` API
to the new `ClipsSession` / `nxuskit_clips_session_*` API introduced in SDK v0.9.1.
## What Changed
| Aspect | Old API | New API |
|--------|---------|---------|
| Handle type | Opaque pointer (`NxuskitClipsEnv*`) | `uint64_t` session handle |
| Safety | Manual pointer management | Generational index (use-after-free protection) |
| Fact builder | Separate `NxuskitClipsFactBuilder` type | `nxuskit_clips_fact_assert_structured()` (JSON slots) |
| Fact iteration | Pointer chain (`first_fact` → `fact_next`) | `nxuskit_clips_facts_by_template()` (JSON array) |
| Template lookup | `nxuskit_clips_find_template()` → pointer | `nxuskit_clips_template_exists()` / `template_list()` |
| Thread safety | Not guaranteed | Session registry with RwLock; `session_halt()` for cross-thread signalling |
## Who Needs to Migrate
* **Chat provider users** (`NxuskitProvider` / `ChatRequest`): **No changes needed.** The Chat provider interface is unchanged.
* **Direct C ABI users** (`nxuskit_clips_env_*` functions): **Must migrate.** Old functions are removed.
* **Rust SDK users** (`nxuskit::ClipsEnvironment`): **Must migrate** to `nxuskit::ClipsSession`.
## C ABI Migration
### Session Lifecycle
```c
// OLD
struct NxuskitClipsEnv *env = nxuskit_clips_env_create();
nxuskit_clips_env_load_file(env, "rules.clp");
nxuskit_clips_env_reset(env);
nxuskit_clips_env_run(env, -1);
nxuskit_clips_env_destroy(env);
// NEW
uint64_t s = nxuskit_clips_session_create();
nxuskit_clips_session_load_file(s, "rules.clp");
nxuskit_clips_session_reset(s);
nxuskit_clips_session_run(s, -1);
nxuskit_clips_session_destroy(s);
```
### Asserting Facts
```c
// OLD — string-based
nxuskit_clips_env_assert_string(env, "(sensor (name \"t1\") (value 42))");
// OLD — fact builder
struct NxuskitClipsFactBuilder *fb = nxuskit_clips_fb_create(env, "sensor");
nxuskit_clips_fb_put_string(fb, "name", "t1");
nxuskit_clips_fb_put_integer(fb, "value", 42);
nxuskit_clips_fb_assert(fb);
// NEW — string-based (unchanged pattern)
nxuskit_clips_fact_assert_string(s, "(sensor (name \"t1\") (value 42))");
// NEW — structured (replaces fact builder)
nxuskit_clips_fact_assert_structured(s, "sensor",
"{\"name\":\"t1\",\"value\":42}");
```
### Querying Facts
```c
// OLD — pointer iteration
struct NxuskitClipsTemplate *tmpl = nxuskit_clips_find_template(env, "sensor");
struct NxuskitClipsFact *fact = nxuskit_clips_template_first_fact(tmpl);
while (fact) {
char *slot = nxuskit_clips_fact_get_slot(fact, "value");
// use slot...
nxuskit_free_string(slot);
struct NxuskitClipsFact *next = nxuskit_clips_fact_next(fact);
nxuskit_clips_fact_destroy(fact);
fact = next;
}
nxuskit_clips_template_destroy(tmpl);
// NEW — JSON array
char *facts = nxuskit_clips_facts_by_template(s, "sensor");
// facts is a JSON array of fact objects — parse with your JSON library
nxuskit_free_string(facts);
```
## Rust SDK Migration
### Basic Usage
```rust
// OLD
use nxuskit::ClipsEnvironment;
let env = ClipsEnvironment::new()?;
env.load_from_string("(deftemplate sensor (slot name) (slot value))")?;
env.reset()?;
env.assert_string("(sensor (name \"t1\") (value 42))")?;
env.run(None)?;
if let Some(tmpl) = env.find_template("sensor")? {
for fact in tmpl.facts().flatten() {
println!("{:?}", fact.get_slot("value")?);
}
}
// NEW
use nxuskit::ClipsSession;
let session = ClipsSession::create()?;
session.load_string("(deftemplate sensor (slot name) (slot value))")?;
session.reset()?;
session.assert_string("(sensor (name \"t1\") (value 42))")?;
session.run(-1)?;
let facts = session.facts_by_template("sensor")?;
println!("{}", facts);
// session is destroyed on drop
```
### FBP (Fact-Based Processing) Pattern
```rust
use nxuskit::ClipsSession;
// Create a persistent session for iterative processing
let session = ClipsSession::create()?;
session.load_file("rules/shared/000-core.clp")?;
session.load_file("rules/data-qc/bounds-check.clp")?;
// Cycle 1: Load initial data
session.reset()?;
session.assert_string(r#"(input-data (record-id 1) (value 150.0))"#)?;
session.run(-1)?;
let alerts = session.facts_by_template("alert")?;
// Cycle 2: New data, same rules (facts persist unless reset)
session.assert_string(r#"(input-data (record-id 2) (value 200.0))"#)?;
session.run(-1)?;
let more_alerts = session.facts_by_template("alert")?;
```
### LKS (Load-知識-Solve) Pattern
```rust
use nxuskit::ClipsSession;
// Load once, solve many times
let session = ClipsSession::create()?;
session.load_file("expert-system.clp")?;
for case in cases {
session.reset()?; // Clear facts, keep rules
session.assert_string(&format!("(case-data (id {}) (symptoms {}))",
case.id, case.symptoms))?;
session.run(-1)?;
let diagnosis = session.facts_by_template("diagnosis")?;
println!("Case {}: {}", case.id, diagnosis);
}
```
## New Capabilities (No Old Equivalent)
These features are only available in the Session API:
| Feature | Function | Description |
|---------|----------|-------------|
| Session halt | `session_halt()` | Thread-safe inference cancellation |
| Session cache | `session_preload()` / `get_cached()` | Named session caching |
| Fact retraction | `fact_retract()` / `fact_retract_by_template()` | Targeted fact removal |
| Rule debugging | `rule_breakpoint_set()` / `rule_times_fired()` | Rule-level debugging |
| Global variables | `global_get_value()` / `global_set_value()` | Defglobal access |
| Watch/dribble | `watch()` / `dribble_on()` | Tracing and logging |
| Strategy control | `strategy_get()` / `strategy_set()` | Conflict resolution |
| Module focus | `focus_push()` / `focus_pop()` | Module execution control |
| Structured assert | `fact_assert_structured()` | JSON-based fact assertion |
| Binary save/load | `session_save_binary()` / `load_binary()` | Fast environment serialization |
---
# Upgrade Path
URL: https://docs.nxus.systems/v0.9.2/nxuskit/migration/upgrade-path
## Overview
When a Pro feature is called without valid authorization, the SDK returns
a specific error type with an actionable message. This document maps every
error to its cause and resolution.
## Error Reference
### `FeatureUnavailable`
**Message**: varies by context (see sub-cases below)
This is the umbrella error returned when a Pro feature cannot be accessed.
The message text tells you exactly what to do.
***
### `LicenseRequired`
**Returned when**: A Pro feature is called but no valid license token was
found in the resolution chain (env var → file → API parameter).
**Message**:
```
License installation required.
```
**Resolution**:
1. Authenticate: `nxuskit-cli license login`
2. Activate your license: `nxuskit-cli license activate --key `
3. For CI/CD: set `NXUSKIT_LICENSE_TOKEN` environment variable with your
deployment token
4. To start a trial: `nxuskit-cli license login` then `nxuskit-cli license activate --trial`
***
### `LicenseExpired`
**Returned when**: The developer token's subscription period has ended.
**Message**:
```
License installation required.
```
**Resolution**:
1. Renew your subscription at your account dashboard
2. After renewal, run `nxuskit-cli license activate --key ` to get a
fresh token
3. Community features continue working during the gap
***
### `EditionInsufficient`
**Returned when**: You have a valid token but the binary is the Community
edition, which does not include Pro code.
**Message**:
```
This feature requires Pro edition.
```
**Resolution**:
1. Download the Pro edition binary (requires authenticated access)
2. Replace your Community binary with the Pro binary
3. Your existing license token will be recognized automatically
***
### `VersionCeilingExceeded`
**Returned when**: A deployment token's version ceiling is lower than the
running SDK version.
**Message**:
```
Deployment token covers up to v{ceiling}. Update your deployment token for v{current}+ support.
```
**Resolution**:
1. If you have an active support subscription, request an updated
deployment token from your account dashboard
2. Alternatively, pin the SDK version to stay within the token ceiling
3. Contact **support@nxus.systems** if you need help
***
### `TrialSuspended`
**Returned when**: A trial token was issued but not activated within
the 7-day grace period.
**Message**:
```
License installation required.
```
**Resolution**:
1. Run `nxuskit-cli license login` to authenticate
2. Run `nxuskit-cli license activate --trial` to resume the trial
3. This extends Pro access for the remainder of the 30-day trial period
***
### `TrialExpired`
**Returned when**: The 30-day trial period has ended.
**Message**:
```
License installation required.
```
**Resolution**:
1. Purchase a Pro license
2. Community features continue working without interruption
3. All Pro features will be restored immediately after activation
***
### `TrialIssuanceFailed`
**Returned when**: The SDK attempted to issue a trial token but could
not complete the operation.
**Message**:
```
License installation required.
```
**Resolution**:
1. Run `nxuskit-cli license login` to authenticate first
2. Then run `nxuskit-cli license activate --trial`
3. Community features remain available regardless
***
## Error Handling by Language
### Rust
```rust
use nxuskit::{FeatureUnavailableError, LicenseExpiredError, LicenseRequiredError};
match nxuskit::zen_evaluate(&table, &input) {
Ok(result) => { /* success */ }
Err(e) if e.is::() => {
eprintln!("{}", e); // "License installation required."
}
Err(e) if e.is::() => {
eprintln!("{}", e); // "License installation required."
}
Err(e) => { /* other errors */ }
}
```
### Python
```python
from nxuskit import zen_evaluate
from nxuskit import LicenseRequiredError, LicenseExpiredError, FeatureUnavailableError
try:
result = zen_evaluate(table_path, input_data)
except LicenseRequiredError as e:
print(e.message) # "License installation required."
except LicenseExpiredError as e:
print(e.message) # "License installation required."
except FeatureUnavailableError as e:
print(e.message) # generic feature gate
```
### Go
```go
import nxuskit "github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go"
result, err := nxuskit.ZenEvaluate(table, input)
if err != nil {
switch {
case errors.Is(err, nxuskit.ErrLicenseRequired):
fmt.Println(err) // "License installation required."
case errors.Is(err, nxuskit.ErrLicenseExpired):
fmt.Println(err) // "License installation required."
default:
fmt.Println(err)
}
}
```
## Quick Decision Tree
```
Pro feature called
│
├─ No token found? → "License installation required."
├─ Token expired? → "License installation required."
├─ Community binary? → EditionInsufficient → download Pro binary
├─ Version ceiling hit? → VersionCeilingExceeded → update deployment token
├─ Trial not activated? → "License installation required."
├─ Trial past 30 days? → "License installation required."
├─ Can't reach service? → "License installation required."
└─ Valid token + Pro binary? → Success
```
---
# API Reference
URL: https://docs.nxus.systems/v0.9.2/nxuskit/reference/api
## Overview
nxusKit APIs are organized around a small set of shared contracts:
- **Provider configuration** creates a backend connection.
- **Chat requests** carry model names, messages, and provider options.
- **Chat responses** return content, metadata, usage, and errors.
- **Streaming calls** emit incremental chunks for interactive workflows.
- **Specialized providers** such as CLIPS and Z3 use structured JSON payloads
inside the same request/response pattern.
Use this page as the entry point for API-level reference material.
## Core References
| Reference | Use for |
|-----------|---------|
| [C ABI Reference](/v0.9.2/nxuskit/reference/api-reference/) | C functions, ownership rules, FFI handles, CLIPS session calls, and memory management. |
| [CLI Input Format Reference](/v0.9.2/nxuskit/reference/cli-reference/) | Structured JSON/YAML/JSONL input contracts for `nxuskit-cli`. |
| [Cloud LLM Providers](/v0.9.2/nxuskit/reference/providers/cloud-llms/) | Provider configuration for hosted LLM APIs. |
| [Local LLM Providers](/v0.9.2/nxuskit/reference/providers/local-llms/) | Ollama, LM Studio, and in-process local model configuration. |
| [Expert System & Utility Providers](/v0.9.2/nxuskit/reference/providers/expert-systems/) | CLIPS, MCP, Mock, and Loopback configuration. |
| [Z3 Constraint Satisfaction Provider](/v0.9.2/nxuskit/reference/providers/z3-solver/) | Z3 input, output, optimization, and streaming contracts. |
## Shared Chat Shape
The language wrappers expose native types, but the shared request shape is:
```json
{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "You are concise."},
{"role": "user", "content": "Summarize nxusKit."}
],
"max_tokens": 512,
"temperature": 0.2,
"stream": false
}
```
Responses include provider content plus optional metadata:
```json
{
"content": "nxusKit is a multi-language SDK...",
"model": "gpt-4o",
"finish_reason": "stop",
"usage": {
"input_tokens": 24,
"output_tokens": 12
}
}
```
Provider-specific options belong in the configuration object or provider options
map. See the provider reference pages before relying on a field across multiple
backends.
## Memory and Ownership
When calling through the C ABI, every returned provider handle, response handle,
stream handle, and allocated string has an explicit free function. Use the
[ownership summary](/v0.9.2/nxuskit/reference/api-reference/#ownership-summary)
before integrating from C, C++, Go FFI, Python FFI, or another native boundary.
---
# C ABI Reference
URL: https://docs.nxus.systems/v0.9.2/nxuskit/reference/api-reference
All functions are declared in `nxuskit.h`. The ABI uses opaque handles and JSON
strings for all data exchange. Every function is thread-safe unless noted.
## Version
### `nxuskit_version`
```c
const char *nxuskit_version(void);
```
Returns the library version string (e.g., `"0.9.1"`). The returned pointer is
static and valid for the process lifetime. Never returns NULL.
## Provider Lifecycle
### `nxuskit_create_provider`
```c
struct NxuskitProvider *nxuskit_create_provider(const char *config_json);
```
Creates a provider from a JSON configuration string.
**Parameters:**
* `config_json` — JSON string with at minimum `{"provider_type": "..."}`.
See [Provider Reference](../providers/cloud-llms/) for provider-specific fields.
**Returns:** Opaque provider handle, or NULL on failure. On failure, call
`nxuskit_last_error()` for the error message.
**Ownership:** Caller owns the returned handle. Must call `nxuskit_free_provider()`
when done.
**Config JSON fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `provider_type` | string | Yes | Provider identifier (see providers list) |
| `api_key` | string | Varies | API key for cloud providers |
| `model` | string | No | Default model name |
| `base_url` | string | No | Custom API endpoint |
| `timeout_ms` | integer | No | Request timeout in milliseconds |
**Example:**
```c
const char *config = "{\"provider_type\":\"openai\",\"api_key\":\"sk-...\"}";
struct NxuskitProvider *p = nxuskit_create_provider(config);
if (!p) {
fprintf(stderr, "Error: %s\n", nxuskit_last_error());
}
```
### `nxuskit_free_provider`
```c
void nxuskit_free_provider(struct NxuskitProvider *provider);
```
Frees a provider handle. Safe to call with NULL (no-op).
**Parameters:**
* `provider` — Handle from `nxuskit_create_provider()`, or NULL.
## Synchronous Chat
### `nxuskit_chat`
```c
struct NxuskitResponse *nxuskit_chat(
struct NxuskitProvider *provider,
const char *request_json
);
```
Sends a synchronous chat request. Blocks until the response is complete.
**Parameters:**
* `provider` — Provider handle (must not be NULL)
* `request_json` — JSON chat request string
**Returns:** Response handle, or NULL on failure.
**Ownership:** Caller owns the returned handle. Must call `nxuskit_free_response()`.
**Request JSON fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `model` | string | Yes | Model identifier |
| `messages` | array | Yes | Array of `{role, content}` objects |
| `temperature` | float | No | Sampling temperature (0.0–2.0) |
| `max_tokens` | integer | No | Maximum tokens in response |
| `top_p` | float | No | Nucleus sampling parameter |
| `stop` | array | No | Stop sequences |
| `stream` | boolean | No | Must be `false` for sync (default) |
| `response_format` | object | No | Response format constraints |
**Message object:**
| Field | Type | Description |
|-------|------|-------------|
| `role` | string | `"system"`, `"user"`, or `"assistant"` |
| `content` | string | Message content |
### `nxuskit_response_json`
```c
const char *nxuskit_response_json(const struct NxuskitResponse *response);
```
Returns the JSON string from a response handle.
**Parameters:**
* `response` — Response handle from `nxuskit_chat()` (must not be NULL)
**Returns:** JSON string pointer. Valid only while the response handle exists.
Do **not** free this pointer — it is owned by the response handle.
**Response JSON fields:**
| Field | Type | Description |
|-------|------|-------------|
| `content` | string | The model's response text |
| `model` | string | Model used |
| `provider` | string | Provider name |
| `usage` | object | Token usage (if available) |
| `usage.prompt_tokens` | integer | Input tokens |
| `usage.completion_tokens` | integer | Output tokens |
| `usage.total_tokens` | integer | Total tokens |
| `finish_reason` | string | Why generation stopped |
| `warnings` | array | Provider warnings (if any) |
### `nxuskit_free_response`
```c
void nxuskit_free_response(struct NxuskitResponse *response);
```
Frees a response handle. Safe to call with NULL.
## Streaming Chat
### Callback Types
```c
typedef int32_t (*NxuskitStreamCallback)(
const char *chunk_json,
void *user_data
);
typedef void (*NxuskitStreamDoneCallback)(
const char *final_json,
void *user_data
);
```
**`NxuskitStreamCallback`** is called for each streaming chunk. Return 0 to
continue, non-zero to request cancellation.
**`NxuskitStreamDoneCallback`** is called exactly once when streaming completes
(success, error, or cancellation).
**Important:** Callbacks fire from a **background thread**. The caller must
ensure `user_data` is thread-safe.
### `nxuskit_chat_stream`
```c
struct NxuskitStream *nxuskit_chat_stream(
struct NxuskitProvider *provider,
const char *request_json,
NxuskitStreamCallback on_chunk,
NxuskitStreamDoneCallback on_done,
void *user_data
);
```
Starts a streaming chat request. Returns immediately; chunks arrive via callbacks.
**Parameters:**
* `provider` — Provider handle (must not be NULL)
* `request_json` — JSON chat request string
* `on_chunk` — Called for each chunk (from background thread)
* `on_done` — Called once when streaming ends (from background thread)
* `user_data` — Opaque pointer passed to both callbacks
**Returns:** Stream handle, or NULL on failure.
**Chunk JSON fields:**
| Field | Type | Description |
|-------|------|-------------|
| `delta` | string | Incremental text content |
| `index` | integer | Chunk sequence number (0-based) |
| `thinking` | string | Chain-of-thought reasoning (if enabled, optional) |
| `finish_reason` | string | Why generation stopped (set on final chunk, optional) |
| `usage` | object | Token usage statistics (typically only on final chunk, optional) |
| `tool_calls` | array | Tool call deltas (if applicable, optional) |
**Done JSON fields:** Same as synchronous response JSON, plus optional `error`:
| Field | Type | Description |
|-------|------|-------------|
| `error.error_type` | string | Error category |
| `error.message` | string | Error description |
### `nxuskit_cancel_stream`
```c
void nxuskit_cancel_stream(struct NxuskitStream *stream);
```
Cancels a streaming request. Blocks until all pending callbacks have completed.
After this call returns, no further callbacks will fire.
Safe to call with NULL.
### `nxuskit_free_stream`
```c
void nxuskit_free_stream(struct NxuskitStream *stream);
```
Frees a stream handle. Must be called after the stream completes or is cancelled.
Safe to call with NULL.
**Typical lifecycle:**
```c
stream = nxuskit_chat_stream(provider, request, on_chunk, on_done, data);
// ... callbacks fire ...
// After on_done fires (or if you want to cancel):
nxuskit_cancel_stream(stream); // optional — ensures no more callbacks
nxuskit_free_stream(stream); // required — frees resources
```
## Model Discovery
### `nxuskit_list_models`
```c
char *nxuskit_list_models(struct NxuskitProvider *provider);
```
Returns a JSON array of available models.
**Parameters:**
* `provider` — Provider handle (must not be NULL)
**Returns:** JSON string (caller-owned), or NULL on failure.
**Ownership:** Caller must free the returned string with `nxuskit_free_string()`.
**Response format:**
```json
[
{"id": "gpt-4o", "name": "GPT-4o"},
{"id": "gpt-4o-mini", "name": "GPT-4o Mini"}
]
```
## Error Handling
### `nxuskit_last_error`
```c
const char *nxuskit_last_error(void);
```
Returns the last error message for the **calling thread**. Returns NULL if no
error has occurred on this thread.
**Thread-local:** Each thread has its own error state. Calling any `nxuskit_*`
function may overwrite the previous error on that thread.
**Lifetime:** The returned pointer is valid until the next `nxuskit_*` call on
the same thread.
## Memory Management
### `nxuskit_free_string`
```c
void nxuskit_free_string(char *ptr);
```
Frees a caller-owned string returned by any `nxuskit_*` function that returns
`char*` (e.g., `nxuskit_list_models()`, `nxuskit_clips_facts_list()`,
`nxuskit_clips_eval()`). Safe to call with NULL.
**Important:** Only use this for strings documented as "caller-owned". Do not
use it for strings from `nxuskit_response_json()` (those are owned by the
response handle) or `nxuskit_version()` (static).
## Ownership Summary
| Function | Returns | Owned By | Free With |
|----------|---------|----------|-----------|
| `nxuskit_version()` | `const char*` | Library (static) | Never free |
| `nxuskit_create_provider()` | `NxuskitProvider*` | Caller | `nxuskit_free_provider()` |
| `nxuskit_chat()` | `NxuskitResponse*` | Caller | `nxuskit_free_response()` |
| `nxuskit_response_json()` | `const char*` | Response handle | Freed with response |
| `nxuskit_chat_stream()` | `NxuskitStream*` | Caller | `nxuskit_free_stream()` |
| `nxuskit_list_models()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_last_error()` | `const char*` | Thread-local | Never free |
## CLIPS Session API
Direct access to the CLIPS 6.4.2 rule engine via session-based handles — create
sessions, load rules, assert facts, run inference, and inspect results without
going through the provider/chat abstraction.
All CLIPS operations use opaque `uint64_t` session handles (generational indices
that prevent use-after-free). Return conventions:
* `int32_t` functions return 0 on success, -1 on error
* `char*` functions return a JSON string (caller-owned, free with `nxuskit_free_string()`) or NULL on error
* `bool` functions return the queried value; check `nxuskit_last_error()` on unexpected results
### Session Lifecycle
#### `nxuskit_clips_session_create`
```c
uint64_t nxuskit_clips_session_create(void);
```
Creates a new isolated CLIPS session. Returns a non-zero session handle, or 0 on
failure (check `nxuskit_last_error()`).
#### `nxuskit_clips_session_destroy`
```c
void nxuskit_clips_session_destroy(uint64_t session);
```
Destroys a session and frees all resources. No-op if the handle is invalid.
#### `nxuskit_clips_session_reset`
```c
int32_t nxuskit_clips_session_reset(uint64_t session);
```
Resets the session: clears all facts, preserves rules, restores initial-fact.
#### `nxuskit_clips_session_clear`
```c
int32_t nxuskit_clips_session_clear(uint64_t session);
```
Clears everything (facts, rules, templates) — returns the session to a pristine state.
#### `nxuskit_clips_session_info`
```c
char *nxuskit_clips_session_info(uint64_t session);
```
Returns session metadata as a JSON object (module count, rule count, fact count, etc.).
### Loading Constructs
#### `nxuskit_clips_session_load_file`
```c
int32_t nxuskit_clips_session_load_file(uint64_t session, const char *path);
```
Loads constructs from a `.clp` file.
#### `nxuskit_clips_session_load_string`
```c
int32_t nxuskit_clips_session_load_string(uint64_t session, const char *constructs);
```
Loads constructs from an in-memory string.
**Example:**
```c
uint64_t s = nxuskit_clips_session_create();
nxuskit_clips_session_load_string(s,
"(deftemplate sensor (slot name) (slot value))");
```
#### `nxuskit_clips_session_load_binary`
```c
int32_t nxuskit_clips_session_load_binary(uint64_t session, const char *path);
```
Loads a pre-compiled binary image (`.bin` file created with `save_binary`).
#### `nxuskit_clips_session_save_binary`
```c
int32_t nxuskit_clips_session_save_binary(uint64_t session, const char *path);
```
Saves the current session state as a binary image for fast reloading.
#### `nxuskit_clips_session_build`
```c
int32_t nxuskit_clips_session_build(uint64_t session, const char *construct);
```
Builds a single CLIPS construct (deftemplate, defrule, etc.) from a string.
#### `nxuskit_clips_session_batch`
```c
int32_t nxuskit_clips_session_batch(uint64_t session, const char *path);
```
Executes a batch file of CLIPS commands.
#### `nxuskit_clips_session_load_json`
```c
int32_t nxuskit_clips_session_load_json(uint64_t session, const char *json);
```
Loads constructs from a JSON specification (templates, rules, facts in one call).
### Session Cache
#### `nxuskit_clips_session_preload`
```c
int32_t nxuskit_clips_session_preload(const char *name, const char *rules_json);
```
Preloads a named session into the cache. The session is created, rules are loaded,
and the session is stored for later retrieval via `get_cached`.
#### `nxuskit_clips_session_get_cached`
```c
uint64_t nxuskit_clips_session_get_cached(const char *name);
```
Returns a cached session handle by name. Returns 0 if not found.
#### `nxuskit_clips_session_cache_remove`
```c
int32_t nxuskit_clips_session_cache_remove(const char *name);
```
Removes a named session from the cache and destroys it.
### Fact Operations
#### `nxuskit_clips_fact_assert_string`
```c
int64_t nxuskit_clips_fact_assert_string(uint64_t session, const char *fact_string);
```
Asserts a fact using CLIPS syntax. Returns the fact index (>= 0) on success, or -1 on error.
**Example:**
```c
int64_t idx = nxuskit_clips_fact_assert_string(s,
"(sensor (name \"temp-1\") (value 150))");
```
#### `nxuskit_clips_fact_assert_structured`
```c
int64_t nxuskit_clips_fact_assert_structured(
uint64_t session,
const char *template_name,
const char *slots_json
);
```
Asserts a fact using a JSON slot specification. Returns the fact index or -1.
**Example:**
```c
int64_t idx = nxuskit_clips_fact_assert_structured(s, "sensor",
"{\"name\":\"temp-1\",\"value\":150}");
```
#### `nxuskit_clips_fact_retract`
```c
int32_t nxuskit_clips_fact_retract(uint64_t session, int64_t fact_index);
```
Retracts a fact by its index.
#### `nxuskit_clips_fact_retract_by_template`
```c
int32_t nxuskit_clips_fact_retract_by_template(uint64_t session, const char *template_name);
```
Retracts all facts of a given template.
#### `nxuskit_clips_fact_exists`
```c
bool nxuskit_clips_fact_exists(uint64_t session, int64_t fact_index);
```
Returns true if the fact index refers to an existing fact.
#### `nxuskit_clips_fact_get_slot`
```c
char *nxuskit_clips_fact_get_slot(uint64_t session, int64_t fact_index, const char *slot_name);
```
Returns a slot value as a type-tagged JSON string (e.g., `{"type":"integer","value":42}`).
**Slot JSON types:**
| CLIPS Type | JSON `type` | JSON `value` |
|------------|-------------|--------------|
| INTEGER | `"integer"` | number |
| FLOAT | `"float"` | number |
| STRING | `"string"` | string |
| SYMBOL | `"symbol"` | string |
| MULTIFIELD | `"multifield"` | array of typed values |
#### `nxuskit_clips_fact_slot_values`
```c
char *nxuskit_clips_fact_slot_values(uint64_t session, int64_t fact_index);
```
Returns all slot values as a JSON object.
#### `nxuskit_clips_fact_pp_form`
```c
char *nxuskit_clips_fact_pp_form(uint64_t session, int64_t fact_index);
```
Returns the pretty-printed CLIPS representation of a fact.
#### `nxuskit_clips_fact_index`
```c
int64_t nxuskit_clips_fact_index(uint64_t session, int64_t fact_index);
```
Returns the canonical CLIPS fact index, or -1 on error.
#### `nxuskit_clips_facts_list`
```c
char *nxuskit_clips_facts_list(uint64_t session);
```
Returns all facts as a JSON array.
#### `nxuskit_clips_facts_by_template`
```c
char *nxuskit_clips_facts_by_template(uint64_t session, const char *template_name);
```
Returns all facts matching a template as a JSON array.
#### `nxuskit_clips_fact_duplication_get` / `set`
```c
bool nxuskit_clips_fact_duplication_get(uint64_t session);
int32_t nxuskit_clips_fact_duplication_set(uint64_t session, bool allow);
```
Query or set whether duplicate facts are allowed.
### Template Operations
#### `nxuskit_clips_template_exists`
```c
bool nxuskit_clips_template_exists(uint64_t session, const char *name);
```
Returns true if the named template exists in the session.
#### `nxuskit_clips_template_list`
```c
char *nxuskit_clips_template_list(uint64_t session);
```
Returns all template names as a JSON array.
#### `nxuskit_clips_template_slot_names`
```c
char *nxuskit_clips_template_slot_names(uint64_t session, const char *template_name);
```
Returns slot names for a template as a JSON array.
#### `nxuskit_clips_template_slot_info`
```c
char *nxuskit_clips_template_slot_info(uint64_t session, const char *template_name);
```
Returns detailed slot information (types, defaults, constraints) as JSON.
#### `nxuskit_clips_template_facts`
```c
char *nxuskit_clips_template_facts(uint64_t session, const char *template_name);
```
Returns all facts of a template as a JSON array.
#### `nxuskit_clips_template_pp_form`
```c
char *nxuskit_clips_template_pp_form(uint64_t session, const char *template_name);
```
Returns the pretty-printed CLIPS definition of a template.
### Inference Engine
#### `nxuskit_clips_session_run`
```c
int64_t nxuskit_clips_session_run(uint64_t session, int64_t limit);
```
Runs inference. Pass `limit = -1` to run until the agenda is exhausted.
Returns the number of rules fired, or -1 on error.
#### `nxuskit_clips_session_halt`
```c
int32_t nxuskit_clips_session_halt(uint64_t session);
```
Signals the session to halt inference (thread-safe — can be called from another thread).
#### `nxuskit_clips_agenda_size`
```c
int64_t nxuskit_clips_agenda_size(uint64_t session);
```
Returns the number of activations on the agenda.
#### `nxuskit_clips_agenda_clear`
```c
int32_t nxuskit_clips_agenda_clear(uint64_t session);
```
Removes all activations from the agenda.
#### `nxuskit_clips_agenda_reorder`
```c
int32_t nxuskit_clips_agenda_reorder(uint64_t session);
```
Reorders the agenda using the current conflict resolution strategy.
#### `nxuskit_clips_strategy_get` / `set`
```c
char *nxuskit_clips_strategy_get(uint64_t session);
int32_t nxuskit_clips_strategy_set(uint64_t session, const char *strategy);
```
Get or set the conflict resolution strategy. Valid values: `"depth"`, `"breadth"`,
`"simplicity"`, `"complexity"`, `"lex"`, `"mea"`, `"random"`.
#### `nxuskit_clips_salience_mode_get` / `set`
```c
char *nxuskit_clips_salience_mode_get(uint64_t session);
int32_t nxuskit_clips_salience_mode_set(uint64_t session, const char *mode);
```
Get or set the salience evaluation mode.
### Rule Operations
#### `nxuskit_clips_rule_exists`
```c
bool nxuskit_clips_rule_exists(uint64_t session, const char *name);
```
Returns true if the named rule exists.
#### `nxuskit_clips_rule_list`
```c
char *nxuskit_clips_rule_list(uint64_t session);
```
Returns all rule names as a JSON array.
#### `nxuskit_clips_rule_times_fired`
```c
int64_t nxuskit_clips_rule_times_fired(uint64_t session, const char *rule_name);
```
Returns how many times a rule has fired, or -1 on error.
#### `nxuskit_clips_rule_breakpoint_set` / `remove` / `has_breakpoint`
```c
int32_t nxuskit_clips_rule_breakpoint_set(uint64_t session, const char *rule_name);
int32_t nxuskit_clips_rule_breakpoint_remove(uint64_t session, const char *rule_name);
bool nxuskit_clips_rule_has_breakpoint(uint64_t session, const char *rule_name);
```
Manage breakpoints on rules for debugging.
#### `nxuskit_clips_rule_refresh`
```c
int32_t nxuskit_clips_rule_refresh(uint64_t session, const char *rule_name);
```
Refreshes a rule, placing its activations back on the agenda.
#### `nxuskit_clips_rule_pp_form`
```c
char *nxuskit_clips_rule_pp_form(uint64_t session, const char *rule_name);
```
Returns the pretty-printed CLIPS definition of a rule.
#### `nxuskit_clips_rule_delete`
```c
int32_t nxuskit_clips_rule_delete(uint64_t session, const char *rule_name);
```
Deletes a rule from the session.
### Module Operations
#### `nxuskit_clips_module_exists`
```c
bool nxuskit_clips_module_exists(uint64_t session, const char *name);
```
Returns true if the named module exists.
#### `nxuskit_clips_module_list`
```c
char *nxuskit_clips_module_list(uint64_t session);
```
Returns all module names as a JSON array.
#### `nxuskit_clips_module_current_get` / `set`
```c
char *nxuskit_clips_module_current_get(uint64_t session);
int32_t nxuskit_clips_module_current_set(uint64_t session, const char *name);
```
Get or set the current module.
#### `nxuskit_clips_focus_push` / `get` / `pop` / `clear`
```c
int32_t nxuskit_clips_focus_push(uint64_t session, const char *module_name);
char *nxuskit_clips_focus_get(uint64_t session);
int32_t nxuskit_clips_focus_pop(uint64_t session);
int32_t nxuskit_clips_focus_clear(uint64_t session);
```
Manage the module focus stack (controls which module's rules are eligible to fire).
### Global Variables
#### `nxuskit_clips_global_exists`
```c
bool nxuskit_clips_global_exists(uint64_t session, const char *name);
```
Returns true if the named defglobal exists.
#### `nxuskit_clips_global_list`
```c
char *nxuskit_clips_global_list(uint64_t session);
```
Returns all global variable names as a JSON array.
#### `nxuskit_clips_global_get_value` / `set_value`
```c
char *nxuskit_clips_global_get_value(uint64_t session, const char *name);
int32_t nxuskit_clips_global_set_value(uint64_t session, const char *name, const char *value_json);
```
Get or set a global variable value. Values use the type-tagged JSON format.
#### `nxuskit_clips_reset_globals_get` / `set`
```c
bool nxuskit_clips_reset_globals_get(uint64_t session);
int32_t nxuskit_clips_reset_globals_set(uint64_t session, bool reset);
```
Query or set whether globals are reset when `session_reset` is called.
### Evaluation
#### `nxuskit_clips_eval`
```c
char *nxuskit_clips_eval(uint64_t session, const char *expression);
```
Evaluates a CLIPS expression and returns the result as a type-tagged JSON string.
#### `nxuskit_clips_function_call`
```c
char *nxuskit_clips_function_call(uint64_t session, const char *function_name, const char *args);
```
Calls a CLIPS function by name with optional arguments string.
### Debugging
#### `nxuskit_clips_watch` / `unwatch`
```c
int32_t nxuskit_clips_watch(uint64_t session, const char *item);
int32_t nxuskit_clips_unwatch(uint64_t session, const char *item);
```
Enable or disable tracing for a watch item. Valid items: `"facts"`, `"rules"`,
`"activations"`, `"compilations"`, `"statistics"`, `"globals"`, `"focus"`, `"all"`.
#### `nxuskit_clips_dribble_on` / `off`
```c
int32_t nxuskit_clips_dribble_on(uint64_t session, const char *path);
int32_t nxuskit_clips_dribble_off(uint64_t session);
```
Start or stop logging all CLIPS I/O to a file.
### CLIPS Ownership Summary
| Function | Returns | Owned By | Free With |
|----------|---------|----------|-----------|
| `nxuskit_clips_session_create()` | `uint64_t` | Session registry | `nxuskit_clips_session_destroy()` |
| `nxuskit_clips_session_get_cached()` | `uint64_t` | Session cache | `nxuskit_clips_session_cache_remove()` |
| `nxuskit_clips_session_info()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_fact_get_slot()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_fact_slot_values()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_fact_pp_form()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_facts_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_facts_by_template()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_slot_names()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_slot_info()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_facts()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_pp_form()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_rule_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_rule_pp_form()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_module_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_module_current_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_focus_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_global_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_global_get_value()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_strategy_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_salience_mode_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_eval()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_function_call()` | `char*` | Caller | `nxuskit_free_string()` |
### Complete Example
```c
#include "nxuskit.h"
#include
int main(void) {
// Create session
uint64_t s = nxuskit_clips_session_create();
if (!s) {
fprintf(stderr, "Error: %s\n", nxuskit_last_error());
return 1;
}
// Load rules
nxuskit_clips_session_load_string(s,
"(deftemplate sensor (slot name (type STRING)) (slot value (type INTEGER)))");
nxuskit_clips_session_load_string(s,
"(defrule high-temp"
" (sensor (name ?n) (value ?v&:(> ?v 100)))"
" =>"
" (printout t \"ALERT: \" ?n \" = \" ?v crlf))");
// Assert facts and run
nxuskit_clips_session_reset(s);
nxuskit_clips_fact_assert_string(s, "(sensor (name \"temp-1\") (value 150))");
int64_t fired = nxuskit_clips_session_run(s, -1);
printf("Rules fired: %lld\n", fired);
// Inspect results
char *facts = nxuskit_clips_facts_list(s);
printf("Facts: %s\n", facts);
nxuskit_free_string(facts);
// Cleanup
nxuskit_clips_session_destroy(s);
return 0;
}
```
## Error Types
Errors returned in response JSON or via `nxuskit_last_error()`:
| Error Type | Description |
|------------|-------------|
| `configuration` | Invalid config, missing API key, version mismatch |
| `invalid_request` | Malformed request JSON, missing required fields |
| `authentication` | Invalid or expired API key |
| `rate_limit` | Provider rate limit exceeded |
| `provider` | Provider-side error (server error, model not found) |
| `timeout` | Request timed out |
| `stream` | Streaming error (connection lost, cancelled) |
| `internal` | Unexpected internal error |
---
# Changelog
URL: https://docs.nxus.systems/v0.9.2/nxuskit/reference/changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## \[Unreleased]
## \[0.9.1] - 2026-04-04
### CLI Level 1 Semantic Remediation
* **Real Engine Integration**: `zen eval`, `solver solve`, `clips eval`, and `bn infer` now execute real engine logic — no more placeholder/stub responses
* **Pipeline Execution**: `pipeline run` dispatches all stage types (LLM, CLIPS, ZEN, solver, BN) through real engines with output handoff and partial results on failure
* **Call Envelope**: `call` propagates tool definitions and includes `tool_calls` and `inference_metadata` in responses
* **Artifact Deep Merge**: `artifact merge` performs recursive deep merge with dot-notation conflict paths
* **Models Capabilities**: `models --supports` filter uses real capability inference from model metadata
* **Provider Auth**: `provider status` uses structured auth subsystem; `provider logout` is provider-scoped
* **Judge/Branch**: `judge select` returns structured errors; `branch compare` produces field-level diffs
### CLI Documentation and Solver Format Compatibility
* **CLI Input Reference**: New `docs/user/cli-input-reference.md` covering all 13 Level 1 commands with JSON schemas, working examples, and common errors
* **Enhanced Help Text**: Every engine command's `--help` now shows input format structure
* **Solver Format Compatibility**: `solver solve` accepts library API format (ConstraintInput with `var_type`, structured constraints, domains, objectives) directly from shared `problem.json` scenario files — no format conversion needed
* **SMT-LIB Support**: `solver solve` accepts SMT-LIB 2 format (S-expressions) as convenience input for Z3 experts
* **Auto-Detection**: Solver input format (simplified CLI, library API, SMT-LIB) is auto-detected from content
### Positioning
* **CLI Description**: Updated from "CLI for interacting with multiple LLM providers" to "JSON-first control plane for shell automation, CI, and multi-engine reasoning workflows"
* **README**: Added CLI / Shell Automation section with examples
* **Naming**: Fixed `nxuskit-engine-cli` → `nxuskit-cli` naming drift across all docs and scripts
### Compliance
* **NOTICE**: Regenerated with zen-engine and z3-sys entries; Python section reformatted to remove excessive whitespace padding
* **Constitution v2.4.0**: Added semantic test assertions, stub prohibition, and task verification criteria (Articles II and III)
* **Acceptance Fixtures**: Three PoR 4.1 acceptance workflow scripts (intake-routing, generator-validator-retry, typed-artifact-handoff)
## \[0.9.0] - 2026-03-11
Initial public release of the nxusKit SDK.
### Highlights
* **Polyglot SDK**: Unified LLM interfaces across Rust, Go, and Python
* **14 LLM Providers**: Claude, OpenAI, Ollama, LM Studio, Mistral, OpenRouter, Together, Groq, Fireworks, Perplexity, MCP, CLIPS, Mock, Loopback
* **CLIPS Expert System**: Rule-based inference via embedded CLIPS 6.4.2 engine with FFI bindings
* **Bayesian Network Inference**: Full-featured BN provider with Variable Elimination, Junction Tree, Loopy BP, NUTS/HMC, and structure/parameter learning
* **Z3 Constraint Solver**: Stateful solver sessions with multi-objective optimization, soft constraints, push/pop scoping, and UNSAT core extraction
* **ZEN Decision Tables**: JSON Decision Model evaluation via zen-engine
* **Plugin Architecture**: Signed plugin loading with Ed25519 verification and capability-based sandboxing
* **SDK CLI**: Command-line tool for all providers (`nxuskit-cli`)
* **SDK Installer**: Cross-platform SDK manager (`install.sh`) with version management
* **Cross-Language Conformance**: Shared test vectors ensuring API parity across Rust, Go, and Python
### Platform Support
| Platform | Architecture | Status |
|----------|-------------|--------|
| Linux | x86\_64 | Supported |
| macOS | ARM64 (Apple Silicon) | Supported |
| macOS | x86\_64 | Supported |
| Windows | x86\_64 | Supported |
### Language SDKs
| Language | Package | Description |
|----------|---------|-------------|
| Rust | `nxuskit` | FFI wrapper with safe Rust API |
| Go | `nxuskit-go` | Idiomatic Go with context support |
| Python | `nxuskit-py` | Pure Python with `requests` HTTP client |
### Getting Started
See [Installation](/v0.9.2/nxuskit/getting-started/installation/) for installation and usage instructions.
For runnable examples, see the [nxusKit-examples](https://github.com/nxus-SYSTEMS/nxusKit-examples) repository.
---
# CLI Input Format Reference
URL: https://docs.nxus.systems/v0.9.2/nxuskit/reference/cli-reference
Single source of truth for every Level 1 `nxuskit-cli` command's input schema,
with copy-paste runnable examples using the loopback provider.
All commands accept `--input -` for stdin and `--format json` (default).
Output is wrapped in a `ResponseEnvelope` with `trace_id`, `request_metadata`,
and timing fields.
***
## Table of Contents
* [call](#call)
* [zen eval](#zen-eval)
* [solver solve](#solver-solve)
* [Solver Format Disambiguation](#solver-format-disambiguation)
* [clips eval](#clips-eval)
* [bn infer](#bn-infer)
* [pipeline run](#pipeline-run)
* [artifact merge](#artifact-merge)
* [artifact summarize](#artifact-summarize)
* [packet validate](#packet-validate)
* [tool-loop run](#tool-loop-run)
* [judge select](#judge-select)
* [branch fork](#branch-fork)
* [branch compare](#branch-compare)
***
### `call`
LLM invocation. Accepts either `prompt` (single-turn) or `messages` (multi-turn).
**Input schema (`CallInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `prompt` | string | no | Single-turn user prompt (convenience shorthand) |
| `messages` | array of `{role, content}` | no | Multi-turn conversation messages |
| `system` | string | no | System message prepended to the conversation |
| `provider` | string | no | Provider name (default: `loopback`, or `$NXUSKIT_PROVIDER`) |
| `model` | string | no | Model identifier (default: `"default"`) |
| `tool_definitions` | array of JSON objects | no | Tool/function schemas passed to the LLM |
| `max_tokens` | u32 | no | Maximum output tokens |
| `temperature` | f32 | no | Sampling temperature |
| `stream` | bool | no | Enable streaming (JSONL output) |
At least one of `prompt` or `messages` should be provided.
**Example:**
```bash
echo '{"prompt": "Hello", "provider": "loopback"}' \
| nxuskit-cli call --input - --format json
```
**Common errors:**
* `Invalid call input JSON: missing field ...` -- Fix: ensure the input is valid JSON with at least `prompt` or `messages`.
* `Unknown provider "xyz"` -- Fix: use a valid provider name (`loopback`, `openai`, `claude`, etc.) or set `$NXUSKIT_PROVIDER`.
***
### `zen eval`
ZEN decision table evaluation (Pro-gated).
**Input schema (`ZenEvalInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `table` | JSON object | **yes** | JDM (JSON Decision Model) decision table definition |
| `input` | JSON object | **yes** | Context data evaluated against the table |
The `table` field must be a valid JDM model with `nodes` and `edges` arrays.
Decision table nodes have `type: "decisionTableNode"` and contain `rules` in
their `content`.
**Example:**
```bash
echo '{
"table": {
"nodes": [
{
"id": "1",
"name": "input",
"type": "inputNode",
"content": {}
},
{
"id": "2",
"name": "decision",
"type": "decisionTableNode",
"content": {
"hitPolicy": "first",
"rules": [
{"_id": "r1", "input.age": ">= 18", "output.status": "adult"}
],
"inputs": [{"id": "i1", "name": "age", "field": "input.age"}],
"outputs": [{"id": "o1", "name": "status", "field": "output.status"}]
}
},
{
"id": "3",
"name": "output",
"type": "outputNode",
"content": {}
}
],
"edges": [
{"id": "e1", "sourceId": "1", "targetId": "2", "type": "edge"},
{"id": "e2", "sourceId": "2", "targetId": "3", "type": "edge"}
]
},
"input": {"age": 25}
}' | nxuskit-cli zen eval --input - --format json
```
**Common errors:**
* `Entitlement check failed: zen` -- Fix: ZEN is Pro-gated. Ensure a valid Pro license is active.
* `Invalid ZEN eval input: missing field "table"` -- Fix: both `table` and `input` are required fields.
***
### `solver solve`
Z3 constraint solving (Pro-gated). Auto-detects three input formats.
#### Solver Format Disambiguation
The CLI accepts three distinct input formats, auto-detected at parse time:
| Format | Detection Rule | Best For |
|--------|---------------|----------|
| **Simplified** | JSON with `"type"` on variables and string constraints | Quick CLI one-liners, human-authored problems |
| **Library API** | JSON with `"var_type"` on variables or `"constraint_type"` on constraints | Cross-language scenario sharing with nxuskit-go/nxuskit-py |
| **SMT-LIB 2** | Input starts with `(` | Direct Z3 interaction, academic benchmarks |
The **library API format** uses the same `ConstraintInput` struct as the Rust, Go,
and Python SDKs. This means a JSON file authored for `solver solve` can be loaded
directly by `nxuskit.solve()` in any SDK, enabling cross-language scenario sharing.
***
#### Format 1: Simplified
**Input schema (`SolverInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `variables` | array of `SolverVariable` | **yes** | Variable declarations |
| `constraints` | array of strings | **yes** | Constraint expressions (e.g. `"x + y == 10"`) |
| `objective` | string | no | `"minimize"` or `"maximize"` |
| `objective_expr` | string | no | Expression to optimize (requires `objective`) |
**`SolverVariable` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Variable identifier |
| `type` | string | **yes** | `"integer"`, `"real"`, or `"boolean"` |
| `bounds` | array of `{"min": n}` / `{"max": n}` | no | Domain bounds |
Supported constraint operators: `==`, `!=`, `>=`, `<=`, `>`, `<`.
Arithmetic in LHS: `x + y == 10`, `x - y == 5`, `x * y == 12`.
**Example (simplified):**
```bash
echo '{
"variables": [
{"name": "x", "type": "integer", "bounds": [{"min": 0}, {"max": 10}]},
{"name": "y", "type": "integer", "bounds": [{"min": 0}, {"max": 10}]}
],
"constraints": ["x + y == 10", "x >= 3"],
"objective": "maximize",
"objective_expr": "x"
}' | nxuskit-cli solver solve --input - --format json
```
***
#### Format 2: Library API (`ConstraintInput`)
**Input schema (`ConstraintInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `variables` | array of `VariableDef` | no | Variable declarations |
| `constraints` | array of `ConstraintDef` | no | Structured constraint definitions |
| `objective` | `ObjectiveDef` | no | Single optimization objective |
| `objectives` | array of `ObjectiveDef` | no | Multiple objectives (multi-objective mode) |
| `config` | `SolverConfig` | no | Per-request solver configuration overrides |
| `retract` | array of strings | no | Named constraints to remove |
| `assumptions` | array of `ConstraintDef` | no | Temporary constraints (auto-retracted after solve) |
**`VariableDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Variable identifier |
| `var_type` | string | **yes** | `"integer"`, `"real"`, or `"boolean"` |
| `domain` | `{"min": f64, "max": f64}` or `[min, max]` | no | Domain bounds |
| `label` | string | no | Human-readable description |
**`ConstraintDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | no | Identifier for retraction / unsat core |
| `constraint_type` | string | **yes** | `"eq"`, `"neq"`, `"lt"`, `"gt"`, `"le"`, `"ge"`, `"add"`, `"sub"`, `"mul"`, `"div"`, `"and"`, `"or"`, `"not"`, `"implies"`, `"iff"`, `"all_different"`, `"at_most"`, `"at_least"`, `"exactly"`, `"in_range"` |
| `params` / `parameters` | JSON object | no | Type-specific parameters (e.g. `{"left": "x", "right": 3}`). Both field names accepted. If omitted, auto-inferred from `variables` and `expression` fields (see below). |
| `variables` | string\[] | no | Variable names involved in the constraint. Used to auto-infer `params` when omitted. |
| `expression` | string | no | Human-readable expression (e.g. `"a * 20 = c"`). Used to auto-infer `params` when omitted. |
| `weight` | f64 | no | Soft constraint penalty (omit for hard constraint) |
| `label` | string | no | Human-readable description |
**`ObjectiveDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Unique objective identifier |
| `direction` | string | **yes** | `"minimize"` or `"maximize"` |
| `expression` | string | **yes** | Expression to optimize (references variable names) |
| `weight` | f64 | no | Weight for weighted multi-objective mode |
| `label` | string | no | Human-readable description |
| `priority` | u32 | no | Priority for lexicographic mode (lower = higher priority) |
**Params auto-inference**: When `params`/`parameters` is omitted or null, the CLI infers it from the `variables` and `expression` fields — matching the behavior of the Rust SDK's `ensure_parameters()` helper. This means shared `problem.json` scenario files work directly without modification:
* Comparison constraints (`ge`, `le`, `eq`, etc.) with `variables: ["a", "b"]` → infers `params: {"left": "a", "right": "b"}`
* Arithmetic constraints (`add`, `mul`, etc.) with `variables: ["a", "b", "c"]` and `expression: "a * 20 = c"` → infers `params: {"left": "a", "right": 20, "result": "c"}`
* Set constraints (`all_different`, `at_most`, `at_least`, `exactly`) with `variables: ["x", "y", "z"]` → infers `params: {"variables": ["x", "y", "z"]}`
* Partial params (e.g., `{"right": 19000}` with `variables: ["salary"]`) → merges to `{"left": "salary", "right": 19000}`
**Type aliases**: The CLI accepts `equal` (→ `eq`) and `not_equal` (→ `neq`) as long-form constraint type names for compatibility with some scenario files.
**Example (library API):**
```bash
echo '{
"variables": [
{"name": "x", "var_type": "integer", "domain": {"min": 0, "max": 10}},
{"name": "y", "var_type": "integer", "domain": {"min": 0, "max": 10}}
],
"constraints": [
{"name": "sum", "constraint_type": "add", "params": {"left": "x", "right": "y", "result": 10}},
{"name": "lower_bound", "constraint_type": "ge", "params": {"left": "x", "right": 3}}
],
"objective": {
"name": "max_x",
"direction": "maximize",
"expression": "x"
}
}' | nxuskit-cli solver solve --input - --format json
```
***
#### Format 3: SMT-LIB 2
Raw SMT-LIB 2 text. Auto-detected when input starts with `(`.
**Example (SMT-LIB):**
```bash
echo '(declare-const x Int)
(declare-const y Int)
(assert (>= x 0))
(assert (<= x 10))
(assert (>= y 0))
(assert (<= y 10))
(assert (= (+ x y) 10))
(assert (>= x 3))
(check-sat)
(get-model)' | nxuskit-cli solver solve --input - --format json
```
**Common errors (all formats):**
* `Entitlement check failed: solver` -- Fix: solver is Pro-gated. Ensure a valid Pro license.
* `Cannot parse constraint expression: 'x + y = 10'` -- Fix: use `==` for equality, not `=`.
* `Invalid solver input JSON: ...` -- Fix: ensure JSON is well-formed. Check that simplified format uses `"type"` (not `"var_type"`).
* `Invalid solver library format: ...` -- Fix: library format requires `"var_type"` on variables and `"constraint_type"` on constraints.
***
### `clips eval`
CLIPS rule engine evaluation.
**Input schema (`ClipsEvalInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `rules` | string | **yes** | CLIPS rule definitions (defrule, deftemplate, etc.) |
| `facts` | array of strings | no | Initial facts to assert (default: `[]`) |
> **Newline escaping:** CLIPS rules contain newlines. In JSON strings you must
> use `\n` for line breaks. When piping from a shell, use `$'...'` quoting or
> a heredoc to embed literal newlines, then let `jq` handle escaping.
**Example:**
```bash
echo '{
"rules": "(defrule greet (person (name ?n)) => (assert (greeting (message (str-cat \"Hello \" ?n)))))",
"facts": ["(person (name \"World\"))"]
}' | nxuskit-cli clips eval --input - --format json
```
**Multi-line rules (using jq for safe escaping):**
```bash
RULES=$(cat <<'CLIPS'
(deftemplate person (slot name))
(deftemplate greeting (slot message))
(defrule greet
(person (name ?n))
=>
(assert (greeting (message (str-cat "Hello " ?n)))))
CLIPS
)
jq -n --arg rules "$RULES" '{"rules": $rules, "facts": ["(person (name \"World\"))"]}' \
| nxuskit-cli clips eval --input - --format json
```
**Common errors:**
* `Failed to load CLIPS rules: ...` -- Fix: check CLIPS syntax. Common issues: unbalanced parentheses, missing `=>` in defrule.
* `Failed to assert fact '(foo)': ...` -- Fix: if using deftemplates, facts must match the template signature (e.g. `(person (name "x"))` not `(person "x")`).
* `Invalid CLIPS eval input: missing field "rules"` -- Fix: `rules` is required. Use `"rules": ""` for an empty ruleset.
***
### `bn infer`
Bayesian network inference via variable elimination.
**Input schema (`BnInferInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `network` | `NetworkDef` | **yes** | Bayesian network structure and CPDs |
| `evidence` | map of string to string | no | Observed variable states (default: `{}`) |
| `query_nodes` | array of strings | **yes** | Variables to compute posterior probabilities for |
| `algorithm` | string | no | Inference algorithm (default: `"variable_elimination"`) |
**`NetworkDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `nodes` | array of `NodeDef` | **yes** | Variable definitions with states |
| `edges` | array of `EdgeDef` | **yes** | Directed edges (parent to child) |
| `cpds` | map of string to `CpdDef` | **yes** | Conditional probability distributions |
**`NodeDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Variable name |
| `states` | array of strings | **yes** | Possible states for this variable |
**`EdgeDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `from` | string | **yes** | Parent node name |
| `to` | string | **yes** | Child node name |
**`CpdDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `probabilities` | array of f64 | **yes** | Flat probability table (row-major order over parent states) |
**Example:**
```bash
echo '{
"network": {
"nodes": [
{"name": "Rain", "states": ["yes", "no"]},
{"name": "Sprinkler", "states": ["on", "off"]},
{"name": "GrassWet", "states": ["wet", "dry"]}
],
"edges": [
{"from": "Rain", "to": "GrassWet"},
{"from": "Sprinkler", "to": "GrassWet"}
],
"cpds": {
"Rain": {"probabilities": [0.2, 0.8]},
"Sprinkler": {"probabilities": [0.4, 0.6]},
"GrassWet": {"probabilities": [0.99, 0.01, 0.9, 0.1, 0.8, 0.2, 0.0, 1.0]}
}
},
"evidence": {"GrassWet": "wet"},
"query_nodes": ["Rain"]
}' | nxuskit-cli bn infer --input - --format json
```
**Common errors:**
* `Invalid variable name '...': ...` -- Fix: node names must be non-empty alphanumeric identifiers.
* `Failed to set CPD for '...': ...` -- Fix: probability array length must equal the product of the node's state count and all parent nodes' state counts.
* `Invalid BN inference input: missing field "network"` -- Fix: `network` and `query_nodes` are both required.
***
### `pipeline run`
Sequential multi-stage pipeline execution. Accepts YAML or JSON.
**Input schema (`PipelineDefinition`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Pipeline name |
| `stages` | array of `Stage` | **yes** | Ordered list of stages to execute |
**`Stage` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Stage identifier |
| `type` | string | **yes** | Stage type: `"llm"`, `"clips_eval"`, `"zen_eval"`, `"solver_solve"`, `"bn_infer"` |
| `config` | JSON object | no | Stage-specific configuration (passed to the engine) |
| `output_key` | string | no | Bind stage output to a named key for `{{key}}` interpolation in later stages |
For `llm` stages, `config` accepts `prompt`, `provider`, and `model`.
For `clips_eval` stages, `config` accepts `rules` and `facts`.
For other stage types, `config` mirrors the respective command's input schema.
Stages execute sequentially. Each stage receives the previous stage's output.
String values in `config` support `{{key}}` interpolation from `output_key` bindings.
If a stage fails, all subsequent stages are marked `"skipped"`.
**Example:**
```bash
echo '{
"name": "demo-pipeline",
"stages": [
{
"name": "generate",
"type": "llm",
"config": {"prompt": "Say hello", "provider": "loopback"},
"output_key": "llm_result"
},
{
"name": "evaluate",
"type": "llm",
"config": {"prompt": "Summarize: {{llm_result}}", "provider": "loopback"}
}
]
}' | nxuskit-cli pipeline run --input - --format json
```
**Common errors:**
* `Invalid pipeline definition: ...` -- Fix: ensure input is valid YAML or JSON with `name` and `stages` fields.
* `Unknown stage type: xyz` -- Fix: valid stage types are `llm`, `clips_eval`, `zen_eval`, `solver_solve`, `bn_infer`.
* `PipelineStageFailed { stage: "...", detail: ... }` -- Fix: check the `stages[].result.message` field in the output for the root cause.
***
### `artifact merge`
Deep-merge multiple JSON artifact files with conflict detection.
This command takes multiple `--input` flags (not stdin JSON). Each input must be a
JSON object (not an array or scalar).
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--input` | string (repeatable) | **yes** (>= 2) | Paths to JSON files to merge |
| `--merge-strategy` | string | no | Conflict resolution: `"error"` (default), `"first"`, `"last"` |
No JSON input schema -- inputs are arbitrary JSON objects read from files.
**Example:**
```bash
echo '{"a": 1, "b": {"x": 10}}' > /tmp/art1.json
echo '{"b": {"y": 20}, "c": 3}' > /tmp/art2.json
nxuskit-cli artifact merge \
--input /tmp/art1.json --input /tmp/art2.json \
--format json
```
**Common errors:**
* `artifact merge requires at least 2 input files` -- Fix: provide at least two `--input` paths.
* `MergeConflict { paths: ["b.x"] }` -- Fix: two files have different values at the same key path. Use `--merge-strategy first` or `--merge-strategy last` to resolve.
* `'...' is not a JSON object` -- Fix: each input file must contain a JSON object (`{...}`), not an array or scalar.
***
### `artifact summarize`
Summarize a JSON artifact's structure and estimated token cost.
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--input` | string | **yes** | Path to JSON file or `-` for stdin |
No JSON input schema -- the input is any valid JSON value.
**Output fields:**
| Field | Type | Description |
|-------|------|-------------|
| `field_count` | u32 | Total number of fields (recursive) |
| `top_level_keys` | array of strings | Keys at the root level |
| `estimated_tokens` | u32 | Rough token estimate (byte length / 4) |
**Example:**
```bash
echo '{"name": "test", "data": {"x": 1, "y": 2}}' \
| nxuskit-cli artifact summarize --input - --format json
```
**Common errors:**
* `Invalid artifact JSON: ...` -- Fix: input must be valid JSON.
***
### `packet validate`
Validate a JSON document against a JSON Schema.
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--input` | string | **yes** | Packet data file (JSON) or `-` for stdin |
| `--schema` | string | **yes** | Path to a JSON Schema file |
No custom input schema -- the packet is any JSON value validated against the
provided JSON Schema.
**Example:**
```bash
echo '{"type": "string"}' > /tmp/schema.json
echo '"hello"' | nxuskit-cli packet validate --input - --schema /tmp/schema.json --format json
```
**Output fields:**
| Field | Type | Description |
|-------|------|-------------|
| `valid` | bool | `true` if the packet conforms to the schema |
| `errors` | array of `{path, message, keyword}` | Validation errors (empty when valid) |
**Common errors:**
* `SchemaNotFound { path: "..." }` -- Fix: the `--schema` path must point to an existing file.
* `Invalid JSON Schema: ...` -- Fix: ensure the schema file is a valid JSON Schema draft.
* Exits with code 1 when validation fails (output still written to stdout).
***
### `tool-loop run`
Iterative tool-augmented LLM loop. The model is called repeatedly until it
converges (stops requesting tool calls) or hits `max_iterations`.
**Input schema (`ToolLoopInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `prompt` | string | **yes** | Initial user prompt |
| `provider` | string | no | Provider name (default: `loopback` or `$NXUSKIT_PROVIDER`) |
| `model` | string | no | Model identifier (default: `"default"`) |
| `max_iterations` | u32 | no | Maximum loop iterations (default: `10`) |
| `tools` | array of strings | no | Tool adapter names: `"file_reader"`, `"calculator"`, `"web_search"` |
| `tool_configs` | JSON object | no | Per-tool configuration |
| `tool_definitions` | array of JSON objects | no | Function/tool schemas passed to the LLM for function calling |
Built-in tool adapters:
* `file_reader` -- reads a file, expects `{"path": "..."}` arguments
* `calculator` -- evaluates a math expression, expects `{"expression": "..."}` arguments
* `web_search` -- searches the web, expects `{"query": "..."}` arguments (MCP-gated)
**Example:**
```bash
echo '{
"prompt": "What is 2 + 2?",
"provider": "loopback",
"tools": ["calculator"],
"max_iterations": 5
}' | nxuskit-cli tool-loop run --input - --format json
```
**Common errors:**
* `Invalid tool-loop input: missing field "prompt"` -- Fix: `prompt` is the only required field.
* `Unknown tool adapter: xyz` -- Fix: valid adapters are `file_reader`, `calculator`, `web_search`.
* `Entitlement check failed: mcp` -- Fix: the `mcp` tool adapter is Pro-gated.
***
### `judge select`
LLM-based candidate selection. Sends candidates and criteria to an LLM and
parses a structured JSON response with scores and reasoning.
**Input schema (`JudgeSelectInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `candidates` | array of `Candidate` | **yes** | Candidates to evaluate |
| `criteria` | string | no | Evaluation criteria description |
| `provider` | string | no | Provider name (default: `"loopback"`) |
| `model` | string | no | Model identifier (default: `"default"`) |
**`Candidate` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | string | **yes** | Unique candidate identifier |
| `content` | string | **yes** | Candidate text to evaluate |
**Example:**
```bash
echo '{
"candidates": [
{"id": "a", "content": "The answer is 42."},
{"id": "b", "content": "The answer is approximately 42.0."}
],
"criteria": "accuracy and conciseness",
"provider": "loopback"
}' | nxuskit-cli judge select --input - --format json
```
**Common errors:**
* `Invalid judge select input: missing field "candidates"` -- Fix: `candidates` array is required with at least one entry.
* `Failed to parse judge response as structured JSON: ...` -- Fix: the LLM must return a JSON object with `selected_id`, `reasoning`, and `scores`. The loopback provider may not produce valid judge output; use a real LLM provider for meaningful results.
***
### `branch fork`
Fan out a single prompt to multiple models concurrently.
**Input schema (`BranchForkInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `prompt` | string | **yes** | Prompt sent to all models |
| `models` | array of strings | **yes** | Model identifiers to invoke in parallel |
| `provider` | string | no | Provider name (default: `"loopback"`) |
| `system` | string | no | System message prepended to each request |
Alternatively, models can be specified via the `--models` CLI flag as a
comma-separated list, which overrides the `models` field in the JSON input.
**Example:**
```bash
echo '{
"prompt": "Explain recursion in one sentence.",
"models": ["model-a", "model-b"],
"provider": "loopback"
}' | nxuskit-cli branch fork --input - --format json
```
**Using `--models` flag:**
```bash
echo '{"prompt": "Explain recursion."}' \
| nxuskit-cli branch fork --input - --models model-a,model-b --format json
```
**Common errors:**
* `Invalid fork input: missing field "prompt"` -- Fix: `prompt` is required.
* `Invalid fork input: missing field "models"` -- Fix: provide `models` in JSON or via `--models` flag.
***
### `branch compare`
Compare results from a previous `branch fork` invocation. Input is the JSON
output of `branch fork` (the `BranchForkResult` object).
**Input schema (`BranchForkResult`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `results` | array of `BranchModelResult` | **yes** | Results from `branch fork` |
**`BranchModelResult` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `model` | string | **yes** | Model identifier |
| `content` | string | **yes** | Model's response text |
| `usage` | `{input_tokens, output_tokens, total_tokens}` | no | Token usage |
| `elapsed_ms` | f64 | **yes** | Response latency in milliseconds |
**Output includes:**
* `comparison`: per-model length and optional quality score
* `diffs`: structural differences (content\_length, word\_count, sentence\_count, elapsed\_ms, content\_similarity for 2-model comparisons)
**Example (piping fork output to compare):**
```bash
echo '{
"prompt": "Explain recursion.",
"models": ["model-a", "model-b"],
"provider": "loopback"
}' | nxuskit-cli branch fork --input - --format json \
| jq '.result' \
| nxuskit-cli branch compare --input - --format json
```
**Common errors:**
* `Invalid fork result input: missing field "results"` -- Fix: input must be a `BranchForkResult` object (the `result` field from a fork envelope, not the full envelope).
---
# Cloud LLM Providers
URL: https://docs.nxus.systems/v0.9.2/nxuskit/reference/providers/cloud-llms
## OpenAI
```json
{
"provider_type": "openai",
"api_key": "sk-...",
"base_url": "https://api.openai.com/v1",
"timeout_ms": 30000
}
```
**Environment variable:** `OPENAI_API_KEY`
**Supported models:** `gpt-4o`, `gpt-4o-mini`, `o1`, `o1-mini`, `o3-mini`, `gpt-4-turbo`
**Capabilities:** System messages, streaming, vision, tools/function calling, JSON mode, JSON schema, seed, logprobs, presence/frequency penalty, response format
## Anthropic Claude
```json
{
"provider_type": "claude",
"api_key": "sk-ant-...",
"base_url": "https://api.anthropic.com",
"timeout_ms": 30000
}
```
**Environment variable:** `ANTHROPIC_API_KEY`
**Supported models:** `claude-sonnet-4-20250514`, `claude-opus-4-20250514`, `claude-haiku-4-5-20251001`, `claude-3-5-sonnet-20241022`
**Capabilities:** System messages, streaming, vision, tools/function calling, JSON mode, top-k sampling. Max stop sequences: 8192.
## Groq
```json
{
"provider_type": "groq",
"api_key": "gsk_...",
"timeout_ms": 30000
}
```
**Environment variable:** `GROQ_API_KEY`
**Supported models:** `llama-3.3-70b-versatile`, `llama-3.1-8b-instant`, `mixtral-8x7b-32768`, `gemma2-9b-it`
**Capabilities:** System messages, streaming, tools/function calling, JSON mode
## Fireworks
```json
{
"provider_type": "fireworks",
"api_key": "fw_...",
"timeout_ms": 30000
}
```
**Environment variable:** `FIREWORKS_API_KEY`
**Capabilities:** System messages, streaming
## Together
```json
{
"provider_type": "together",
"api_key": "...",
"timeout_ms": 30000
}
```
**Environment variable:** `TOGETHER_API_KEY`
**Capabilities:** System messages, streaming
## OpenRouter
```json
{
"provider_type": "openrouter",
"api_key": "sk-or-...",
"timeout_ms": 30000
}
```
**Environment variable:** `OPENROUTER_API_KEY`
**Capabilities:** System messages, streaming, vision, tools/function calling
## Perplexity
```json
{
"provider_type": "perplexity",
"api_key": "pplx-...",
"timeout_ms": 30000
}
```
**Environment variable:** `PERPLEXITY_API_KEY`
**Capabilities:** System messages, streaming
## Mistral
```json
{
"provider_type": "mistral",
"api_key": "...",
"timeout_ms": 30000
}
```
**Environment variable:** `MISTRAL_API_KEY`
**Supported models:** `mistral-large-latest`, `mistral-medium-latest`, `mistral-small-latest`, `codestral-latest`
**Capabilities:** System messages, streaming, tools/function calling, JSON mode
---
# Expert System & Utility Providers
URL: https://docs.nxus.systems/v0.9.2/nxuskit/reference/providers/expert-systems
## CLIPS Rule Engine
The CLIPS provider runs rules against a CLIPS 6.4.1 expert system engine.
Unlike LLM providers, CLIPS uses deterministic rule-based reasoning.
```json
{
"provider_type": "clips",
"model": "/path/to/rules/directory"
}
```
**Configuration:**
* `model` field is used for the rules directory path (contains `.clp` rule files or `.bin` binary images)
**Capabilities:** System messages
**Note:** No API key required. The CLIPS engine runs in-process.
For writing custom rules, see the [Rule Authoring Guide](/v0.9.2/nxuskit/guides/clips-rule-authoring/).
## MCP (Model Context Protocol)
Connects to an MCP server for tool-augmented model interactions.
```json
{
"provider_type": "mcp",
"base_url": "http://localhost:3000",
"model": "model-name"
}
```
**Configuration:**
* `base_url` — MCP server URI (required)
* `model` — Model name to use on the server
**Capabilities:** System messages, streaming
## Mock (Testing)
Returns deterministic responses for unit testing.
```json
{
"provider_type": "mock"
}
```
**Capabilities:** System messages, streaming
**Note:** No API key or configuration required. Returns fixed responses.
## Loopback (Testing)
Echoes back the user's input for integration testing.
```json
{
"provider_type": "loopback"
}
```
**Capabilities:** System messages, streaming
**Note:** Use `"model": "echo"` in the chat request to echo back the user's
message content. Other model names return an empty response.
---
# Local LLM Providers
URL: https://docs.nxus.systems/v0.9.2/nxuskit/reference/providers/local-llms
nxusKit supports two categories of local LLM providers:
* **In-Process Providers** — Load and run models directly in your application process. No external server required. Requires Cargo feature flags.
* **HTTP-Based Providers** — Connect to a locally running inference server (Ollama, LM Studio). No feature flags needed.
***
## In-Process Providers
In-process providers load GGUF model files directly into your application and run inference without any external server. This gives you the lowest possible latency, full control over model lifecycle, and zero network overhead.
### Backends
nxusKit provides two in-process inference backends:
| Backend | Feature Flag | Engine | Status |
|---------|-------------|--------|--------|
| llama.cpp | `provider-local-llama` | [llama-cpp-2](https://github.com/utilityai/llama-cpp-rs) (safe Rust bindings to llama.cpp) | Production-ready |
| mistral.rs | `provider-local-mistralrs` | [mistral.rs](https://github.com/EricLBuehler/mistral.rs) (pure-Rust inference on Candle) | Experimental |
Both backends load the same **GGUF** model format. If both features are enabled, you can select a backend explicitly or let nxusKit auto-select the first available one.
### Supported Model Format
**GGUF** (GPT-Generated Unified Format) is the only supported format. GGUF files are self-contained — they bundle weights, tokenizer, and metadata in a single file. Both backends read the same `.gguf` files.
You can obtain GGUF models from:
* [Hugging Face](https://huggingface.co/models?library=gguf) — Search for "GGUF" in model filters
* [Ollama](https://ollama.com/library) — Models pulled by Ollama are stored as GGUF blobs (nxusKit can discover these)
* [TheBloke on Hugging Face](https://huggingface.co/TheBloke) — Prolific quantizer of popular models
### Compatible Model Families
Any model published in GGUF format that is compatible with llama.cpp should work. The following model families are known to work:
| Model Family | Parameters | Example GGUF | Notes |
|---|---|---|---|
| **Llama 3.2** | 1B, 3B | `Llama-3.2-1B-Instruct-Q4_K_M.gguf` | Meta's latest small models. Great for CPU. |
| **Llama 3.1** | 8B, 70B, 405B | `Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf` | Excellent general-purpose. 8B runs well on 16GB RAM. |
| **Llama 3** | 8B, 70B | `Meta-Llama-3-8B-Instruct-Q4_K_M.gguf` | Predecessor to 3.1, widely available. |
| **Llama 2** | 7B, 13B, 70B | `llama-2-7b-chat.Q4_K_M.gguf` | Older but battle-tested. |
| **Mistral** | 7B | `mistral-7b-instruct-v0.3.Q4_K_M.gguf` | Strong performance relative to size. |
| **Mixtral** | 8x7B, 8x22B | `mixtral-8x7b-instruct-v0.1.Q4_K_M.gguf` | Mixture-of-experts. Needs more RAM. |
| **Phi-3 / Phi-3.5** | 3.8B, 14B | `Phi-3.5-mini-instruct-Q4_K_M.gguf` | Microsoft. Strong reasoning for size. |
| **Gemma 2** | 2B, 9B, 27B | `gemma-2-9b-it-Q4_K_M.gguf` | Google. Good coding and instruction following. |
| **Qwen 2.5** | 0.5B–72B | `Qwen2.5-7B-Instruct-Q4_K_M.gguf` | Alibaba. Multilingual, strong at math/code. |
| **DeepSeek-R1** | 1.5B–70B (distilled) | `DeepSeek-R1-Distill-Llama-8B-Q4_K_M.gguf` | Reasoning-focused distilled models. |
| **CodeLlama** | 7B, 13B, 34B | `codellama-7b-instruct.Q4_K_M.gguf` | Code-specialized Llama variant. |
| **TinyLlama** | 1.1B | `tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf` | Tiny. Useful for testing and CI. |
| **StableLM** | 1.6B, 3B | `stablelm-2-1_6b-chat.Q4_K_M.gguf` | Stability AI. Small and fast. |
| **Yi** | 6B, 9B, 34B | `Yi-1.5-9B-Chat-Q4_K_M.gguf` | 01.AI. Strong multilingual. |
| **Command R** | 35B, 104B | `c4ai-command-r-v01-Q4_K_M.gguf` | Cohere. RAG-optimized. |
| **Falcon** | 7B, 40B, 180B | `falcon-7b-instruct-Q4_K_M.gguf` | TII. |
> **Tip:** For testing and development, start with **TinyLlama 1.1B** (fast, tiny, runs anywhere) or **Llama 3.2 1B** (modern, instruction-tuned, still small enough for CPU).
### Quantization Levels
GGUF models come in different quantization levels that trade quality for size/speed. nxusKit auto-detects the quantization from the filename:
| Quantization | Bits/Weight | Relative Quality | Relative Size | Recommended For |
|---|---|---|---|---|
| `F32` | 32 | Best (reference) | Largest | Accuracy testing only |
| `F16` | 16 | Excellent | ~50% of F32 | GPU with sufficient VRAM |
| `Q8_0` | 8.5 | Near-lossless | ~50% of F16 | Quality-sensitive tasks |
| `Q6_K` | 6.6 | Very good | ~38% of F16 | Good quality/size balance |
| `Q5_K_M` | 5.7 | Good | ~33% of F16 | Balanced |
| `Q5_K_S` | 5.5 | Good | ~32% of F16 | Slightly smaller than K\_M |
| `Q4_K_M` | 4.8 | Acceptable | ~27% of F16 | **Most popular**. Best quality/size tradeoff. |
| `Q4_K_S` | 4.5 | Acceptable | ~26% of F16 | Slightly smaller than K\_M |
| `Q3_K_M` | 3.9 | Degraded | ~22% of F16 | Memory-constrained environments |
| `Q2_K` | 3.4 | Poor | ~18% of F16 | Extreme memory constraints only |
> **Recommendation:** Use **Q4\_K\_M** for most deployments. It provides the best balance of quality, speed, and memory usage.
### Memory Requirements
Approximate RAM needed to load a model (varies by quantization):
| Model Size | Q4\_K\_M | Q8\_0 | F16 |
|---|---|---|---|
| 1B params | ~0.8 GB | ~1.2 GB | ~2 GB |
| 3B params | ~2 GB | ~3.5 GB | ~6 GB |
| 7-8B params | ~4.5 GB | ~8 GB | ~15 GB |
| 13B params | ~8 GB | ~14 GB | ~26 GB |
| 34B params | ~20 GB | ~36 GB | ~68 GB |
| 70B params | ~40 GB | ~72 GB | ~140 GB |
These are approximate. Actual usage depends on context window size, batch size, and KV cache.
### GPU Acceleration
GPU offloading is automatic when available:
| Platform | Acceleration | How to Enable |
|---|---|---|
| macOS (Apple Silicon) | Metal | Automatic — llama.cpp detects Metal at build time |
| Linux (NVIDIA) | CUDA | Install CUDA toolkit; llama-cpp-2 detects at build time |
| Linux (AMD) | ROCm/Vulkan | Vulkan support via llama.cpp build flags |
| Windows (NVIDIA) | CUDA | Install CUDA toolkit |
| All platforms | CPU (AVX2/NEON) | Always available as fallback |
Control GPU offloading with `n_gpu_layers`:
* `-1` — offload all layers to GPU (maximum acceleration)
* `0` — CPU only (default)
* `N` — offload first N layers (partial offloading for limited VRAM)
### Configuration
```json
{
"provider_type": "local",
"model": "/path/to/model.gguf",
"options": {
"backend": "llama-cpp",
"n_gpu_layers": -1,
"context_size": 4096,
"batch_size": 512,
"threads": 8
}
}
```
**Configuration options:**
| Option | Type | Default | Description |
|---|---|---|---|
| `backend` | string | auto-detect | `"llama-cpp"` or `"mistralrs"`. Auto-selects first available if omitted. |
| `n_gpu_layers` | integer | `0` | GPU layer offloading. `-1` = all, `0` = CPU only, `N` = first N layers. |
| `context_size` | integer | model default | Context window size in tokens. |
| `batch_size` | integer | backend default | Prompt processing batch size. Higher = faster prompt processing, more memory. |
| `threads` | integer | auto-detect | CPU thread count. Leave unset for optimal auto-detection. |
### Rust API
```rust
use nxuskit-engine::{LocalRuntimeProvider, ChatRequest, Message};
let provider = LocalRuntimeProvider::builder()
.model_path("/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf")
.n_gpu_layers(-1) // Use GPU
.context_size(4096)
.build()?;
let request = ChatRequest::new("Llama-3.2-1B-Instruct-Q4_K_M.gguf")
.with_message(Message::user("Explain quantum computing in one paragraph."))
.with_temperature(0.7)
.with_max_tokens(256);
let response = provider.chat(&request).await?;
println!("{}", response.content);
```
### Model Discovery
The provider can discover available models from multiple sources:
```rust
let models = provider.list_models().await?;
for model in &models {
println!("{}: {} ({})",
model.id,
model.name,
model.metadata.get("quantization").unwrap_or(&"unknown".into()));
}
```
**Discovery sources** (in priority order):
1. **Explicit path** — The model path in your configuration
2. **Search paths** — Directories you configure (scans for `.gguf` files)
3. **Ollama store** (opt-in) — Discovers models already pulled by Ollama
**Ollama store locations** (auto-detected):
* macOS: `~/.ollama/models`
* Linux: `/usr/share/ollama/.ollama/models` or `~/.ollama/models`
* Windows: `%USERPROFILE%\.ollama\models`
**Environment variables:**
* `NXUSKIT_MODELS` — Custom model search directory
* `OLLAMA_MODELS` — Override Ollama store location
### Model Cache Management
Models stay loaded in memory after first use. You can manage the cache explicitly:
```rust
// Pre-load a model (async, happens in background)
provider.preload_model("/models/llama-3.2-1b.Q4_K_M.gguf").await?;
// Check what's loaded
for info in provider.cached_models() {
println!("{}: {} bytes", info.path, info.memory_bytes.unwrap_or(0));
}
// Free memory
provider.unload_model("/models/llama-3.2-1b.Q4_K_M.gguf");
```
### Capabilities
| Capability | Supported |
|---|---|
| System messages | Yes |
| Streaming | Yes (token-by-token) |
| Vision/images | No |
| JSON mode | No (llama-cpp) / Yes (mistral.rs) |
| Seed (deterministic) | Yes |
| Stop sequences | Yes (up to 4) |
| Temperature | Yes |
| Top-p | Yes |
| Max tokens | Yes |
| Presence penalty | No |
| Frequency penalty | No |
| Tool calling | No |
### Backend Comparison
| Feature | llama.cpp (`provider-local-llama`) | mistral.rs (`provider-local-mistralrs`) |
|---|---|---|
| Maturity | Production-ready | Experimental |
| Language | C++ with Rust bindings | Pure Rust (Candle) |
| Build time | Fast (~30s) | Slow (~3-5 min, pulls Candle) |
| GPU support | Metal, CUDA, Vulkan | Metal, CUDA (via Candle) |
| JSON mode | No | Yes (ISQ support) |
| Chat templates | Manual | Auto-detected from GGUF metadata |
| PagedAttention | No | Yes (CUDA, Apple Silicon) |
| In-situ quantization | No | Yes (load unquantized, quantize at runtime) |
| Binary size impact | Small (~2 MB) | Large (~20 MB, Candle framework) |
***
## HTTP-Based Providers
HTTP-based local providers connect to a separately running inference server. No Cargo feature flags are needed — they use the standard HTTP transport.
### Ollama
Run models locally via [Ollama](https://ollama.com/).
```json
{
"provider_type": "ollama",
"base_url": "http://localhost:11434",
"timeout_ms": 120000
}
```
**Environment variable:** `OLLAMA_HOST` (optional, defaults to `http://localhost:11434`)
**Supported models:** Any model pulled via `ollama pull`, e.g., `llama3.1`, `codellama`, `mistral`, `phi3`
**Capabilities:** System messages, streaming
**Note:** No API key required. The provider connects to a locally running Ollama server. The default timeout is 120 seconds (longer than cloud providers) to accommodate model loading.
### LM Studio
Run models locally via [LM Studio](https://lmstudio.ai/).
```json
{
"provider_type": "lmstudio",
"base_url": "http://localhost:1234/v1",
"timeout_ms": 120000
}
```
**Environment variable:** `LMSTUDIO_HOST` (optional, defaults to `http://localhost:1234/v1`)
**Capabilities:** System messages, streaming
**Note:** No API key required. Start the LM Studio local server before using this provider.
***
## Choosing Between Local Providers
| Consideration | In-Process (local) | Ollama | LM Studio |
|---|---|---|---|
| Setup complexity | Download a GGUF file | Install Ollama + pull model | Install LM Studio + download model |
| External server | None required | Must be running | Must be running |
| Latency | Lowest (no HTTP overhead) | Low (localhost HTTP) | Low (localhost HTTP) |
| Model lifecycle control | Full (preload/unload API) | Managed by Ollama | Managed by LM Studio |
| Memory management | Direct (cache API) | Managed by Ollama | Managed by LM Studio |
| Feature flags needed | Yes (`provider-local-llama`) | No | No |
| Build dependencies | C++ compiler (llama.cpp) | None | None |
| Best for | Embedded/library use, max control | Quick experimentation | GUI-based development |
---
# Z3 Constraint Satisfaction Provider
URL: https://docs.nxus.systems/v0.9.2/nxuskit/reference/providers/z3-solver
The Z3 provider integrates [Microsoft Z3](https://github.com/Z3Prover/z3), an industry-grade SMT (Satisfiability Modulo Theories) solver, into the nxusKit provider interface. It enables constraint satisfaction, optimization, and formal verification problems to be expressed and solved using the same `chat()` / `chat_stream()` API as LLM providers.
Unlike LLM providers, Z3 is deterministic — the same input always produces the same output.
## Configuration
```json
{
"provider_type": "z3",
"timeout_ms": 30000,
"random_seed": 42,
"produce_unsat_core": true,
"logic": "QF_LIA"
}
```
**Configuration options:**
| Option | Type | Default | Description |
|---|---|---|---|
| `timeout_ms` | integer | 30000 | Solver timeout in milliseconds |
| `random_seed` | integer | none | Seed for search heuristics (for reproducibility) |
| `produce_unsat_core` | boolean | false | Extract conflicting constraints when problem is unsatisfiable |
| `logic` | string | auto | SMT logic preset (e.g., `"QF_LIA"`, `"QF_LRA"`, `"QF_BV"`) |
| `max_conflicts` | integer | none | Maximum conflict (branch) limit for search |
| `model_paths` | string\[] | none | Directories to scan for `.smt2` and `.z3` model files |
**Capabilities:** System messages, streaming, JSON mode, seed
## Input Format
The Z3 provider accepts structured JSON as the user message content. The JSON describes variables, constraints, and optionally an optimization objective.
### Variables
```json
{
"variables": [
{"name": "x", "var_type": "integer"},
{"name": "y", "var_type": "integer", "domain": {"min": 1, "max": 100}},
{"name": "flag", "var_type": "boolean"},
{"name": "ratio", "var_type": "real", "domain": {"min": 0.0, "max": 1.0}}
]
}
```
**Variable types:** `integer`, `real`, `boolean`
**Domain constraints** (optional): `min`, `max` for numeric types.
### Constraints
```json
{
"constraints": [
{"constraint_type": "eq", "params": {"left": "x", "right": 42}},
{"constraint_type": "gt", "params": {"left": "y", "right": "x"}},
{"constraint_type": "all_different", "params": {"variables": ["x", "y", "z"]}},
{"constraint_type": "in_range", "params": {"variable": "x", "min": 1, "max": 10}}
]
}
```
**Supported constraint types:**
| Type | Description | Parameters |
|---|---|---|
| `eq` | Equal | `left`, `right` |
| `neq` | Not equal | `left`, `right` |
| `lt` | Less than | `left`, `right` |
| `gt` | Greater than | `left`, `right` |
| `le` | Less than or equal | `left`, `right` |
| `ge` | Greater than or equal | `left`, `right` |
| `add` | Addition expression | `left`, `right` (or `operands` list) |
| `sub` | Subtraction expression | `left`, `right` |
| `mul` | Multiplication expression | `left`, `right` |
| `div` | Division expression | `left`, `right` |
| `and` | Logical AND | `operands` list |
| `or` | Logical OR | `operands` list |
| `not` | Logical NOT | `operand` |
| `implies` | Logical implication | `left`, `right` |
| `iff` | If and only if | `left`, `right` |
| `all_different` | All variables must differ | `variables` list |
| `at_most` | At most N true | `variables`, `n` |
| `at_least` | At least N true | `variables`, `n` |
| `exactly` | Exactly N true | `variables`, `n` |
| `in_range` | Value within range | `variable`, `min`, `max` |
Parameters can reference variable names (strings), literal values (numbers, booleans), or nested expressions.
### Optimization
Add an `objective` field to minimize or maximize a variable:
```json
{
"variables": [...],
"constraints": [...],
"objective": {
"direction": "minimize",
"expression": "cost"
}
}
```
**Directions:** `"minimize"` or `"maximize"`
### Named Constraints
Constraints can be named for unsat core extraction:
```json
{
"constraints": [
{"name": "budget_limit", "constraint_type": "le", "params": {"left": "cost", "right": 1000}},
{"name": "quality_req", "constraint_type": "ge", "params": {"left": "quality", "right": 8}}
]
}
```
When the problem is unsatisfiable and `produce_unsat_core` is enabled, the response includes the names of conflicting constraints.
## Output Format
The response `content` field contains JSON:
### Satisfiable (SAT)
```json
{
"status": "sat",
"assignments": {
"x": 42,
"y": 58,
"flag": true
},
"stats": {
"solve_time_ms": 2,
"num_conflicts": 0,
"num_decisions": 5
}
}
```
### Unsatisfiable (UNSAT)
```json
{
"status": "unsat",
"unsat_core": ["budget_limit", "quality_req"],
"stats": {
"solve_time_ms": 1,
"num_conflicts": 3
}
}
```
### Optimal (Optimization)
```json
{
"status": "optimal",
"assignments": {
"cost": 150,
"quality": 8
},
"objective_value": 150.0,
"stats": {
"solve_time_ms": 15,
"num_solutions_found": 4
}
}
```
## Streaming
* **Satisfaction problems**: Single result chunk (solve is typically \< 1ms).
* **Optimization problems**: Progressive improvement — each improving solution is emitted as a `StreamChunk`, with the final chunk containing `finish_reason` and complete stats.
## Examples
### Basic Satisfaction
```rust
use nxuskit-engine::{Z3Provider, ChatRequest, Message};
let provider = Z3Provider::builder()
.timeout_ms(5_000)
.build()?;
let problem = r#"{
"variables": [
{"name": "x", "var_type": "integer", "domain": {"min": 1, "max": 9}},
{"name": "y", "var_type": "integer", "domain": {"min": 1, "max": 9}},
{"name": "z", "var_type": "integer", "domain": {"min": 1, "max": 9}}
],
"constraints": [
{"constraint_type": "all_different", "params": {"variables": ["x", "y", "z"]}},
{"constraint_type": "eq", "params": {"left": {"add": ["x", "y", "z"]}, "right": 15}}
]
}"#;
let request = ChatRequest::new("z3-solver")
.with_message(Message::user(problem));
let response = provider.chat(&request).await?;
let output: serde_json::Value = serde_json::from_str(&response.content)?;
assert_eq!(output["status"], "sat");
```
### Via C ABI (Go)
```go
provider, err := nxuskit.NewZ3FFIProvider(
nxuskit.WithZ3Timeout(5000),
nxuskit.WithZ3UnsatCore(true),
)
response, err := provider.Chat(ctx, &nxuskit.ChatRequest{
Model: "z3-solver",
Messages: []nxuskit.Message{
{Role: "user", Content: problemJSON},
},
})
```
### Via C ABI (Python)
```python
from nxuskit-py._ffi_provider import create_ffi_provider
provider = create_ffi_provider({
"provider_type": "z3",
"timeout_ms": 5000,
"produce_unsat_core": True,
})
response = provider.chat(model="z3-solver", messages=[
{"role": "user", "content": problem_json}
])
```
## Model Discovery
The Z3 provider can discover pre-defined constraint model files:
```rust
let models = provider.list_models().await?;
// Returns built-in models ("z3-solver", "z3-optimizer") plus
// any .smt2 and .z3 files found in configured model_paths
```
## Use Cases
* **Scheduling**: Resource allocation, timetabling, shift planning
* **Configuration**: Product configuration with constraints, compatibility checking
* **Puzzles**: Sudoku, N-Queens, logic puzzles
* **Verification**: Property checking, invariant validation
* **Optimization**: Cost minimization, resource optimization with constraints
* **Planning**: Task sequencing with dependency and resource constraints
---
# nxus.SYSTEMS Documentation
URL: https://docs.nxus.systems/v0.9.4
import { CardGrid, LinkCard } from '@astrojs/starlight/components';
---
# GitHub Repositories
URL: https://docs.nxus.systems/v0.9.4/github
The public nxus.SYSTEMS GitHub organization is
[github.com/nxus-SYSTEMS](https://github.com/nxus-SYSTEMS).
## Public Repositories
| Repository | What to use it for |
| --- | --- |
| [nxusKit SDK](https://github.com/nxus-SYSTEMS/nxusKit) | Source for the multi-language SDK covering LLM providers, rule engines, constraint solving, Bayesian networks, decision tables, the C ABI, and CLI/Bash workflows. |
| [nxusKit Examples](https://github.com/nxus-SYSTEMS/nxusKit-examples) | Runnable Rust, Go, Python, and CLI/Bash examples for common nxusKit integration patterns. |
| [nxus Codex Plugins](https://github.com/nxus-SYSTEMS/nxus-codex-plugins) | Codex Plugin packages from nxus.SYSTEMS, including nxusKit Celerat. |
| [nxus Docs](https://github.com/nxus-SYSTEMS/nxus-docs) | Source for this public documentation site, hosted at [docs.nxus.systems](https://docs.nxus.systems/). |
## Related Links
- [nxusKit documentation](/v0.9.4/nxuskit/)
- [nxusKit examples documentation](/v0.9.4/nxuskit/examples/)
- [Codex Plugins documentation](/codex-plugins/)
- [Commercial website](https://nxus.systems)
- [Plans](https://nxus.systems/pricing)
---
# nxusKit SDK
URL: https://docs.nxus.systems/v0.9.4/nxuskit
nxusKit is a unified, type-safe SDK for calling LLM providers (Claude, OpenAI, Ollama, and more),
CLIPS rule engines, Z3 constraint solvers, Bayesian networks, and ZEN decision tables — from Rust, Go, Python, and the C ABI.
## Start Here
Install the SDK, configure credentials, and run your first request:
- [Installation](/v0.9.4/nxuskit/getting-started/installation/)
- [First Call](/v0.9.4/nxuskit/getting-started/first-call/)
- [Authentication](/v0.9.4/nxuskit/getting-started/authentication/)
## Browse by Task
- **Build an integration** — Start with [installation](/v0.9.4/nxuskit/getting-started/installation/), then use the [provider model](/v0.9.4/nxuskit/concepts/provider-model/) to choose the right backend.
- **Explore working code** — Browse [examples](/v0.9.4/nxuskit/examples/) for reusable patterns, local model setup, solver workflows, and complete applications.
- **Author rules** — Use the [CLIPS rule authoring guide](/v0.9.4/nxuskit/guides/clips-rule-authoring/) and the [CLIPS session API](/v0.9.4/nxuskit/reference/api-reference/#clips-session-api).
- **Look up contracts** — Use the [API reference](/v0.9.4/nxuskit/reference/api/), [CLI reference](/v0.9.4/nxuskit/reference/cli-reference/), and [provider references](/v0.9.4/nxuskit/reference/providers/cloud-llms/).
- **Manage editions** — Review [feature tiers](/v0.9.4/nxuskit/concepts/tier-system/) and [license activation](/v0.9.4/nxuskit/concepts/licensing/).
---
# Architecture
URL: https://docs.nxus.systems/v0.9.4/nxuskit/concepts/architecture
## Overview
nxusKit is organized around a shared provider model with language-specific
wrappers for Rust, Go, and Python, plus a stable C ABI. Each wrapper exposes
native types while keeping the same core concepts: provider configuration, chat
requests, chat responses, streaming chunks, and structured error handling.
The architecture has four practical layers:
1. **Language wrappers** — Idiomatic SDK surfaces for application code.
2. **Provider abstraction** — A common contract for chat, streaming, capability
discovery, and provider metadata.
3. **Provider implementations** — Cloud LLMs, local LLMs, CLIPS, Z3, Mock,
Loopback, and MCP adapters.
4. **Native boundary** — C ABI functions and ownership rules for embedding and
cross-language integration.
## Component Map
| Component | Role |
|-----------|------|
| Rust SDK | Reference implementation, async provider interface, CLI, and native engine integrations. |
| Go SDK | Go-native provider interface with context cancellation and channel-based streaming. |
| Python SDK | Python-friendly provider creation, chat calls, and FFI access. |
| C ABI | Stable native boundary for providers, responses, streams, errors, and CLIPS sessions. |
| CLI | Shell interface for chat, provider checks, structured JSON workflows, and Pro features. |
| Examples | Runnable patterns and applications that demonstrate cross-language usage. |
## Provider Families
nxusKit providers fall into four broad groups:
| Family | Examples | Behavior |
|--------|----------|----------|
| Cloud LLMs | OpenAI, Anthropic, Groq, Mistral, Fireworks, Together, OpenRouter, Perplexity | Hosted model APIs with provider-specific capabilities. |
| Local LLMs | Ollama, LM Studio, in-process GGUF backends | Local inference for development, privacy, or low-latency use cases. |
| Deterministic engines | CLIPS, Z3 | Repeatable rule evaluation, inference, constraint solving, and optimization. |
| Utility providers | Mock, Loopback, MCP | Testing, integration checks, and tool-oriented workflows. |
See the [Provider Model](/v0.9.4/nxuskit/concepts/provider-model/) for the shared
configuration and request flow.
## Cross-Language Design
The SDK keeps concepts aligned across languages:
| Concept | Rust | Go | C ABI |
|---------|------|----|-------|
| Provider configuration | `ProviderConfig` | `ProviderConfig` | provider config JSON |
| Chat request | `ChatRequest` | `ChatRequest` | request JSON |
| Chat response | `ChatResponse` | `ChatResponse` | response handle + JSON |
| Streaming | async stream | channel stream | callback stream |
| Errors | typed errors | typed errors | `nxuskit_last_error()` |
This lets teams choose a language per service without redesigning provider
selection, request structure, credentials, or feature-gating behavior.
## Native Boundary
The C ABI is the stable integration point for native consumers and higher-level
FFI wrappers. It uses opaque handles for providers, responses, and streams. Any
memory returned across the boundary has a matching free function.
Read the [C ABI Reference](/v0.9.4/nxuskit/reference/api-reference/) before embedding
nxusKit in C, C++, Go FFI, Python FFI, or another native runtime.
## Operational Flow
```text
Application code
-> language wrapper or C ABI
-> provider configuration
-> chat or streaming request
-> provider implementation
-> response, chunks, metadata, or typed error
```
For Pro features, the same call path also checks license state before executing
the feature. Community-tier features continue to run without a license token.
## What to Read Next
- [Installation](/v0.9.4/nxuskit/getting-started/installation/)
- [Provider Model](/v0.9.4/nxuskit/concepts/provider-model/)
- [Streaming](/v0.9.4/nxuskit/guides/streaming/)
- [C ABI Reference](/v0.9.4/nxuskit/reference/api-reference/)
- [CLI Input Format Reference](/v0.9.4/nxuskit/reference/cli-reference/)
- [Examples](/v0.9.4/nxuskit/examples/)
---
# Licensing
URL: https://docs.nxus.systems/v0.9.4/nxuskit/concepts/licensing
## Overview
nxusKit Pro features require a valid license token. This guide covers the
full lifecycle: authentication, activation, deployment, renewal, and
deactivation.
## Quick Start
```bash
# 1. Authenticate with your nxus.systems account
nxuskit-cli license login
# 2. Activate with your Purchase ID / Activation Key from My Products
nxuskit-cli license activate --key --accept-eula
# 3. Accept the End User License Agreement (required once per machine)
nxuskit-cli --accept-eula
# Or pre-accept for CI/CD (see EULA Acceptance below)
# 4. Verify activation
nxuskit-cli license status
# 5. Use Pro features — they just work
```
## EULA Acceptance
nxusKit requires acceptance of the End User License Agreement (EULA) before
use. Acceptance is recorded once per machine and persists across sessions.
### Interactive (TTY)
When running in an interactive terminal, the CLI prompts you to accept the EULA
on first use:
```
nxusKit End User License Agreement
...
Do you accept the EULA? [y/N]:
```
Type `y` and press Enter to accept. Acceptance is stored at
`~/.config/nxuskit/eula_accepted` (mode `0600`).
### Non-interactive (CI/CD)
In non-TTY environments (CI runners, Docker, scripts), the interactive prompt is
suppressed and the CLI exits with an error if the EULA has not been pre-accepted.
**Option 1 — `--accept-eula` flag** (recommended for CI):
```bash
nxuskit-cli --accept-eula license status
```
The flag is accepted on any subcommand. In GitHub Actions:
```yaml
- name: Verify license
run: nxuskit-cli --accept-eula license status
env:
NXUSKIT_LICENSE_TOKEN: ${{ secrets.NXUSKIT_LICENSE_TOKEN }}
```
**Option 2 — Pre-write the acceptance file**:
Create the file before invoking the CLI (useful in container image builds):
```bash
mkdir -p ~/.config/nxuskit
echo "accepted" > ~/.config/nxuskit/eula_accepted
chmod 0600 ~/.config/nxuskit/eula_accepted
```
### Acceptance File
| Path | `~/.config/nxuskit/eula_accepted` |
|------|-----------------------------------|
| Permissions | `0600` (owner read/write only) |
| Content | `accepted` (literal string) |
| Created by | Interactive prompt or `--accept-eula` flag |
---
## Licensing Environments
Release builds default to the production licensing API:
```
https://nxus.systems/licensing-api/v1
```
The production ES256 public key is embedded in release builds. Standard users do not configure the key or endpoint.
Development and test lanes may opt into a non-production endpoint with
`NXUSKIT_LICENSE_SERVER` and may label that lane with
`NXUSKIT_LICENSE_ENVIRONMENT`. These overrides are visible in
`nxuskit-cli license status --json` under `licensing.endpoint`,
`licensing.environment`, and `licensing.signing_key`; they are not silent
fallbacks.
## Offline-First Entitlements
After activation, Pro-gated entitlement checks validate the cached token
locally: signature, expiry, machine binding, product id, edition, and
entitlement claims are checked without contacting the licensing API. The
licensing API is contacted for activation, explicit refresh/sync, or recovery
from a local validation failure.
---
## Token Types
The SDK manages five token shapes:
| Token | Storage | Purpose | Expiry | Machine-bound? |
|-------|---------|---------|--------|----------------|
| **Auth** | `~/.config/nxuskit/auth.json` | Authenticates you with the licensing service | 30 days | No |
| **Developer** | `~/.nxuskit/license.token` | Authorizes purchased Pro SDK features for local developer workstations after storefront checkout | Subscription period | Yes (up to 3 machines) |
| **Deployment** | `NXUSKIT_LICENSE_TOKEN` env var | Authorizes customer shipping/runtime use of products that embed or depend on nxusKit | Never expires | No (org-scoped) |
| **Real Purchase** | `~/.nxuskit/license.token` | Backward-compatible SDK fixture/claim shape; production storefront activations currently issue Developer tokens | Subscription period | Yes |
| **Leased** | `~/.nxuskit/license.token` or `NXUSKIT_LICENSE_TOKEN` | CI/automation license that can be revoked server-side | Short lease, default 72 hours | Yes |
For CI automations that need a working Pro license but also need routine
revocation control, prefer a leased activation key over a long-lived deployment
token. Re-run `nxuskit-cli license activate --key
--accept-eula` on the runner before the 72-hour lease
expires. If the lease is blocked server-side, reactivation fails and any
already-issued token lapses at its normal `exp`.
## Step-by-Step Activation
### 1. Authenticate
Before activating a license, you must authenticate with your nxus.systems
account:
```bash
nxuskit-cli license login
```
This opens your browser to the nxus.systems login page. After logging in,
enter the code shown in your terminal. The auth token is stored at
`~/.config/nxuskit/auth.json` and used automatically for subsequent commands.
Check auth status:
```bash
nxuskit-cli license status
```
### 2. Activate
With authentication complete, activate your license. First-time activations
must accept the EULA:
```bash
nxuskit-cli license activate --key --accept-eula --json
```
The `--accept-eula` flag is recorded in
`~/.config/nxuskit/eula_accepted` (mode `0600`); subsequent activations on
the same machine do not need to repeat it. The `--json` flag is recommended
for scripting — see the JSON output schema in §3.
On success you will see (text mode):
```
Activated. 1/3 machines used.
Token stored: ~/.nxuskit/license.token
```
The license token is stored locally and validated on each SDK
initialization. **Activation uses an extended 30s client timeout
(`EXTENDED_TIMEOUT_SECS = 30`)** to absorb production cold-starts; the
matching proxy timeout extension is in
`nxus_device_auth/services/proxy_client.py::EXTENDED_TIMEOUT_PATHS`.
#### Real-purchase activation (production)
After purchasing a license at `https://nxus.systems/shop`, your purchase
IDs appear at `https://nxus.systems/my/products`. Each card shows the
exact CLI to run:
```bash
nxuskit-cli license activate --key nxus_purchase_ --accept-eula --json
```
Production storefront purchases currently issue `developer` license tokens:
machine-bound, seat-indexed, and valid through the commercial subscription
period. The SDK also accepts the legacy/fixture `real_purchase` claim shape for
compatibility, but it is not the production storefront issuer contract.
Customer shipping/runtime use belongs to the separate `deployment` token flow.
`leased` tokens are designed for CI/automation where revocation control matters — re-activate before the default 72-hour expiry;
blocking the lease server-side prevents future activations and existing tokens
lapse at `exp`.
### 3. Verify
Check your license status at any time:
```bash
nxuskit-cli license status
```
Output includes token type, edition, expiry date, machine count, licensing
environment, endpoint, and signing-key metadata.
For JSON output (useful in scripts):
```bash
nxuskit-cli license status --json
```
### 4. Use Pro Features
Once activated, Pro features work transparently:
```python
# Python — ZEN decision tables (Pro)
from nxuskit import zen_evaluate
result = zen_evaluate(table_path, input_data)
# Python — Solver (Pro)
from nxuskit import SolverConfig
```
```rust
// Rust — ZEN evaluation (Pro)
let result = nxuskit::zen_evaluate(&table, &input)?;
```
```go
// Go — Solver (Pro)
session, err := nxuskit.NewSolverSession(config)
```
## Trial Activation
To start a 30-day Pro trial, first register for an account and authenticate:
```bash
nxuskit-cli license login
nxuskit-cli license activate --trial
```
The trial provides full Pro-tier access for 30 days.
## Deployment Tokens
Deployment tokens are designed for production, CI/CD, and containerized
environments. They have no expiry and no machine binding.
### Setup
Set the deployment token as an environment variable:
```bash
export NXUSKIT_LICENSE_TOKEN=""
```
This works for:
- CI/CD pipelines (GitHub Actions, GitLab CI, Jenkins)
- Docker containers
- Kubernetes pods
- Production servers
- Serverless functions
### Version Ceiling
Deployment tokens include a **version ceiling** (e.g., `0.9`). The token
is valid for any SDK version at or below that ceiling:
- Token ceiling `0.9` → works with v0.9.0, v0.9.1, v0.9.5
- Token ceiling `0.9` → does NOT work with v0.10.0+
When you upgrade the SDK past the ceiling, you will see:
```
Deployment token covers up to v0.9.x. Update your deployment token for v0.10+ support.
```
Organizations with active support subscriptions receive updated deployment
tokens when new major.minor versions are released.
## Token Resolution Chain
The SDK resolves tokens from multiple sources in this precedence order:
| Priority | Source | Use Case |
|----------|--------|----------|
| 1 (highest) | `NXUSKIT_LICENSE_TOKEN` env var | CI/CD, containers |
| 2 | `~/.nxuskit/license.token` file | Local development |
| 3 (lowest) | API parameter | Embedded / programmatic |
The first valid token found is used. This order is the same for static and
dynamic linking modes.
## Multiple Machines
Each developer license supports up to 3 machine activations:
```bash
# Activate on machine 1
nxuskit-cli license activate --key
# → Activated. 1/3 machines used.
# Activate on machine 2
nxuskit-cli license activate --key
# → Activated. 2/3 machines used.
# If all 3 slots are used, deactivate one first:
nxuskit-cli deactivate
# → Deactivated. 2/3 machines used.
```
## Renewal
When your subscription approaches expiry (7 days out), the SDK logs a
once-per-session reminder:
```
Pro license expires in 7 days. Renew at your account dashboard.
```
After expiry, Pro features return:
```
License installation required.
```
Community features continue working without interruption.
## Deactivation
To free a machine activation slot:
```bash
nxuskit-cli deactivate
```
The local token file is removed and the activation count is decremented.
To revoke your auth session:
```bash
nxuskit-cli license logout
```
## Troubleshooting
| Symptom | Cause | Fix |
|---------|-------|-----|
| `License installation required.` | No valid license token found | Run `nxuskit-cli license login`, then `nxuskit-cli license activate --key ` |
| `LicenseExpired` | Subscription lapsed | Renew at your account dashboard |
| `EditionInsufficient` | Community binary | Download Pro binary |
| `VersionCeilingExceeded` | SDK upgraded past token ceiling | Request updated deployment token |
| `FeatureUnavailable` | Multiple possible causes | Run `nxuskit-cli license status` for details |
| Auth token expired | 30-day auth session ended | Run `nxuskit-cli license login` again |
---
# Provider Model
URL: https://docs.nxus.systems/v0.9.4/nxuskit/concepts/provider-model
## Overview
nxusKit presents LLMs, local inference servers, rule engines, solvers, and test
adapters through one provider interface. Your application chooses a
`provider_type`, sends a `ChatRequest`, and receives a structured response. The
same request/response pattern works whether the backend is OpenAI, Anthropic,
Ollama, CLIPS, Z3, Mock, or Loopback.
The goal is portability: application code can switch providers without changing
its surrounding orchestration, logging, retry, or licensing logic.
## Provider Types
| Category | Provider types | Use when |
|----------|----------------|----------|
| Cloud LLMs | `openai`, `claude`, `groq`, `mistral`, `fireworks`, `together`, `openrouter`, `perplexity` | You need hosted models, managed scaling, or provider-specific model quality. |
| Local LLMs | `ollama`, `lmstudio`, `local` | You need local inference, data locality, lower latency, or offline development. |
| Reasoning engines | `clips`, `z3` | You need deterministic rule evaluation, constraint solving, or explainable decisions. |
| Utility providers | `mock`, `loopback`, `mcp` | You need tests, integration checks, or model-context tooling. |
## Configuration Shape
All providers use the same high-level configuration fields:
```json
{
"provider_type": "openai",
"model": "gpt-4o",
"api_key": "sk-...",
"base_url": "https://api.openai.com/v1",
"timeout_ms": 30000,
"options": {}
}
```
Only `provider_type` is always required. API keys can come from explicit
configuration, environment variables, or the credential store. See
[Authentication](/v0.9.4/nxuskit/getting-started/authentication/) for the precedence
rules.
## Request Flow
1. Create a provider from configuration.
2. Build a chat request with a model name and messages.
3. Call `chat()` for a complete response or `chat_stream()` for incremental chunks.
4. Read response content and provider metadata.
```rust
use nxuskit::{ChatRequest, Message, NxuskitProvider, ProviderConfig};
let provider = NxuskitProvider::new(ProviderConfig {
provider_type: "openai".into(),
..Default::default()
})?;
let request = ChatRequest::new("gpt-4o")
.with_message(Message::user("Summarize the provider model."));
let response = provider.chat(request)?;
println!("{}", response.content);
```
## Capabilities
Providers advertise capabilities such as streaming, vision, JSON mode, tool
calling, deterministic seeds, and local model discovery. Use the capability
metadata to choose a provider at runtime instead of hard-coding assumptions.
For provider-specific details, see:
- [Cloud LLM Providers](/v0.9.4/nxuskit/reference/providers/cloud-llms/)
- [Local LLM Providers](/v0.9.4/nxuskit/reference/providers/local-llms/)
- [Expert System & Utility Providers](/v0.9.4/nxuskit/reference/providers/expert-systems/)
- [Z3 Constraint Satisfaction Provider](/v0.9.4/nxuskit/reference/providers/z3-solver/)
## Choosing a Provider
| Need | Start with |
|------|------------|
| General hosted chat, tools, and JSON output | Cloud LLM provider |
| Local development without external API calls | Ollama or LM Studio |
| Embedded local inference with direct model lifecycle control | In-process local provider |
| Deterministic business rules | CLIPS |
| Constraint solving and optimization | Z3 |
| Unit tests with predictable responses | Mock or Loopback |
---
# Tier System
URL: https://docs.nxus.systems/v0.9.4/nxuskit/concepts/tier-system
## Overview
nxusKit SDK uses a dual-edition model for the public SDK surface.
The public `nxusKit` repository contains nxusKit SDK Community Edition, which is free and open source. CE is not a trial, teaser, or time-limited evaluation; it is intended to remain useful on its own. We do not move released CE features behind the Pro paywall, and code released as CE remains available under its open-source license.
Community Edition is useful on its own without Pro. The public `nxusKit-examples` repository labels examples by edition, so developers can see which workflows run with CE alone and which require Pro.
nxusKit SDK Pro adds proprietary commercial capabilities for teams that need solver-backed workflows, ZEN decision tables, plugin loading, and trust-policy features. Pro is distributed under a paid, trial, or evaluation entitlement. **Enterprise** adds delegated trust and custom plugin configuration for large organizations.
## Feature Matrix
| Feature Domain | Community | Pro | Enterprise |
|----------------|:---------:|:---:|:----------:|
| LLM Cloud Providers (OpenAI, Claude, xAI Grok, Groq, Mistral, Fireworks, Together, OpenRouter, Perplexity) | Yes | Yes | Yes |
| LLM Local Providers (Ollama, LM Studio) | Yes | Yes | Yes |
| CLIPS Rule Engine (ClipsSession API) | Yes | Yes | Yes |
| Bayesian Network Inference | Yes | Yes | Yes |
| Auth Helper (API-key management, credential store) | Yes | Yes | Yes |
| Tool Calling / Function Calling | Yes | Yes | Yes |
| Streaming & Token Usage | Yes | Yes | Yes |
| Retry & Adaptive Rate Limiting | Yes | Yes | Yes |
| Vision / Image Support | Yes | Yes | Yes |
| OAuth Authentication Infrastructure | Yes | Yes | Yes |
| Cross-language Parity (Rust, Go, Python) | Yes | Yes | Yes |
| Static + Dynamic Linking | Yes | Yes | Yes |
| **ZEN Decision Tables** | — | Yes | Yes |
| **Constraint Solver (Z3-backed)** | — | Yes | Yes |
| **Plugin Loading & Trust Policy** | — | Yes | Yes |
| **MCP (Model Context Protocol)** | — | Yes | Yes |
| **CLIPS Advanced (programmatic rules, session persistence)** | — | Yes | Yes |
| **Custom Plugin Configuration Paths** | — | — | Yes |
| **Delegated Trust Roots** | — | — | Yes |
| **Priority Support** | — | — | Yes |
## Numerical Limits
| Limit | Community | Pro | Enterprise |
|-------|:---------:|:---:|:----------:|
| Max concurrent CLIPS sessions | 16 | 64 | 256 |
| Max cached rulebases | 8 | 32 | 128 |
| Max rules per session | 500 | 5,000 | 50,000 |
| Max facts per session | 10,000 | 100,000 | 1,000,000 |
| Max Bayesian network nodes | 50 | 500 | 5,000 |
| Max solver constraints | — | 10,000 | 100,000 |
| Machine activations (developer tokens) | — | 3 | Unlimited |
## SDK Wrapper Availability
All editions provide wrappers for all three languages:
| Language | Package | Install |
|----------|---------|---------|
| Rust | `nxuskit` | `cargo add nxuskit` |
| Go | `nxuskit` | `go get github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go` |
| Python | `nxuskit-py` | `pip install nxuskit-py` |
## Example Tier Assignments
| Example | Tier | Reason |
|---------|------|--------|
| LLM basics, streaming, tool calling | Community | Uses cloud/local LLM providers |
| CLIPS basics, CLIPS-LLM hybrid | Community | CLIPS engine is Community-tier |
| Bayesian network inference | Community | BN inference is Community-tier |
| Gamer (game AI solver) | **Pro** | Uses Z3 constraint solver |
| Racer (optimization) | **Pro** | Uses Z3 constraint solver |
| Ruler (rule evaluation) | **Pro** | Uses ZEN decision tables |
| Solver (generic CSP) | **Pro** | Uses Z3 constraint solver |
| Riffer (music generation) | **Pro** | Uses solver + CLIPS pipeline |
| Sweeper (minesweeper AI) | **Pro** | Uses Z3 constraint solver |
## Licensing
| Aspect | Community | Pro | Enterprise |
|--------|-----------|-----|------------|
| License type | Open-source | Commercial subscription | Commercial subscription |
| Token required | No | Yes (developer or deployment) | Yes |
| Machine activations | N/A | Up to 3 per license | Unlimited |
| Deployment tokens | N/A | Unlimited instances, no per-seat fees | Unlimited |
| Version ceiling | N/A | Locked to major.minor at purchase time | Locked to major.minor |
| Trial | N/A | 30-day trial (registration required) | Contact sales |
## Getting Started with Pro
1. Create an account and register for a trial or purchase a license
2. Authenticate: `nxuskit-cli license login`
3. Activate on your machine: `nxuskit-cli license activate --key `
4. For CI/CD: set `NXUSKIT_LICENSE_TOKEN` with your deployment token
See the [License Activation Guide](/v0.9.4/nxuskit/concepts/licensing/) for the full workflow.
---
# nxusKit Examples
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples
[](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE)



**[Examples Docs](https://docs.nxus.systems/nxuskit/examples/)** · **[SDK Docs](https://docs.nxus.systems/nxuskit/)** · **[nxusKit SDK](https://github.com/nxus-SYSTEMS/nxusKit)** · **[Examples Portfolio](https://nxus.systems/examples)** · **[Website](https://nxus.systems)**
34 production-quality examples for the nxusKit SDK in Rust, Go, and Python, plus selected CLI/Bash implementations for shell-first orchestration — covering LLM patterns, CLIPS rule engines, Z3 constraint solvers, Bayesian networks, and ZEN decision tables.
## A Word About CLIPS
During its development at NASA from 1985 to 1996, the primary CLIPS
contributors were: Robert Savely, who conceived and championed the project;
Chris Culbert, who managed the project; Gary Riley and Brian Dantes, who were
the lead developers; and Frank Lopez, who developed the first version. Since
leaving NASA in 1996, Gary Riley has maintained CLIPS as public domain
software.
## Quick Start
```bash
# 1. Install the SDK (see https://docs.nxus.systems/nxuskit/getting-started/installation/)
# 2. Set up this project
source ~/.nxuskit/sdk/current/scripts/setup-sdk.sh # Go, env vars, library paths
./scripts/setup-sdk-symlink.sh # Rust Cargo paths override
# 3. Run an example
cargo run --manifest-path examples/patterns/basic-chat/rust/Cargo.toml # Rust
go run -tags nxuskit ./examples/patterns/basic-chat/go # Go
python examples/patterns/basic-chat/python/main.py # Python
```
## Examples
### Patterns — Reusable SDK integration patterns
| Example | Edition | Description | Languages |
|---------|---------|-------------|-----------|
| [basic-chat](/v0.9.4/nxuskit/examples/patterns/basic-chat/) | Community | Basic chat completion with a simple prompt | Rust, Go, Python |
| [streaming](/v0.9.4/nxuskit/examples/patterns/streaming/) | Community | Streaming chat completion with real-time output | Rust, Go, Python |
| [multi-provider](/v0.9.4/nxuskit/examples/patterns/multi-provider/) | Community | Using multiple providers in one application | Rust, Go, Python, CLI/Bash |
| [convenience-api](/v0.9.4/nxuskit/examples/patterns/convenience-api/) | Community | LiteLLM-style convenience API usage | Rust, Go |
| [blocking-api](/v0.9.4/nxuskit/examples/patterns/blocking-api/) | Community | Synchronous blocking API for simpler use cases | Rust, Go |
| [capability-detection](/v0.9.4/nxuskit/examples/patterns/capability-detection/) | Community | Detecting provider capabilities at runtime | Rust, Go, CLI/Bash |
| [cost-routing](/v0.9.4/nxuskit/examples/patterns/cost-routing/) | Community | Cost-aware provider routing and selection | Rust, Go, Python, CLI/Bash |
| [polymorphic](/v0.9.4/nxuskit/examples/patterns/polymorphic/) | Community | Polymorphic provider patterns with trait objects | Rust, Go |
| [retry-fallback](/v0.9.4/nxuskit/examples/patterns/retry-fallback/) | Community | Retry and fallback strategies across providers | Rust, Go, Python, CLI/Bash |
| [structured-output](/v0.9.4/nxuskit/examples/patterns/structured-output/) | Community | JSON mode and structured output generation | Rust, Go, Python, CLI/Bash |
| [timeout-config](/v0.9.4/nxuskit/examples/patterns/timeout-config/) | Community | Timeout configuration and connection management | Rust, Go, Python |
| [token-budget](/v0.9.4/nxuskit/examples/patterns/token-budget/) | Community | Token budget management and cost estimation | Rust, Go, Python, CLI/Bash |
| [vision](/v0.9.4/nxuskit/examples/patterns/vision/) | Community | Vision and multimodal capabilities with images | Rust, Go, Python, CLI/Bash |
| [auth-helper](/v0.9.4/nxuskit/examples/patterns/auth-helper/) | Community | OAuth login flow and credential management helper | Rust, Go |
| ↳ `status` | | List provider authentication status and stored credentials | |
| ↳ `set` | | Store an API key for a specific provider | |
| ↳ `remove` | | Remove a stored API key for a provider | |
| ↳ `dashboard` | | Open provider credential dashboard in browser | |
| [solver](/v0.9.4/nxuskit/examples/patterns/solver/) | Pro | Z3 constraint solver integration via nxusKit SDK | Rust, Go, Python, CLI/Bash |
| ↳ `theme-park` | | Budget and space planning for a theme park with rides, food courts, and entertainment zones | |
| ↳ `space-colony` | | Resource allocation for a space colony dealing with solar storm what-if scenarios | |
| ↳ `fantasy-draft` | | Fantasy sports draft optimization under salary cap with injury what-if analysis | |
| ↳ real-world: **Theme Park Planning** | | Facility layout, capital budgeting, resource allocation | |
| ↳ real-world: **Space Colony Planning** | | Infrastructure sizing, capacity planning, disaster recovery modeling | |
| ↳ real-world: **Fantasy Sports Draft** | | Portfolio optimization, team composition, auction bidding strategies | |
| [bayesian-inference](/v0.9.4/nxuskit/examples/patterns/bayesian-inference/) | Community | Bayesian network inference via nxusKit SDK | Rust, Go, Python, CLI/Bash |
| ↳ `haunted-house` | | Investigate a haunted house — is it a ghost or a raccoon? | |
| ↳ `coffee-shop` | | Diagnose bad espresso from grind size, temperature, and bean age | |
| ↳ `plant-doctor` | | Diagnose a sick plant from overwatering, nutrient, and disease evidence | |
| ↳ real-world: **Haunted House** | | Fault diagnosis, anomaly detection, sensor fusion from multiple noisy sensors pointing to hidden causes | |
| ↳ real-world: **Coffee Shop** | | Manufacturing quality control, process parameter tuning, root cause analysis in production | |
| ↳ real-world: **Plant Doctor** | | Medical diagnosis, agricultural advisory systems, multi-symptom differential diagnosis | |
| [solver-what-if](/v0.9.4/nxuskit/examples/patterns/solver-what-if/) | Pro | What-if scenario analysis with solver scoping | Rust, Go, Python, CLI/Bash |
| ↳ `wedding` | | Wedding budget planning with $25k constraint and vendor what-if scenarios | |
| ↳ `mars` | | Mars colony resource allocation with dust storm what-if disruptions | |
| ↳ `recipe` | | Recipe scaling with vegan substitution — may be UNSAT | |
| ↳ real-world: **Wedding Budget Planning** | | Event planning, capital budgeting, portfolio allocation | |
| ↳ real-world: **Mars Colony Planning** | | Infrastructure sizing, supply chain planning, disaster preparedness | |
| ↳ real-world: **Recipe Scaling** | | Manufacturing scaling, formulation optimization, process engineering | |
### Integrations — Combining SDK features
| Example | Edition | Description | Languages |
|---------|---------|-------------|-----------|
| [ollama](/v0.9.4/nxuskit/examples/integrations/ollama/) | Community | Using Ollama for local inference | Rust, Go, Python |
| [lmstudio](/v0.9.4/nxuskit/examples/integrations/lmstudio/) | Community | Using LM Studio for local inference | Rust, Go |
| [alert-triage](/v0.9.4/nxuskit/examples/integrations/alert-triage/) | Community | Alert triage with LLM-powered analysis | Rust, Go, CLI/Bash |
| [cli-assistant](/v0.9.4/nxuskit/examples/integrations/cli-assistant/) | Community | Interactive CLI assistant with LLM backend | Rust, Go |
| [clips-basics](/v0.9.4/nxuskit/examples/integrations/clips-basics/) | Community | CLIPS rule engine basics via nxusKit SDK | Rust, Go, CLI/Bash |
| [clips-llm-hybrid](/v0.9.4/nxuskit/examples/integrations/clips-llm-hybrid/) | Community | Hybrid CLIPS rules + LLM reasoning | Rust, Go, Python, CLI/Bash |
| [common-sense-guardrails](/v0.9.4/nxuskit/examples/integrations/common-sense-guardrails/) | Community Runs in Community Edition. Pro adds optional Solver and ZEN proof stages. | Progressive LLM guardrails with Community CLIPS validation and optional Pro proof stages | Python, CLI/Bash |
| ↳ `car-wash` | | Catch the classic car-wash walk-vs-drive failure with object-presence rules and optional solver proof | |
| ↳ `coupon-stack` | | Reject promotion stacking that violates eligibility and margin policy, with optional ZEN validation | |
| ↳ `pallet-door` | | Block unsafe warehouse advice that ignores dimensional clearance, with optional solver what-if | |
| ↳ `cold-chain` | | Prevent cheaper logistics recommendations that violate handling requirements, with optional ZEN validation | |
| ↳ real-world: **LLM answer validation** | | Catch plausible recommendations that fail physical, operational, or policy preconditions before they reach users | |
| ↳ real-world: **Policy enforcement** | | Turn free-form answers into facts, apply deterministic rules, and produce auditable repair context | |
| ↳ real-world: **Operational decision support** | | Preserve fast LLM drafting while requiring concrete feasibility evidence for workflow-critical recommendations | |
| [model-research-harness](/v0.9.4/nxuskit/examples/integrations/model-research-harness/) | Community Runs in Community Edition. Future Pro profiles may add Solver portfolio optimization and ZEN decision tables. | Python-first harness for provider-neutral model research, Promptfoo import, CLIPS policy, Bayesian scoring, and dry-run lifecycle recommendations | Python, CLI/Bash |
| ↳ `basic-ticket-routing` | | Run a credentials-free support ticket classification research smoke | |
| ↳ `promptfoo-import` | | Import a Promptfoo config and run the converted nxusKit harness matrix | |
| ↳ `software-dev` | | Evaluate code analysis, bug finding, patching, generation, refactoring, and review outputs | |
| ↳ real-world: **Model evaluation** | | Score model candidates against task-specific outputs and report confidence instead of relying on ad hoc impressions | |
| ↳ real-world: **Provider comparison** | | Compare local and cloud providers through one provider-neutral workflow while keeping capability claims honest | |
| ↳ real-world: **Lifecycle policy** | | Generate dry-run pull, pin, keep, or retest recommendations bounded by deterministic policy | |
| ↳ real-world: **Software development workflow research** | | Exercise code analysis, bug finding, bugfixing, generation, refactoring, and review scenarios with public-safe fixtures | |
| [bn-solver-clips-pipeline](/v0.9.4/nxuskit/examples/integrations/bn-solver-clips-pipeline/) | Pro | Three-stage BN prediction → Solver optimization → CLIPS safety pipeline | Rust, Go, CLI/Bash |
| ↳ `festival` | | Music festival staging — crowd predictions drive band scheduling and safety | |
| ↳ `rescue` | | Search and rescue — survivor probability drives team assignment and safety checks | |
| ↳ `bakery` | | Bakery scheduling — demand forecasts drive oven allocation and allergen separation | |
| ↳ real-world: **Event planning** | | Predict attendance, optimize resource allocation, enforce safety codes | |
| ↳ real-world: **Emergency response** | | Estimate survival windows, deploy rescue assets, enforce operational protocols | |
| ↳ real-world: **Manufacturing** | | Forecast demand, schedule production, enforce quality and safety standards | |
| ↳ real-world: **Logistics** | | Predict delivery volumes, optimize fleet routing, enforce regulatory compliance | |
| ↳ real-world: **Healthcare** | | Predict patient load, optimize staff scheduling, enforce clinical safety protocols | |
| [llm-solver-hybrid](/v0.9.4/nxuskit/examples/integrations/llm-solver-hybrid/) | Pro | Hybrid LLM + Z3 solver problem solving | Rust, Go, Python, CLI/Bash |
| ↳ `seating` | | Wedding dinner seating — 12 guests across 3 tables with constraints | |
| ↳ `dungeon` | | Dungeon layout — 5 rooms with boss and treasure placement rules | |
| ↳ `road-trip` | | Road trip planning — 14 days across 5 national parks with preferences | |
| [bn-structure-learning](/v0.9.4/nxuskit/examples/integrations/bn-structure-learning/) | Community | Bayesian network structure learning from data | Rust, Go, Python |
| ↳ `golf` | | Golf course conditions — weather, soil, and maintenance factor learning | |
| ↳ `bmx` | | BMX performance — skill level, technique, and jump factor learning | |
| ↳ `sourdough` | | Sourdough baking — feeding schedule, flour type, and temperature factor learning | |
| ↳ real-world: **Epidemiology** | | Discover disease risk factor relationships from patient records | |
| ↳ real-world: **Manufacturing** | | Identify root causes of defects from production data | |
| ↳ real-world: **Finance** | | Map causal relationships between economic indicators | |
| ↳ real-world: **Genomics** | | Learn gene regulatory networks from expression data | |
| ↳ real-world: **Quality control** | | Find which process parameters affect product quality | |
| [zen-decisions](/v0.9.4/nxuskit/examples/integrations/zen-decisions/) | Pro | ZEN decision table evaluation via nxusKit SDK | Rust, Go, Python, CLI/Bash |
| ↳ `maze-rat` | | First Hit Policy — route a maze runner through personality-driven decisions | |
| ↳ `potion` | | Collect Hit Policy — match ingredient lists against brewing recipes | |
| ↳ `food-truck` | | Expression Nodes — compute dynamic pricing with conditional logic | |
### Apps — Complete applications
| Example | Edition | Description | Languages |
|---------|---------|-------------|-----------|
| [puzzler](/v0.9.4/nxuskit/examples/apps/puzzler/) | Pro | Multi-approach puzzle solver comparing CLIPS, LLM, and hybrid strategies | Rust, Go |
| ↳ `sudoku` | | Solve Sudoku puzzles using CLIPS constraint propagation | |
| ↳ `set-game` | | Find valid SET card combinations using CLIPS pattern matching | |
| ↳ `compare` | | Side-by-side comparison of CLIPS, LLM, and hybrid solvers | |
| [racer](/v0.9.4/nxuskit/examples/apps/racer/) | Pro | CLIPS vs LLM head-to-head benchmarking tool | Rust, Go |
| ↳ `race` | | Head-to-head CLIPS vs LLM race on a single problem | |
| ↳ `benchmark` | | Statistical benchmarking with multiple runs and timing | |
| ↳ `list` | | List all available problems with difficulty ratings | |
| ↳ `describe` | | Show detailed description of a specific problem | |
| [riffer](/v0.9.4/nxuskit/examples/apps/riffer/) | Pro | Music sequence analysis and transformation tool (still learning to shred) | Rust, Go |
| ↳ `analyze` | | Analyze a music sequence for key, intervals, and rhythm patterns | |
| ↳ `score` | | Score a sequence on six musical dimensions | |
| ↳ `transform` | | Transform a sequence — transpose, invert, or retrograde | |
| ↳ `convert` | | Convert between MIDI and MusicXML formats | |
| [ruler](/v0.9.4/nxuskit/examples/apps/ruler/) | Pro | LLM-powered CLIPS rule generator with automatic validation | Rust, Go, CLI/Bash |
| ↳ `generate` | | Generate CLIPS rules from natural language descriptions | |
| ↳ `validate` | | Validate CLIPS rule syntax and semantic correctness | |
| ↳ `save` | | Save generated rules to a file for later use | |
| ↳ `load` | | Load previously saved rules from a file | |
| ↳ `examples` | | Run progressive complexity examples demonstrating rule generation | |
| [arbiter](/v0.9.4/nxuskit/examples/apps/arbiter/) | Pro | CLIPS-validated LLM retry app with rule-based answer verification | Rust, Go, CLI/Bash |
| ↳ `classification` | | Categorize input text into specified categories | |
| ↳ `extraction` | | Extract structured information from unstructured text | |
| ↳ `reasoning` | | Perform logical inference and multi-step reasoning | |
## SDK Editions
| Badge | Meaning |
|-------|---------|
| **Community** | Runs with the free OSS SDK |
| **Pro** | Requires a Pro license ([activation guide](https://github.com/nxus-SYSTEMS/nxusKit)) |
Edition labels describe the minimum runnable edition for the default path. A Community example can still list optional Pro enhancements; those stages are disabled by default and require a Pro entitlement only when you run them.
See `conformance/example-tiers.json` for the full tier map.
## Project Structure
```
examples/
├── patterns/ Community-tier reusable patterns
├── integrations/ SDK feature combinations
├── apps/ Complete applications (mostly Pro tier)
└── shared/ Shared libraries and helpers (Rust, Go, Python, CLI/Bash)
conformance/ Example manifest and tier definitions
scripts/ Build and test helpers
```
## Building
All examples require the nxusKit SDK. Run these once after cloning:
```bash
# Set up Go workspace, env vars, and native library paths
source ~/.nxuskit/sdk/current/scripts/setup-sdk.sh
# Set up Rust Cargo paths override (generates .cargo/config.toml)
./scripts/setup-sdk-symlink.sh
```
The first script creates Go workspace files and exports environment variables. The second generates a `.cargo/config.toml` that tells Cargo where to find the installed Rust SDK (the generated file is `.gitignore`d — each developer runs this once).
### Rust
```bash
cargo run --manifest-path examples///rust/Cargo.toml
```
### Go
```bash
go run -tags nxuskit ./examples///go/cmd
```
### Python
```bash
python examples///python/main.py
```
### CLI/Bash
```bash
cd examples///bash
make run
```
---
Built with gratitude for the open-source projects that make nxusKit possible.
See [ACKNOWLEDGEMENTS.md](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/ACKNOWLEDGEMENTS.md) for a curated list of key projects.
---
## License
nxusKit Examples is dual-licensed under MIT or Apache 2.0, at your option. See [LICENSE](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE), [LICENSE-MIT](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE-MIT), and [LICENSE-APACHE](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE-APACHE).
Copyright 2025-2026 nxus.SYSTEMS LLC.
---
# Arbiter - Auto-Retry LLM with CLIPS Validation
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/apps/arbiter
A command-line tool demonstrating the Solver pattern: using CLIPS rules to evaluate LLM output quality and automatically retry with adjusted parameters when validation fails.
> Stop accepting unreliable LLM output — validate every response against CLIPS rules and retry automatically until your standards are met.
**Scenarios**: `classification` · `extraction` · `reasoning`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** CLIPS-validated LLM retry app with rule-based answer verification
- **Scenario:** Submit questions to an LLM and validate answers against CLIPS rules, retrying on validation failure
- **`tech_tags` in manifest:** `CLIPS, LLM` — example id **`arbiter`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Real-World Application
Operations research tool, constraint modeling workbench.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
Solver
## CLIPS integration path (validation)
Go CLIPS validation uses **provider chat** with local `go/clips_wire.go` types mirroring `ClipsInput` / `ClipsOutput`. For **Session API** access, use `nxuskit.ClipsSession`. Reference: `conformance/clips-json-contract.json`; nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/arbiter`:
cd rust && cargo build
cd go && make build
```
## Features
- **LLM Output Validation** - Use CLIPS rules to evaluate response quality
- **Automatic Retry** - Retry with adjusted parameters on validation failure
- **Configurable Strategies** - Define retry strategies for different failure modes
- **Multiple Conclusion Types** - Classification, extraction, and reasoning tasks
- **Scoring System** - Score attempts based on validation results
## Installation
### Rust
```bash
cd examples/apps/arbiter/rust
cargo build --release
```
### Go
```bash
cd examples/apps/arbiter/go
make build
```
## Run
### Rust
```bash
cd examples/apps/arbiter/rust
# Show help
cargo run -- --help
# Run classification task
cargo run -- -t classification -i "This product is amazing!" --categories "positive,negative,neutral"
# Run with custom config
cargo run -- -c config.yaml -i "Analyze this text"
# Run extraction task
cargo run -- -t extraction -i "John works at Acme Corp in New York"
# Verbose mode
cargo run -- -v -t reasoning -i "If A implies B and B implies C, what can we conclude about A and C?"
```
### Go
```bash
cd examples/apps/arbiter/go
# Show help
./bin/arbiter --help
# Run classification
./bin/arbiter -t classification -i "Great service!" --categories "positive,negative,neutral"
```
## Command Line Options
```
USAGE:
arbiter [OPTIONS] -i
OPTIONS:
-c, --config Configuration file path
-i, --input Input text to process
-t, --type Conclusion type: classification, extraction, reasoning
--categories Comma-separated categories for classification
--max-retries Maximum retry attempts (default: 3)
-v, --verbose Show detailed progress
-h, --help Show help message
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/arbiter --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/arbiter --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Conclusion Types
### Classification
Categorize input into predefined categories.
```bash
arbiter -t classification -i "I love this!" --categories "positive,negative,neutral"
```
### Extraction
Extract structured information from text.
```bash
arbiter -t extraction -i "Contact John at john@example.com or 555-1234"
```
### Reasoning
Perform logical reasoning and inference.
```bash
arbiter -t reasoning -i "All cats are mammals. Whiskers is a cat. What is Whiskers?"
```
## Configuration
Create a YAML configuration file for custom settings:
```yaml
# arbiter-config.yaml
max_retries: 5
strategies:
- failure_type: invalid_category
adjustments:
temperature: -0.2
prompt_suffix: "Choose only from the given categories."
- failure_type: incomplete_extraction
adjustments:
temperature: 0
prompt_suffix: "Extract all mentioned entities."
- failure_type: invalid_reasoning
adjustments:
temperature: -0.1
prompt_suffix: "Show your reasoning step by step."
```
## Example Output
### Classification Result
```
=== Solver: Classification Task ===
Input: "This product exceeded my expectations!"
Categories: positive, negative, neutral
Attempt 1:
LLM Response: "positive"
Validation: PASSED
Score: 100
Result: positive (1 attempt, 45ms)
```
### With Retry
```
=== Solver: Classification Task ===
Input: "It's okay I guess"
Categories: positive, negative, neutral
Attempt 1:
LLM Response: "somewhat positive"
Validation: FAILED (invalid category)
Strategy: Reduce temperature, clarify categories
Attempt 2:
LLM Response: "neutral"
Validation: PASSED
Score: 95
Result: neutral (2 attempts, 1.2s)
```
## Retry Strategies
The arbiter includes default strategies for common failure modes:
| Failure Type | Adjustment |
|--------------|------------|
| Invalid category | Lower temperature, clarify options |
| Incomplete extraction | Reset temperature, request all entities |
| Invalid reasoning | Lower temperature, request step-by-step |
| Confidence too low | Increase temperature slightly |
| Format error | Add format examples to prompt |
## Architecture
```
arbiter/
├── rust/
│ ├── src/main.rs # CLI entry point
│ └── Cargo.toml
├── go/
│ ├── cmd/main.go # CLI entry point
│ ├── solver.go # Core solver logic
│ ├── strategies.go # Retry strategies
│ ├── validator.go # CLIPS validation
│ └── go.mod
└── shared/
├── rules/ # CLIPS validation rules
└── configs/ # Example configurations
```
## How It Works
1. **Initial Request**: Send input to LLM with configured prompt
2. **Validation**: Pass LLM response through CLIPS validation rules
3. **Evaluation**: Score the response based on validation results
4. **Retry Decision**: If validation fails, find matching retry strategy
5. **Adjustment**: Apply strategy adjustments (temperature, prompt, etc.)
6. **Repeat**: Retry up to max_retries times
7. **Result**: Return best successful attempt or highest-scoring failure
## Notes
- CLIPS validation rules are in `shared/rules/classification-eval.clp`
- Build Go with `-tags=clips` for real ClipsProvider integration
- LLM approach requires API key (ANTHROPIC_API_KEY or OPENAI_API_KEY)
## Testing
```bash
# Rust
cd examples/apps/arbiter/rust
cargo test
# Go
cd examples/apps/arbiter/go
go test -v ./...
```
## License
Part of the nxusKit project.
---
# Puzzler - Puzzle Solver Comparison
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/apps/puzzler
A command-line tool for comparing three approaches to solving logic puzzles: CLIPS-only, LLM-only, and Hybrid.
> Compare CLIPS rule-based constraint solving against LLM reasoning side by side, then combine both in a hybrid approach for real puzzle problems.
**Scenarios**: `sudoku` · `set-game` · `compare`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS · Solver
- **Summary:** Multi-approach puzzle solver comparing CLIPS, LLM, and hybrid strategies
- **Scenario:** Compare CLIPS rule-based, LLM reasoning, and hybrid approaches for solving logic puzzles
- **`tech_tags` in manifest:** `CLIPS, LLM, Solver` — example id **`puzzler`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Real-World Application
Educational puzzle solver, constraint programming tutorial.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
Solver
## CLIPS integration path (CLIPS-only / hybrid modes)
The Go CLIPS solver path uses **provider chat** (`go/clips_wire.go` mirrors `ClipsInput` / `ClipsOutput` JSON). It is not the **Session API** (`nxuskit.ClipsSession`). See `conformance/clips-json-contract.json` and nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/puzzler`:
cd rust && cargo build
cd go && make build
```
## Features
- **Sudoku Puzzles** - Solve Sudoku puzzles of varying difficulty
- **Set Game** - Find valid sets in Set card game hands
- **Three Approaches**:
- **CLIPS-only**: Pure rule-based constraint propagation
- **LLM-only**: Pure LLM reasoning
- **Hybrid**: CLIPS primary with LLM fallback for stuck states
- **Comparison Mode** - Run all approaches and compare results
## Installation
### Rust
```bash
cd examples/apps/puzzler/rust
cargo build --release
```
### Go
```bash
cd examples/apps/puzzler/go
make build
```
## Run
### Rust
```bash
cd examples/apps/puzzler/rust
# Show help
cargo run -- --help
# Solve a Sudoku puzzle
cargo run -- sudoku -p easy
# Compare all approaches on Sudoku
cargo run -- sudoku --compare
# Play Set game
cargo run -- set -p random
# Compare approaches on Set game
cargo run -- set --compare
```
### Go
```bash
cd examples/apps/puzzler/go
# Show help
./bin/puzzler --help
# Solve a Sudoku puzzle
./bin/puzzler sudoku -p easy
# Compare all approaches
./bin/puzzler sudoku --compare
```
## Command Line Options
```
USAGE:
puzzler [OPTIONS]
GAMES:
sudoku Solve Sudoku puzzles
set Find sets in Set game cards
OPTIONS:
-p, --puzzle Puzzle identifier (easy, medium, hard, expert, or custom)
-a, --approach Solver approach: clips, llm, hybrid (default: hybrid)
-c, --compare Compare all three approaches
-v, --verbose Show detailed solving steps
-h, --help Show help message
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/puzzler --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/puzzler --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Puzzle Types
### Sudoku
Difficulty levels:
- **easy** - Many given numbers, straightforward solving
- **medium** - Moderate difficulty
- **hard** - Requires advanced techniques
- **expert** - Very few givens, requires backtracking
### Set Game
Find valid sets where each attribute (color, shape, shading, number) is either all the same or all different across three cards.
## Example Output
### Sudoku Comparison
```
=== Sudoku Puzzle: easy ===
Approach | Time | Solved | Moves
--------------|---------|--------|-------
CLIPS-only | 12ms | Yes | 47
LLM-only | 2.3s | Yes | 52
Hybrid | 15ms | Yes | 47
Winner: CLIPS-only (fastest)
```
### Set Game
```
=== Set Game: 12 cards ===
Found 3 valid sets:
Set 1: Red-Oval-Solid-1, Red-Oval-Striped-2, Red-Oval-Empty-3
Set 2: Green-Diamond-Solid-1, Purple-Diamond-Striped-1, Red-Diamond-Empty-1
Set 3: ...
```
## Architecture
```
puzzler/
├── rust/
│ ├── src/main.rs # CLI entry point
│ └── Cargo.toml
├── go/
│ ├── cmd/main.go # CLI entry point
│ ├── sudoku.go # Sudoku solver logic
│ ├── setgame.go # Set game solver logic
│ └── go.mod
└── shared/
└── puzzles/ # Puzzle definitions
```
## Notes
- CLIPS validation rules are in `shared/puzzles/`
- LLM solving uses Ollama by default (no API key required)
- Optional: Set ANTHROPIC_API_KEY or OPENAI_API_KEY for cloud providers
## Testing
```bash
# Rust
cd examples/apps/puzzler/rust
cargo test
# Go
cd examples/apps/puzzler/go
go test -v ./...
```
## License
Part of the nxusKit project.
---
# Racer - CLIPS vs LLM Head-to-Head Competition
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/apps/racer
A benchmarking tool for running concurrent races between CLIPS rule-based solving and LLM reasoning on logic problems.
> Race CLIPS rule engines against LLMs on logic puzzles and let the data choose your AI strategy.
**Scenarios**: `race` · `benchmark` · `list` · `describe`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## Real-World Application
Motorsport strategy advisor, real-time decision engine.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
CLIPS
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** CLIPS rule-based racing strategy engine
- **Scenario:** Simulate racing pit-stop strategy using CLIPS rules
- **`tech_tags` in manifest:** `CLIPS` — example id **`racer`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## CLIPS integration path
The Go CLIPS runner uses **provider chat** (`go/clips_wire.go`). For **Session API** usage, use CLIPS session bindings in the SDK. Reference: `conformance/clips-json-contract.json`; nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/racer`:
cd rust && cargo build
cd go && make build
```
## Features
- **Head-to-Head Racing** - Run CLIPS and LLM approaches simultaneously
- **Benchmarking** - Statistical analysis over multiple runs
- **Problem Library** - Built-in collection of logic problems
- **Scoring Modes** - Speed, accuracy, or composite scoring
- **JSON Output** - Machine-readable results for analysis
## Installation
### Rust
```bash
cd examples/apps/racer/rust
cargo build --release
```
### Go
```bash
cd examples/apps/racer/go
make build
```
## Run
### Rust
```bash
cd examples/apps/racer/rust
# Show help
cargo run -- --help
# Run a single race
cargo run -- race einstein-riddle
# Run with accuracy scoring
cargo run -- race -s accuracy family-relations
# Benchmark with 20 runs
cargo run -- benchmark -n 20 einstein-riddle -o results.json
# List available problems
cargo run -- list
# Describe a specific problem
cargo run -- describe einstein-riddle
```
### Go
```bash
cd examples/apps/racer/go
# Show help
./bin/racer --help
# Run a single race
./bin/racer race einstein-riddle
# Benchmark mode
./bin/racer benchmark -n 10 logic-grid
```
## Commands
### race
Run a single head-to-head race between CLIPS and LLM.
```bash
racer race [OPTIONS]
OPTIONS:
-s, --scoring Scoring: speed, accuracy, composite (default: speed)
-t, --timeout Timeout per approach (default: 60)
-m, --model LLM model to use
--clips-only Run only CLIPS approach
--llm-only Run only LLM approach
-j, --json Output in JSON format
-v, --verbose Show detailed progress
```
### benchmark
Run multiple races for statistical analysis.
```bash
racer benchmark [OPTIONS]
OPTIONS:
-n, --runs Number of benchmark runs (default: 10)
-o, --output Write results to file
-j, --json Output in JSON format
```
### list
List available problems with optional filtering.
```bash
racer list [OPTIONS]
OPTIONS:
-t, --type Filter by problem type
-d, --difficulty Filter by difficulty
```
### describe
Show detailed information about a problem.
```bash
racer describe
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/racer --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/racer --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Problem Types
- **einstein-riddle** - The classic Einstein's Riddle (Zebra Puzzle)
- **family-relations** - Family relationship deduction
- **logic-grid** - Logic grid puzzles
- **scheduling** - Resource scheduling problems
- **classification** - Multi-attribute classification
## Scoring Modes
- **speed** - Fastest correct answer wins
- **accuracy** - Most accurate/complete answer wins
- **composite** - Weighted combination of speed and accuracy
## Example Output
### Race Results
```
=== Race: einstein-riddle ===
Contender | Time | Correct | Score
-------------|---------|---------|-------
CLIPS | 45ms | Yes | 100
LLM (Claude) | 3.2s | Yes | 98
Winner: CLIPS (faster with equal accuracy)
```
### Benchmark Results
```
=== Benchmark: einstein-riddle (20 runs) ===
Contender | Avg Time | Win Rate | Avg Score
-------------|----------|----------|----------
CLIPS | 47ms | 85% | 99.5
LLM (Claude) | 3.4s | 15% | 97.2
Statistical Winner: CLIPS (p < 0.001)
```
## Architecture
```
racer/
├── rust/
│ ├── src/main.rs # CLI entry point
│ └── Cargo.toml
├── go/
│ ├── cmd/main.go # CLI entry point
│ ├── runner.go # Race runner logic
│ ├── problems.go # Problem definitions
│ └── go.mod
└── shared/
└── problems/ # Problem definitions
```
## Notes
- CLIPS functionality uses ClipsProvider for rule execution
- LLM approach requires API key (ANTHROPIC_API_KEY or OPENAI_API_KEY)
- Benchmarks may vary based on LLM response times
## Testing
```bash
# Rust
cd examples/apps/racer/rust
cargo test
# Go
cd examples/apps/racer/go
go test -v ./...
```
## License
Part of the nxusKit project.
---
# Riffer - Music Sequence Analysis and Transformation (Rust)
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/apps/riffer
A command-line tool for analyzing and transforming music sequences, implemented in Rust.
> Analyze, score, and transform MIDI and MusicXML sequences using CLIPS rule-based music theory and LLM-powered narrative and transformation.
**Scenarios**: `analyze` · `score` · `transform` · `convert`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** CLIPS rule-based music composition engine
- **Scenario:** Generate musical riffs using CLIPS composition rules
- **`tech_tags` in manifest:** `CLIPS` — example id **`riffer`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## Real-World Application
Algorithmic music generation, creative AI assistant.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
CLIPS
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/riffer`:
cd rust && cargo build
cd go && make build
```
## Features
- **Analyze** - Detect key signature, analyze intervals, contour, rhythm, and dynamics
- **Score** - 6-dimension musicality scoring with improvement suggestions
- **Transform** - Transpose, invert, retrograde, augment, diminish, change key/tempo
- **Convert** - Convert between MIDI and MusicXML formats
## Installation
```bash
cd examples/apps/riffer/rust
cargo build --release
```
Find and set the binary path:
```bash
# Find where cargo built the binary
RIFFER=$(cargo metadata --format-version 1 | sed -n 's/.*"target_directory":"\([^"]*\)".*/\1/p')/release/riffer
# Verify it exists
ls -la "$RIFFER"
```
## Run
From the `examples/apps/riffer/rust` directory:
### Analyze a sequence
```bash
# JSON output (default)
"$RIFFER" analyze -i ../shared/testdata/e_minor_riff.mid
# Markdown output
"$RIFFER" analyze -i ../shared/testdata/e_minor_riff.mid -f markdown
```
### Score musicality
```bash
# Get a 6-dimension score with suggestions
"$RIFFER" score -i ../shared/testdata/e_minor_riff.mid -f markdown
```
Output includes:
- Overall score (0-100)
- Dimension scores: Harmonic Coherence, Melodic Interest, Rhythmic Variety, Resolution Quality, Dynamics Expression, Structural Balance
- Improvement suggestions
### Transform a sequence
```bash
# Transpose up 5 semitones
$RIFFER transform -i input.mid -o output.mid --transpose 5
# Invert around middle C (MIDI note 60)
$RIFFER transform -i input.mid -o output.mid --invert 60
# Reverse notes (retrograde)
$RIFFER transform -i input.mid -o output.mid --retrograde
# Rhythmic augmentation - double note durations (not to be confused with augmented chords)
$RIFFER transform -i input.mid -o output.mid --augment 2.0
# Rhythmic diminution - halve note durations (not to be confused with diminished chords)
$RIFFER transform -i input.mid -o output.mid --diminish 2.0
# Change key to G major
$RIFFER transform -i input.mid -o output.mid --key G
# Change tempo to 140 BPM
$RIFFER transform -i input.mid -o output.mid --tempo 140
# Combine multiple transformations
$RIFFER transform -i input.mid -o output.mid --transpose 5 --tempo 140
```
### Convert between formats
```bash
# MIDI to MusicXML
$RIFFER convert -i input.mid -o output.xml
# MusicXML to MIDI
$RIFFER convert -i input.xml -o output.mid
```
## Supported Formats
- **MIDI** (.mid, .midi) - Standard MIDI File format
- **MusicXML** (.xml, .musicxml) - MusicXML partwise format
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/riffer --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/riffer --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Example Output
### Analysis (Markdown)
```markdown
# Music Analysis: c_major_scale
## Summary
- **Notes**: 8
- **Duration**: 3840 ticks
## Key Detection
- **Detected Key**: C Major
- **Confidence**: 96.7%
## Scale Analysis
- **In Scale**: 8 notes
- **Out of Scale**: 0 notes
- **Harmonic Coherence**: 100.0%
```
### Score (Markdown)
```markdown
# Music Score: c_major_scale
## Overall Score: 59.3/100 (fair)
## Dimension Scores
| Dimension | Score | Rating |
|-----------|-------|--------|
| Harmonic Coherence | 100.0 | excellent |
| Melodic Interest | 39.0 | poor |
| Rhythmic Variety | 20.0 | poor |
## Suggestions for Improvement
- Add more interval variety for melodic interest
- Add rhythmic variety with different note durations
```
## Architecture
```
riffer/
├── main.rs # CLI entry point
├── types.rs # Core data types (Note, Sequence, etc.)
├── errors.rs # Error handling
├── formats/
│ ├── midi.rs # MIDI read/write
│ └── musicxml.rs # MusicXML read/write
├── theory/
│ ├── intervals.rs # Interval classification
│ ├── keys.rs # Key detection (Krumhansl-Schmuckler)
│ └── scales.rs # Scale definitions
└── engine/
├── analyzer.rs # Sequence analysis
├── scorer.rs # 6-dimension scoring
├── transformer.rs # Transformations
└── clips_bridge.rs # CLIPS rule engine (ClipsProvider)
```
## Testing
```bash
cd examples/apps/riffer/rust
cargo test
```
## License
Part of the nxusKit project.
---
# Ruler - Natural Language to CLIPS Rule Generation
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/apps/ruler
A command-line tool for generating CLIPS rules from natural language descriptions using LLM, with validation and automatic retry logic.
> Turn plain English into validated CLIPS rules — describe your business logic, get production-ready expert system code with automatic error correction.
**Scenarios**: `generate` · `validate` · `save` · `load` · `examples`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** CLIPS rule authoring and execution app
- **Scenario:** Author, load, and execute CLIPS rules interactively
- **`tech_tags` in manifest:** `CLIPS` — example id **`ruler`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## Real-World Application
Business rules workbench, rule management console.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
CLIPS
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/ruler`:
cd rust && cargo build
cd go && make build
```
## Features
- **Natural Language Input** - Describe rules in plain English
- **CLIPS Code Generation** - Produces valid CLIPS deftemplates and defrules
- **Automatic Validation** - Validates generated code against CLIPS syntax
- **Retry with Feedback** - Automatically retries with error feedback on failures
- **Progressive Examples** - Built-in examples from basic to advanced complexity
- **Multiple Output Formats** - Save as .clp, .json, or binary
## Installation
### Rust
```bash
cd examples/apps/ruler/rust
cargo build --release
```
### Go
```bash
cd examples/apps/ruler/go
make build
```
## Run
### Rust
```bash
cd examples/apps/ruler/rust
# Show help
cargo run -- --help
# Generate rules from natural language
cargo run -- generate "Create a rule that classifies adults if age >= 18"
# Generate with advanced complexity
cargo run -- generate -c advanced "Medical triage expert system" -o triage.clp
# Run progressive examples
cargo run -- examples -c basic
# Validate existing CLIPS code
cargo run -- validate my-rules.clp
# Load and display rules
cargo run -- load my-rules.clp
```
### Go
```bash
cd examples/apps/ruler/go
# Show help
./bin/ruler --help
# Generate rules
./bin/ruler generate "Classify customers as gold if purchases > 5000"
# Generate with output file
./bin/ruler generate -o customer.clp "Customer loyalty program rules"
```
## Commands
### generate
Generate CLIPS rules from a natural language description.
```bash
ruler generate [OPTIONS]
OPTIONS:
-c, --complexity Target complexity: basic, intermediate, advanced
-m, --model LLM model to use (default: claude-haiku-4-5-20251001)
-r, --retries Max retry attempts (default: 5)
-o, --output Write output to file
-j, --json Output in JSON format
-v, --verbose Show detailed progress
```
### validate
Validate CLIPS code syntax and structure.
```bash
ruler validate [OPTIONS]
OPTIONS:
-v, --verbose Show detailed validation results
```
### examples
Run built-in progressive complexity examples.
```bash
ruler examples [OPTIONS]
OPTIONS:
-c, --complexity Filter by complexity level
-l, --list List examples without running
```
### save / load
Save or load rule sets.
```bash
ruler save # Save current rules
ruler load # Load rules from file
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/ruler --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/ruler --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Complexity Levels
### Basic
- Simple single-rule definitions
- Basic deftemplates with few slots
- Straightforward conditions
Example: "Classify people as adults if age >= 18"
### Intermediate
- Multiple related rules
- Fact chaining and dependencies
- Moderate slot complexity
Example: "Customer loyalty program with bronze, silver, gold tiers"
### Advanced
- Complex multi-rule systems
- Salience and conflict resolution
- Advanced pattern matching
Example: "Medical triage system with symptom analysis"
## Example Output
### Generated CLIPS Code
```clp
; Generated by Ruler from: "Classify adults if age >= 18"
(deftemplate person
(slot name (type STRING))
(slot age (type INTEGER)))
(deftemplate classification
(slot person-name (type STRING))
(slot category (type SYMBOL)))
(defrule classify-adult
"Classify a person as an adult if age >= 18"
(person (name ?name) (age ?age&:(>= ?age 18)))
=>
(assert (classification (person-name ?name) (category adult))))
```
### Validation Result
```
Validation: PASSED
Templates: 2
Rules: 1
Warnings: 0
```
## Architecture
```
ruler/
├── rust/
│ ├── src/main.rs # CLI entry point
│ └── Cargo.toml
├── go/
│ ├── cmd/main.go # CLI entry point
│ ├── generator.go # Rule generation logic
│ ├── validator.go # CLIPS validation
│ └── go.mod
└── shared/
└── examples/ # Built-in examples
```
## Retry Logic
When generated code fails validation:
1. Parse the validation error
2. Include error context in retry prompt
3. Adjust complexity hints if needed
4. Retry up to N times (default: 5)
5. Return best attempt if all retries fail
## Notes
- CLIPS functionality uses ClipsProvider for validation
- LLM approach requires API key (ANTHROPIC_API_KEY or OPENAI_API_KEY)
- Generated code quality depends on description clarity
## Testing
```bash
# Rust
cd examples/apps/ruler/rust
cargo test
# Go
cd examples/apps/ruler/go
go test -v ./...
```
## License
Part of the nxusKit project.
---
# Alert Triage Integration
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/integrations/alert-triage
LLM-powered alert triage for observability systems, with batch processing and structured output.
> Turn alert noise into prioritized action by letting an LLM classify severity, surface root causes, and recommend remediation steps automatically.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## Overview
This example demonstrates using LLMs to triage monitoring alerts, providing priority assessment, likely causes, and suggested remediation actions. It's designed to work with Alertmanager-format alerts.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Alert triage with LLM-powered analysis
- **Scenario:** Classify and prioritize alerts using LLM reasoning
- **`tech_tags` in manifest:** `LLM` — example id **`alert-triage`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
SOC alert triage, IT incident management.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/alert-triage`:
cd rust && cargo build
cd go && make build
```
## Features
- Batch alert processing for efficiency
- Structured JSON output with priority, cause, and actions
- Compatible with Alertmanager webhook format
- Prioritization based on severity and context
## Alert Format
Input alerts follow the Alertmanager format:
```json
{
"alertname": "HighMemoryUsage",
"severity": "warning",
"instance": "web-server-01",
"description": "Memory usage above 85% for 5 minutes"
}
```
## Triage Output
Each alert receives a triage result:
```json
{
"alertname": "HighMemoryUsage",
"priority": 3,
"summary": "Memory pressure on web server",
"likely_cause": "Memory leak or increased traffic",
"suggested_actions": [
"Check for memory leaks in application logs",
"Review recent deployments",
"Consider horizontal scaling"
]
}
```
## Priority Scale
| Priority | Meaning | Response |
|----------|---------|----------|
| 1 | Critical | Immediate action required |
| 2 | High | Respond within 1 hour |
| 3 | Medium | Respond within 4 hours |
| 4 | Low | Respond within 24 hours |
| 5 | Informational | No action required |
## Library usage
### Rust
```rust
use alert_triage::{triage_alerts, Alert};
let alerts = vec![
Alert { alertname: "...", severity: "critical", ... },
];
let results = triage_alerts(&provider, "llama3", &alerts).await?;
for result in results {
println!("{}: Priority {} - {}", result.alertname, result.priority, result.summary);
}
```
### Go
```go
alerts := []Alert{{AlertName: "...", Severity: "critical", ...}}
results, err := TriageAlerts(ctx, provider, "llama3", alerts)
for _, result := range results {
fmt.Printf("%s: Priority %d - %s\n", result.AlertName, result.Priority, result.Summary)
}
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Sample Data
A `sample_alerts.json` file is provided with example alerts for testing.
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Integration Ideas
1. **Alertmanager webhook**: Receive alerts via HTTP webhook
2. **PagerDuty integration**: Update incident priority based on triage
3. **Slack notifications**: Send enriched alerts to Slack channels
4. **Runbook linking**: Match alerts to relevant runbooks
5. **Historical learning**: Improve triage based on past incident resolutions
---
# Multi-Provider Pipeline -- BN -> Solver -> CLIPS
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/integrations/bn-solver-clips-pipeline
Demonstrates the flagship nxusKit integration pattern: chaining Bayesian Network prediction, constraint solver optimization, and CLIPS rule-based safety enforcement in a 3-stage pipeline. Each stage feeds its output into the next, showing how probabilistic, combinatorial, and symbolic reasoning compose through a unified SDK.
> Chain probabilistic prediction, constraint optimization, and rule-based safety enforcement into a single production-ready pipeline using one unified SDK.
**Scenarios**: `festival` · `rescue` · `bakery`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## CLIPS integration path (stage 3)
Stage 3 is **CLIPS**: the **Go** path uses **provider chat** (`go/clips_wire.go`, `ClipsInput` / `ClipsOutput` JSON in the chat API). The **Rust** path uses the **Session API** (`nxuskit::clips::ClipsSession` — load rules, `fact_assert_structured`, `run`). Use the path that matches your integration style; both enforce the same rule files.
Schema: `conformance/clips-json-contract.json`. Docs: nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · CLIPS · Solver · BN
- **Summary:** Three-stage BN prediction → Solver optimization → CLIPS safety pipeline
- **Scenario:** Chain Bayesian Network prediction into Solver optimization with CLIPS safety enforcement
- **`tech_tags` in manifest:** `BN, Solver, CLIPS` — example id **`bn-solver-clips-pipeline`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go |
|---------|-------------|------|-----|
| **BnNetwork** | Load and query Bayesian Network from BIF file | `BnNetwork::from_bif()` | `LoadBnNetwork()` |
| **BnEvidence** | Set observed evidence for inference | `evidence.set_discrete()` | `ev.SetDiscrete()` |
| **Variable Elimination** | Exact posterior inference algorithm | `net.infer(&ev, "ve")` | `net.Infer(ev, "ve")` |
| **SolverSession** | Create and configure Z3 constraint solver | `SolverSession::new()` | `NewSolverSession()` |
| **Constraint Optimization** | Single-objective optimization with constraints | `session.solve()` | `session.Solve()` |
| **CLIPS (stage 3)** | Rule engine for safety | **`ClipsSession`**: `load_file`, `fact_assert_structured`, `run` | **Provider chat**: `NewClipsProvider()`, JSON in `ChatRequest` |
| **Fact assertion** | Solver → CLIPS | Structured slots → `fact_assert_structured` | JSON facts in user message |
| **Alert / conclusion readout** | Derived template facts | `facts_by_template` + `fact_slot_values` | Parse `ClipsOutput.conclusions` |
| **Pipeline Composition** | 3-stage data flow across provider types | Stage 1 -> 2 -> 3 | Stage 1 -> 2 -> 3 |
## Technologies
Solver, BN
## Pipeline Architecture
```
┌─────────────┐ Posteriors ┌──────────────┐ Assignments ┌───────────────┐
│ BN Network │ ──────────────> │ Solver │ ──────────────> │ CLIPS Rules │
│ (Prediction) │ │ (Optimization)│ │ (Safety) │
└─────────────┘ └──────────────┘ └───────────────┘
model.bif problem.json rules.clp
evidence.json
```
**Stage 1 -- BN Prediction**: Loads a Bayesian Network from a BIF file, sets observed evidence, and runs Variable Elimination to compute posterior distributions over a target variable (crowd size, survivor probability, or demand level).
**Stage 2 -- Solver Optimization**: Uses the BN prediction to inform a Z3 constraint optimization problem. Variables, constraints, and objectives are loaded from `problem.json`. The solver finds optimal assignments (band-to-stage, team-to-zone, or item-to-oven mappings).
**Stage 3 -- CLIPS Safety Enforcement**: Converts solver assignments into CLIPS facts and asserts them into a rule engine loaded with domain-specific safety rules. The engine fires rules to detect violations and generates typed alerts (critical, warning, info).
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/bn-solver-clips-pipeline`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario festival
cargo run -- --scenario rescue --verbose
cargo run -- --scenario bakery --step
```
### Go
```bash
cd go
make build
./bin/bn-solver-clips-pipeline --scenario festival
./bin/bn-solver-clips-pipeline --scenario rescue --verbose
./bin/bn-solver-clips-pipeline --scenario bakery --step
```
Or directly:
```bash
cd go
go run . --scenario festival
```
## Scenarios
### Festival (Music Festival Stage Planning)
A music festival needs to assign bands to stages while maximizing audience enjoyment. The BN predicts crowd size from weather, headliner popularity, and time of day. The solver optimizes band-to-stage assignments. CLIPS rules enforce noise limits and pyrotechnic safety regulations.
- **BN predicts**: `crowd_size` given weather, headliner popularity, time of day
- **Solver optimizes**: band-to-stage assignments maximizing `total_enjoyment`
- **CLIPS enforces**: noise proximity limits, pyrotechnic material restrictions
### Rescue (Search and Rescue Operation)
A disaster response team must deploy rescue units across zones. The BN estimates survivor probability from building damage, time since event, and weather conditions. The solver assigns teams to zones to maximize rescues. CLIPS rules enforce operational safety protocols.
- **BN predicts**: `survivor_probability` given building damage, hours since event, weather
- **Solver optimizes**: team-to-zone assignments maximizing `total_survivors_rescued`
- **CLIPS enforces**: helicopter wind limits, team deployment protocols
### Bakery (Production Scheduling)
A bakery plans its daily production across multiple ovens. The BN forecasts demand level from day of week, season, and local events. The solver schedules items across ovens to minimize waste. CLIPS rules enforce allergen isolation and food safety regulations.
- **BN predicts**: `demand_level` given day of week, season, local events
- **Solver optimizes**: item-to-oven assignments minimizing `total_waste`
- **CLIPS enforces**: allergen cross-contamination, gluten-free isolation, scheduling conflicts
## Interactive Modes
All examples support debugging flags for inspecting pipeline internals:
```bash
# Verbose mode - show intermediate data, network variables, fact assertions, rule traces
cargo run -- --scenario festival --verbose # Rust
go run . --scenario festival --verbose # Go
# Step mode - pause at each pipeline stage with explanations
cargo run -- --scenario rescue --step # Rust
go run . --scenario rescue --step # Go
# Combined mode
cargo run -- --scenario bakery --verbose --step
go run . --scenario bakery --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Scenario Data Format
Each scenario directory contains four files:
| File | Purpose | Consumed By |
|------|---------|-------------|
| `model.bif` | Bayesian Network definition in BIF format (variables, parents, CPTs) | Stage 1: BnNetwork |
| `evidence.json` | Observed variable values as `{"variable": "state"}` pairs | Stage 1: BnEvidence |
| `problem.json` | Solver problem with variables, constraints, and objectives | Stage 2: SolverSession |
| `rules.clp` | CLIPS rule definitions for domain-specific safety checks | Stage 3: ClipsProvider |
| `expected-output.json` | Golden output describing expected pipeline results | Testing/validation |
### Adding a New Scenario
1. Create a new directory under `scenarios/`
2. Define the BN model in `model.bif` with evidence and prediction variables
3. Create `evidence.json` with the observed evidence
4. Define the optimization problem in `problem.json`
5. Write CLIPS safety rules in `rules.clp` with appropriate templates
6. Add the scenario's CLIPS template mapping to `knownScenarios` in the source code
7. Create `expected-output.json` with the expected pipeline results
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Event planning | Predict attendance, optimize resource allocation, enforce safety codes |
| Emergency response | Estimate survival windows, deploy rescue assets, enforce operational protocols |
| Manufacturing | Forecast demand, schedule production, enforce quality and safety standards |
| Logistics | Predict delivery volumes, optimize fleet routing, enforce regulatory compliance |
| Healthcare | Predict patient load, optimize staff scheduling, enforce clinical safety protocols |
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
Each scenario includes an `expected-output.json` that describes the expected structure of the pipeline results, useful for regression testing and validation.
---
# BN Structure Learning -- Causal Discovery from Data
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/integrations/bn-structure-learning
Demonstrates Bayesian Network structure learning: discovering causal relationships directly from observational CSV data, learning parameters, evaluating model fit, and running inference on the learned model. Two structure learning algorithms (Hill-Climb and K2) are compared to identify high-confidence causal links.
> Discover causal structure hidden in your data — learn Bayesian network topology and parameters directly from CSV observations using Hill-Climb and K2 search algorithms.
**Scenarios**: `golf` · `bmx` · `sourdough`
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · BN
- **Summary:** Bayesian network structure learning from data
- **Scenario:** Learn Bayesian network structure from observational data
- **`tech_tags` in manifest:** `BN` — example id **`bn-structure-learning`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go |
|---------|-------------|------|-----|
| **BnNetwork (empty)** | Create an empty network for structure learning | `nxuskit_bn_net_create()` | `NewBnNetwork()` |
| **Hill-Climb Search** | Greedy structure search with edge add/remove/reverse | `nxuskit_bn_search_structure(..., "hill_climb", ...)` | `net.SearchStructure(..., "hill_climb")` |
| **K2 Search** | Order-based structure search with variable ordering | `nxuskit_bn_search_structure(..., "k2", ...)` | `net.SearchStructure(..., "k2")` |
| **BIC Scoring** | Bayesian Information Criterion (penalizes complexity) | `scoring = "bic"` | `Scoring: "bic"` |
| **BDeu Scoring** | Bayesian Dirichlet equivalent uniform scoring | `scoring = "bdeu"` | `Scoring: "bdeu"` |
| **MLE Learning** | Maximum Likelihood Estimation for CPT parameters | `nxuskit_bn_learn_mle()` | `net.LearnMLE()` |
| **Log-Likelihood** | Evaluate model fit against training data | `nxuskit_bn_log_likelihood()` | `net.LogLikelihood()` |
| **VE Inference** | Variable Elimination on the learned model | `nxuskit_bn_infer(..., "ve", ...)` | `net.Infer(ev, "ve")` |
## Technologies
BN
## Pipeline Architecture
```
┌───────────┐ Column names ┌──────────────┐ Learned edges ┌───────────────┐
│ CSV Data │ ───────────────> │ Structure │ ─────────────────> │ Parameter │
│ (200 rows) │ │ Learning │ │ Learning │
└───────────┘ │ (HC / K2) │ │ (MLE) │
└──────────────┘ └───────┬───────┘
│
┌──────────────┐ Fit score ┌──────┴───────┐
│ Algorithm │ <───────────── │ Log- │
│ Comparison │ │ Likelihood │
└──────────────┘ └──────┬───────┘
│
┌──────┴───────┐
│ Inference │
│ (VE) │
└──────────────┘
```
**Step 1 -- Load CSV Data**: Reads the scenario CSV file, discovers column names (which become BN variables) and row count.
**Step 2 -- Hill-Climb + BIC**: Runs greedy structure search starting from an empty graph. At each step, the algorithm tries adding, removing, or reversing an edge, accepting the change that most improves the BIC score. BIC balances fit against model complexity via a log(N) penalty term.
**Step 3 -- K2 + BDeu**: Runs order-based structure search using the CSV column ordering. K2 processes variables in order, greedily adding parent edges that improve the BDeu score. BDeu uses an equivalent sample size (ESS) hyperparameter that controls the strength of the prior.
**Step 4 -- MLE Parameter Learning**: Fits conditional probability tables (CPTs) to the Hill-Climb structure using Maximum Likelihood Estimation with Laplace smoothing (pseudocount=1.0) to avoid zero probabilities.
**Step 5 -- Log-Likelihood Evaluation**: Computes how well the learned model explains the training data. Per-sample log-likelihood allows comparison across different dataset sizes.
**Step 6 -- Inference**: Runs Variable Elimination on the learned model with sample evidence to demonstrate that the learned network supports standard BN queries.
**Step 7 -- Algorithm Comparison**: Compares edges discovered by both algorithms. Shared edges represent high-confidence causal relationships found independently by two different search strategies.
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/bn-structure-learning`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario golf
cargo run -- --scenario bmx --verbose
cargo run -- --scenario sourdough --step
```
### Go
```bash
cd go
make build
./bin/bn-structure-learning --scenario golf
./bin/bn-structure-learning --scenario bmx --verbose
./bin/bn-structure-learning --scenario sourdough --step
```
Or directly:
```bash
cd go
go run . --scenario golf
```
## Scenarios
### Golf (Course Conditions)
Models how weather, soil conditions, maintenance practices, and fertilizer affect golf course playing conditions. The data encodes realistic correlations: rainy weather increases soil moisture, which softens fairways; heavy fertilizer increases green speed; longer mowing increases rough thickness.
- **Variables**: weather, soil_moisture, mowing, foot_traffic, fertilizer, green_speed, fairway_firmness, rough_thickness
- **Expected causal links**: weather -> soil_moisture -> fairway_firmness, fertilizer -> green_speed, mowing -> rough_thickness
- **Inference demo**: P(green_speed | weather=rainy, fertilizer=heavy)
### BMX (Rider Performance)
Models how rider skill, technique, and jump characteristics affect BMX race outcomes. High skill correlates with perfect pump timing and fast speed; extreme jumps with low skill dramatically increase crash risk.
- **Variables**: jump_height, berm_angle, pump_timing, speed, skill, lap_time, crash_risk, style_score
- **Expected causal links**: skill -> pump_timing, skill -> jump_height, speed -> lap_time, jump_height + skill -> crash_risk
- **Inference demo**: P(lap_time | skill=pro, pump_timing=perfect)
### Sourdough (Baking)
Models how feeding schedule, flour choice, temperature, and starter maturity affect sourdough bread characteristics. Warm temperatures with mature starters produce fast rises and dense bubbles; rye flour and infrequent feeding lead to sour flavors.
- **Variables**: feeding_schedule, flour_type, ambient_temp, hydration, starter_age, rise_time, bubble_density, flavor_profile
- **Expected causal links**: ambient_temp + starter_age -> rise_time -> bubble_density, flour_type -> flavor_profile, feeding_schedule -> starter_age
- **Inference demo**: P(flavor_profile | flour_type=rye, ambient_temp=warm)
## Interactive Modes
```bash
# Verbose mode -- show raw JSON results and intermediate data
cargo run -- --scenario golf --verbose # Rust
go run . --scenario golf --verbose # Go
# Step mode -- pause at each step with explanations
cargo run -- --scenario bmx --step # Rust
go run . --scenario bmx --step # Go
# Combined mode
cargo run -- --scenario sourdough --verbose --step
go run . --scenario sourdough --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Structure Learning Concepts
### Hill-Climb vs K2
| Property | Hill-Climb | K2 |
|----------|-----------|-----|
| Search strategy | Greedy local search | Order-based forward search |
| Starting point | Empty graph | Empty graph + variable ordering |
| Operations | Add, remove, reverse edges | Add parent edges only |
| Ordering required | No | Yes (results depend on ordering) |
| Score function | BIC (default) | BDeu (default) |
| Complexity | O(n^2 * max_steps) | O(n^2 * max_parents) |
| Strengths | Flexible, no ordering needed | Fast, principled Bayesian scoring |
| Weaknesses | Can get stuck in local optima | Sensitive to variable ordering |
### Scoring Functions
**BIC (Bayesian Information Criterion)**: `BIC = LL - (k/2) * ln(N)` where LL is log-likelihood, k is the number of free parameters, and N is the sample size. Penalizes complexity more strongly with larger datasets.
**BDeu (Bayesian Dirichlet equivalent uniform)**: A Bayesian score that uses a Dirichlet prior. The equivalent sample size (ESS) parameter controls prior strength: small ESS values prefer simpler structures, large ESS values are more permissive.
### Parameter Learning (MLE)
Maximum Likelihood Estimation counts co-occurrences in the data to estimate conditional probability tables. Laplace smoothing (pseudocount > 0) adds a small count to every cell, preventing zero probabilities that would make log-likelihood undefined.
### Fit Evaluation (Log-Likelihood)
Log-likelihood measures how well the model's CPTs explain the observed data: `LL = sum_i sum_j log P(x_ij | parents(x_j))`. Higher (less negative) values indicate better fit. Per-sample log-likelihood (LL / N) normalizes for dataset size.
## CSV Format Requirements
- **Header row**: First row contains column names (become BN variable names)
- **Encoding**: UTF-8 with LF line endings
- **Delimiter**: Comma-separated values
- **Values**: Categorical (discrete) values only for structure learning
- **Missing values**: Rows with empty cells are skipped with a warning
- **Sorting**: Primary sort by first column, secondary by second column
### Adding a New Scenario
1. Create a new directory under `scenarios/`
2. Add a `data.csv` file with header row and at least 50 data rows
3. Ensure correlations in the data reflect the causal structure you expect to discover
4. Add the scenario configuration to `scenario_config()` (Rust) or `knownScenarios` (Go)
5. Create `expected-output.json` with expected edge ranges and inference results
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Epidemiology | Discover disease risk factor relationships from patient records |
| Manufacturing | Identify root causes of defects from production data |
| Finance | Map causal relationships between economic indicators |
| Genomics | Learn gene regulatory networks from expression data |
| Quality control | Find which process parameters affect product quality |
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
Each scenario includes an `expected-output.json` that describes expected edge count ranges, inference results, and fit evaluation bounds for regression testing.
---
# CLI Assistant Integration
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/integrations/cli-assistant
Converts natural language queries into shell commands using LLM with streaming output.
> Turn plain English into shell commands instantly — build a streaming CLI assistant that speaks your language and runs in your terminal.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## Overview
This example demonstrates a practical CLI tool that translates human-readable requests into executable shell commands. It showcases streaming for real-time output as the command is generated.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Interactive CLI assistant with LLM backend
- **Scenario:** Build an interactive terminal assistant powered by an LLM
- **`tech_tags` in manifest:** `LLM` — example id **`cli-assistant`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Developer productivity tool, command-line copilot.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Features
- Natural language to shell command translation
- Streaming output shows command as it's generated
- Safety comments for dangerous operations
- Works with common Unix commands
## Example Queries
| Query | Generated Command |
|-------|------------------|
| "find all rust files modified in the last week" | `find . -name "*.rs" -mtime -7` |
| "show disk usage sorted by size" | `du -sh * \| sort -h` |
| "list all running docker containers" | `docker ps` |
## Build
```bash
cd rust && cargo build
cd ../go && make build
```
## Library usage
### Rust
```rust
use nxuskit::prelude::*;
let provider = OllamaProvider::builder().model("llama3").build()?;
let command = generate_command(&provider, query).await?;
println!("Generated: {}", command);
```
### Go
```go
command, err := GenerateCommand(ctx, provider, query)
fmt.Println("Generated:", command)
```
## Run
### Rust
```bash
cd rust
cargo run
# Interactive mode
cargo run -- "your query here"
```
### Go
```bash
cd go
go run .
# Interactive mode
go run . "your query here"
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Safety Considerations
The LLM is instructed to:
- Add warning comments for dangerous operations (rm -rf, etc.)
- Use common, well-known Unix commands
- Provide clarifying comments for ambiguous requests
**Important**: Always review generated commands before executing them.
## Extending the Example
Ideas for enhancement:
1. Add command execution with confirmation prompt
2. Implement command history
3. Add support for platform-specific commands (Windows, macOS, Linux)
4. Include command explanation mode
5. Add syntax highlighting for output
---
# CLIPS Basics
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/integrations/clips-basics
Load rules, assert facts, and run the CLIPS inference engine
> Bring deterministic rule-based logic to your applications by driving the CLIPS inference engine directly through the nxusKit SDK.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · CLIPS
- **Summary:** CLIPS rule engine basics via nxusKit SDK
- **Scenario:** Load rules, assert facts, and run the CLIPS inference engine
- **`tech_tags` in manifest:** `CLIPS` — example id **`clips-basics`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## CLIPS integration path
This example uses **provider chat**: JSON shaped like `ClipsInput` is sent as the user message body to the CLIPS `LLMProvider`, and the engine returns `ClipsOutput` JSON in `response.content`. Local wire types mirror that contract and are **not** SDK exports: Go `go/clips_wire.go`, Rust via shared crate `examples/shared/clips-wire-rust` (`nxuskit-examples-clips-wire`), Python reference `examples/shared/python/clips_wire.py`.
For **Session API** access (load rules, assert facts, run, inspect via handles), use `nxuskit::ClipsSession`, `nxuskit.ClipsSession`, or the C ABI in the SDK bundle.
Schema reference: `conformance/clips-json-contract.json` in this repository. Full field documentation: nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (heading anchor `#clipsinput-json-reference`; in the extracted bundle, see `docs/rule-authoring.md`).
## Real-World Application
Business rules engine, compliance checking
## Technologies
CLIPS
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `examples/shared/python/clips_wire.py` | Wire types only (use with nxuskit-py provider chat) |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/clips-basics`:
cd rust && cargo build
cd go && make build
```
Cross-language parity: the **animal classification** demos use the same `ClipsInput`-shaped JSON (`facts` → `template` / `values`) in Go (`main.go` example 1 dog; example 2 Frog/Penguin/Spider batch) and Rust (`animal_classification.rs` via `ClipsInputWire`).
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/clips-basics
```
---
# CLIPS+LLM Hybrid Integration
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/integrations/clips-llm-hybrid
Demonstrates combining CLIPS expert system with LLM for deterministic business rules plus natural language understanding.
> Combine deterministic CLIPS rules with LLM reasoning to build AI pipelines that are both fluent and auditable.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## CLIPS integration path
The CLIPS stage uses **provider chat** (JSON `ClipsInput` in the user message, `ClipsOutput` in `content`). See `go/clips_wire.go` and Rust crate `examples/shared/clips-wire-rust`. For **Session API** usage, use the CLIPS session bindings in your language SDK instead.
Schema: `conformance/clips-json-contract.json`. Documentation: nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## What this demonstrates
**Difficulty: Intermediate** 🟦 · LLM · CLIPS
- **Summary:** Hybrid CLIPS rules + LLM reasoning
- **Scenario:** Combine deterministic CLIPS rules with LLM-based reasoning
- **`tech_tags` in manifest:** `CLIPS, LLM` — example id **`clips-llm-hybrid`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go |
|---------|-------------|------|-----|
| **ClipsProvider** | Rule-based expert system as LLMProvider | ✅ `ClipsProvider::builder()` | ✅ `NewClipsProvider()` |
| **JSON Fact Assertion** | Convert structured data to CLIPS facts | ✅ `ChatRequest` with JSON | ✅ `ChatRequest` with JSON |
| **Conclusion Extraction** | Parse CLIPS output for derived facts | ✅ `ClipsOutput::conclusions` | ✅ `ClipsOutput.Conclusions` |
| **Provider Abstraction** | Same interface for LLM and CLIPS | ✅ `LLMProvider` trait | ✅ `LLMProvider` interface |
| **ResponseFormat** | Structured JSON output from LLM | ✅ `ResponseFormat::Json` | ✅ `JSONMode: true` |
| **Hybrid Pipeline** | LLM → CLIPS → LLM workflow | ✅ `analyze_ticket()` | ✅ `AnalyzeTicket()` |
## Real-World Application
Explainable AI decisions, regulated industry automation.
## Technologies
CLIPS, LLM
## Overview
This example shows the "hybrid AI" pattern: using LLM for natural language understanding and CLIPS for deterministic business decisions. Both Rust and Go implementations use the **real ClipsProvider** to execute CLIPS rules.
## Why Hybrid?
| Approach | Strengths | Weaknesses |
|----------|-----------|------------|
| **LLM only** | Natural language understanding, flexibility | Inconsistent policy application, no audit trail |
| **CLIPS only** | Deterministic, auditable, policy-compliant | Can't understand unstructured text |
| **Hybrid** | Both! Understanding AND compliance | More complex architecture |
## Three-Step Flow
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Step 1 │ │ Step 2 │ │ Step 3 │
│ LLM │ ──► │ CLIPS │ ──► │ LLM │
│ (classify) │ │ (routing) │ │ (response) │
└─────────────┘ └─────────────┘ └─────────────┘
Extract Apply rules Generate
category, deterministic empathetic
priority, team routing, customer
sentiment SLA, escalation response
```
1. **LLM Classification**: Extract category, priority, sentiment, entities from ticket text
2. **CLIPS Routing**: Apply deterministic rules for team assignment, SLA, escalation
3. **LLM Response**: Generate appropriate customer response
## Routing Rules
The CLIPS rules in `ticket-routing.clp` apply:
| Category | Priority | Team | SLA | Escalation |
|----------|----------|------|-----|------------|
| Security | Any | Security | 4h | Level 2 |
| Infrastructure | Critical | SRE | 2h | Level 1 |
| Infrastructure | High | SRE | 4h | Level 1 |
| Application | Critical | Development | 4h | Level 1 |
| Application | High | Development | 8h | None |
| General | Any | General Support | 24h | None |
## Library usage
### Rust (with ClipsProvider)
```rust
use clips_llm_hybrid::analyze_ticket;
use std::path::Path;
// nxusKit: Hybrid analysis using LLM + ClipsProvider
let rules_path = Path::new("ticket-routing.clp");
let result = analyze_ticket(&provider, "llama3", ticket_text, rules_path).await?;
// Deterministic routing from CLIPS (auditable, explainable)
println!("Team: {}", result.team);
println!("SLA: {} hours", result.sla_hours);
// LLM-derived insights (natural language understanding)
println!("Sentiment: {}", result.sentiment);
println!("Response: {}", result.suggested_response);
```
### Go (with ClipsProvider)
```go
// nxusKit: Hybrid analysis using LLM + ClipsProvider
rulesPath := "ticket-routing.clp"
result, err := AnalyzeTicket(ctx, provider, "llama3", ticketText, rulesPath)
// Deterministic routing from CLIPS (auditable, explainable)
fmt.Println("Team:", result.Team)
fmt.Println("SLA:", result.SLAHours, "hours")
// LLM-derived insights (natural language understanding)
fmt.Println("Sentiment:", result.Sentiment)
```
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/clips-llm-hybrid`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## CLIPS Rules File
See `ticket-routing.clp` for the actual CLIPS rules used in the Rust implementation.
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Production Considerations
1. **Rule versioning**: Track changes to CLIPS rules with version control
2. **Audit logging**: Log all routing decisions with rule traces
3. **Fallback handling**: Define default routing for edge cases
4. **Rule testing**: Unit test CLIPS rules independently of LLM
5. **Performance**: Cache common routing patterns
---
# Common-Sense Guardrails
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/integrations/common-sense-guardrails
> Catch plausible but impossible LLM recommendations by turning answers into facts, firing rules, and repairing failures with auditable prompts.
**Scenarios**: `car-wash` · `coupon-stack` · `pallet-door` · `cold-chain`
## Edition
**Community** - runs the full guardrail workflow: raw answer, structured facts, CLIPS validation, deterministic repair packet, and corrected answer.
**Edition note:** Runs in Community Edition. Pro adds optional Solver and ZEN proof stages.
## Pro Enhancement Path
Pro adds optional proof stages only when requested with `--stage pro` or `--stage all`.
- `solver-proof`: uses Solver artifacts for object-presence and dimensional feasibility scenarios.
- `zen-policy`: uses ZEN decision artifacts for promotion policy and cold-chain handling scenarios.
Mock Pro evidence is fixture-backed and does not require entitlement. In live mode this example checks for the normal nxusKit Pro entitlement signal before labeling a Pro proof stage as live-entitled; without entitlement it skips the Pro stage with a clear message and leaves Community stages runnable. The first-release Python and Bash implementations do not execute Solver or ZEN engines directly; they show the handoff shape through checked-in proof artifacts.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** Progressive LLM guardrails with Community CLIPS validation and optional Pro proof stages.
- **Scenario:** Refine LLM recommendations with structured extraction, rules, retry repair, and optional Pro proof.
- **`tech_tags` in manifest:** `LLM`, `CLIPS` - example id **`common-sense-guardrails`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Mock mode uses only Python 3, Bash, and `jq`. Live mode uses an installed nxusKit SDK or `nxuskit-cli`.
- **Languages in this example:** python, bash.
- **Models:** Live and auto mode can use `NXUSKIT_PROVIDER` with `NXUSKIT_MODEL`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, reachable `OLLAMA_HOST`, or reachable `LMSTUDIO_BASE_URL`.
- **CLIPS:** Community validation is represented by scenario-local CLIPS rule files and normalized findings.
## Scenario Purposes
| Scenario | Failure class | Guardrail |
|----------|---------------|-----------|
| `car-wash` | Implicit object-presence precondition | Washing the car requires the car to be at the wash location, not just the person. |
| `coupon-stack` | Promotion policy and margin violation | Discounts, free shipping, and loyalty credits must satisfy stacking and margin rules. |
| `pallet-door` | Dimensional feasibility and unsafe geometry | A pallet cannot be pushed through a door that is narrower than the loaded pallet. |
| `cold-chain` | Handling and auditability violation | Frozen medical material must use certified refrigerated service with temperature traceability. |
## Run
Canonical Community smoke commands:
```bash
cd examples/integrations/common-sense-guardrails/python
python3 main.py --scenario car-wash --mode mock --stage ce
cd ../bash
bash main.sh --scenario car-wash --mode mock --stage ce
```
Machine-readable parity checks:
```bash
cd examples/integrations/common-sense-guardrails/python
python3 main.py --scenario car-wash --mode mock --stage all --json
cd ../bash
bash main.sh --scenario car-wash --mode mock --stage all --json
```
All launch scenarios:
```bash
for scenario in car-wash coupon-stack pallet-door cold-chain; do
python3 main.py --scenario "$scenario" --mode mock --stage ce --json
done
```
## Mode Behavior
- `--mode mock`: uses checked-in fixtures for every Community stage and optional Pro evidence. It performs no provider, network, or entitlement preflight.
- `--mode live`: requires a configured live provider and fails before scenario content is sent if preflight is unavailable.
- `--mode auto`: uses live execution when provider preflight succeeds; otherwise it labels the run as fixture-backed mock mode.
Live structured fact extraction prefers pure JSON. If the model wraps a valid JSON object in prose, the runners extract it and mark the structured-facts stage as `warn`; if no valid JSON object is recoverable after retry, the structured-facts stage is marked `fail` and the run falls back to checked-in fact fixtures so later guardrail stages can still show their behavior.
Provider preflight order is explicit nxusKit provider/model environment, phase-specific model environment, nxusKit-recognized cloud credentials, reachable Ollama, then reachable LM Studio. Do not commit provider credentials or license tokens.
For local Ollama live runs, the Python runner honors `OLLAMA_HOST` and uses a short 5 second connect timeout with a 120 second read timeout because local model responses can be slower than cloud providers. The Bash runner forwards model settings to `nxuskit-cli call`; CLI timeout behavior comes from the installed SDK.
Live runs can use one provider/model for every phase or override phases independently:
```bash
export NXUSKIT_PROVIDER=ollama
export NXUSKIT_MODEL=qwen3.5:4b
export OLLAMA_HOST=http://127.0.0.1:11434
```
Phase-specific provider overrides are also supported with `NXUSKIT_COMMON_SENSE_BASELINE_PROVIDER`, `NXUSKIT_COMMON_SENSE_FACTS_PROVIDER`, and `NXUSKIT_COMMON_SENSE_REPAIR_PROVIDER`. See [OLLAMA_MODELS.md](/v0.9.4/nxuskit/examples/integrations/common-sense-guardrails/ollama-models/) for local Ollama model notes from the repository walkthrough.
## Local Model Starting Points
These are dated smoke-test starting points from the DevOps Ollama model-testing notes, not model rankings or product guarantees.
| Model | Why try it |
|-------|------------|
| `qwen3.5:4b` | 2026-05-11/12 local smokes show the desired guardrail-demo shape: naive car-wash answer fails as `walk`, constrained output is parseable, and enhanced object-presence prompting recovers to `drive`; it also has local structured/document evidence. |
| `qwen3.5:2b` | 2026-05-12 local smoke shows the same fail/recover car-wash shape at a smaller 2.7 GB footprint; use it when low-resource local testing matters more than tool-intent strength. |
| `gemma3:1b` or `erukude/omni-json:1b` | 2026-05-09/12 small-model smokes found both useful for very small guardrail demos because they reproduce the naive failure and recover under the enhanced prompt. |
| `nemotron-3-nano:4b` | 2026-05-12 smokes show the car-wash fail/recover target plus a native strict tool-call pass, making it a useful local comparison point. |
Avoid using passing or unparsed baseline behavior as a demo failure source. For example, the same DevOps notes show `phi4-mini-reasoning:3.8b` answering `drive` on the naive prompt and `granite4:350m-h` failing to recover under the enhanced prompt, so neither is a good default for this specific guardrail walkthrough.
## Scenario Data Contract
Each scenario directory contains these required Community files:
```text
problem.json
expected-output.json
rules.clp
mock-baseline.json
mock-facts.json
mock-repair.json
mock-corrected.json
```
Pro-enabled scenarios add one of:
```text
solver-problem.json
decision-model.json
```
Structured fact fixtures must include:
- `goal`
- `candidate_actions`
- `objects_required`
- `objects_moved`
- `resources`
- `constraints`
- `policy_context`
- `confidence`
CLIPS findings normalize to `status`, `rule_id`, `severity`, `message`, and `evidence`. Expected-output fixtures list required stage ids, expected finding rule ids, correction text fragments, and optional Pro stage metadata.
## Adding a Scenario
1. Create `scenarios//`.
2. Add every required Community file listed above.
3. Include a stable `id`, non-empty prompts, and a `repair_template` containing `{findings}` in `problem.json`.
4. Add scenario-local `rules.clp` findings with stable kebab-case rule ids.
5. Add `solver-problem.json` or `decision-model.json` only when the optional Pro stage is meaningful.
6. Run validation and both contract test suites before updating manifest scenarios.
Authoring validation:
```bash
cd examples/integrations/common-sense-guardrails/python
python3 main.py --validate-scenarios
python3 test_contract.py
cd ../bash
bash main.sh --validate-scenarios
bash test.sh
```
## Public Inspiration
Shout-out to [Haris Rahi](https://harisrahi.ai) and [Tamara Storm](https://www.linkedin.com/in/tamarastorm) for their LinkedIn discussions on the car-wash scenario from Opper.ai, Focus AI, and the HOB benchmark line.
## Scope Exclusions
This is not a medical, legal, financial, or safety certification system. Do not add PHI, regulated personal data, certification claims, or model-ranking claims to scenarios. The examples demonstrate an engineering pattern for auditable guardrails, not a complete common-sense benchmark.
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| LLM answer validation | Catch plausible recommendations that fail physical, operational, or policy preconditions before they reach users |
| Policy enforcement | Turn free-form answers into facts, apply deterministic rules, and produce auditable repair context |
| Operational decision support | Preserve fast LLM drafting while requiring concrete feasibility evidence for workflow-critical recommendations |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`: extracted bundle or installer layout) for live SDK checks. Mock acceptance commands do not need the SDK.
```bash
# From `/examples/integrations/common-sense-guardrails`:
cd python && python3 main.py --help
cd ../bash && make test
```
---
# Curated Ollama Models
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/integrations/common-sense-guardrails/ollama-models
This note records local model passes used for the common-sense guardrails walkthrough. The first pass on 2026-05-07 combined `ollama-cache list` SSD residency with `ollama list` installed sizes and filtered to models under 8 GB. Follow-up passes on 2026-05-11 and 2026-05-12 added the car-wash fail/recover smoke shape and structured-output checks.
These are dated smoke-test starting points, not model rankings or product guarantees.
## Source Notes
- Live structured fact extraction prefers pure JSON. If the model wraps a valid JSON object in prose, the Python and Bash runners extract it and mark the structured-facts stage as `warn`. If no valid JSON object is recoverable after retry, the stage is marked `fail` and the run falls back to checked-in fact fixtures so later guardrail stages can still demonstrate their behavior.
- Ollama structured outputs are most reliable when the API `format` field carries JSON or a JSON schema, and Ollama recommends grounding the prompt with the schema and using low temperature. Provider-native structured-output controls are still the robust path for future hardening, but this walkthrough no longer treats structured-facts failure as the expected result.
- Local car-wash smokes found `qwen3.5:4b` to be the best primary walkthrough candidate: small enough for local proof, stronger than the 2B option, and tested against the desired naive `walk` failure plus enhanced `drive` recovery.
- Local car-wash smokes found `qwen3.5:2b` useful as the low-resource option with the same fail/recover shape.
- Small-model smokes also found `gemma3:1b` and `erukude/omni-json:1b` useful for very small demos. `nemotron-3-nano:4b` is useful as a comparison point because separate tool-intent smokes showed native strict behavior.
- `llama3.2` remains a historical target candidate from earlier sweeps, but it is no longer the default recommendation for this walkthrough.
References:
-
-
-
- DevOps Ollama model-testing notes from 2026-05-09 through 2026-05-12
## Recommended Walkthrough Models
Use these first because they are small local smoke-test candidates that match the guardrail demo shape:
| Role | Model | Installed size | Why it is on the list | Walkthrough note |
|------|-------|----------------|------------------------|------------------|
| Primary live walkthrough | `qwen3.5:4b` | 3.4 GB | Stronger small Qwen 3.5 option from the 2026-05-11/12 local smokes. | Desired car-wash shape: naive answer fails as `walk`, constrained output is parseable, and enhanced object-presence prompting recovers to `drive`. Use this first when available. |
| Low-resource walkthrough | `qwen3.5:2b` | 2.7 GB | Smaller Qwen 3.5 option from the 2026-05-12 local smoke. | Same fail/recover car-wash shape at a smaller footprint. Use when local resource constraints matter more than maximum tool-intent strength. |
| Very small demo candidates | `gemma3:1b` or `erukude/omni-json:1b` | 815 MB / 1.4 GB | Very small models that reproduced the demo failure and recovery shape in local smokes. | Useful for constrained machines, but keep the primary docs and article proof centered on `qwen3.5:4b`. |
| Comparison candidate | `nemotron-3-nano:4b` | 2.8 GB | Car-wash fail/recover target plus separate native strict tool-call smoke evidence. | Interesting for comparison, but adding it to the main walkthrough can dilute the guardrails story. |
Other observed models:
| Model | Installed size | Use | Walkthrough note |
|-------|----------------|-----|------------------|
| `llama3.2` | 2.0 GB | Historical target candidate. | Earlier local sweeps showed a valid fail/recover shape, but newer release-surface guidance prefers `qwen3.5:4b` primary and `qwen3.5:2b` low-resource. |
| `phi4-mini-reasoning:3.8b` | 3.2 GB | Avoid as default for this scenario. | Answered `drive` on the naive prompt, which removes the intended baseline failure. |
| `granite4:350m-h` | 366 MB | Avoid as default for this scenario. | Failed to recover under the enhanced prompt in local smokes. |
| `qwen3:4b` | 2.5 GB | Historical extraction experiment. | Direct JSON probes were useful, but newer Qwen 3.5 smokes are the better starting point for the full walkthrough. |
## Current Walkthrough Default
Prefer `qwen3.5:4b` for the interactive walkthrough when it is available. It is the primary v0.9.4 local proof candidate, remains small enough for a developer laptop, and has current local smoke evidence for the car-wash fail/recover shape.
```bash
export NXUSKIT_PROVIDER=ollama
export NXUSKIT_MODEL=qwen3.5:4b
export OLLAMA_HOST=http://127.0.0.1:11434
```
For a lower-resource run, use the 2B Qwen 3.5 variant:
```bash
export NXUSKIT_PROVIDER=ollama
export NXUSKIT_MODEL=qwen3.5:2b
export OLLAMA_HOST=http://127.0.0.1:11434
```
For phase-specific experiments, keep the stronger model on extraction and repair while trying a smaller baseline:
```bash
export NXUSKIT_PROVIDER=ollama
export NXUSKIT_MODEL=qwen3.5:2b
export NXUSKIT_COMMON_SENSE_FACTS_MODEL=qwen3.5:4b
export NXUSKIT_COMMON_SENSE_REPAIR_MODEL=qwen3.5:4b
export OLLAMA_HOST=http://127.0.0.1:11434
```
## Structured Facts Posture
Provider-native structured-output controls remain the preferred hardening path, especially Ollama JSON/schema formatting and thinking-mode controls when exposed through the installed SDK/CLI surface. The example itself should be described more narrowly: live structured facts can pass with pure JSON, warn when valid JSON is recovered from prose, or fail after retry and fall back to fixtures. Failure is a fallback state, not the expected walkthrough result.
---
# LLM-Solver Hybrid -- Natural Language to Optimized Solutions
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/integrations/llm-solver-hybrid
Demonstrates using an LLM to translate natural language constraints into structured solver variables and constraints, then feeding them to the Z3-based constraint solver for optimization. Supports mock mode (no API key needed) and live mode with configurable LLM providers.
> Bridge natural language and constraint solvers — let an LLM parse human intent, let Z3 find the optimal answer.
**Scenarios**: `seating` · `dungeon` · `road-trip`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · LLM · Solver
- **Summary:** Hybrid LLM + Z3 solver problem solving
- **Scenario:** Use an LLM to formulate constraints and Z3 to solve them
- **`tech_tags` in manifest:** `LLM, Solver` — example id **`llm-solver-hybrid`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust, python (paths under this directory).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go | Python |
|---------|-------------|------|-----|--------|
| **LLM Chat API** | Send structured prompts to LLM providers | `nxuskit::chat()` | `provider.Chat()` | `provider.chat(..., response_format=ResponseFormat.JSON)` |
| **Constraint Solver** | Z3-based solver session with variables, constraints, objectives | `nxuskit::solver::SolverSession` | `NewSolverSession()` | `nxuskit.solver.SolverSession` |
| **JSON Parsing/Validation** | Parse LLM output into typed variable and constraint definitions | `serde_json` | `encoding/json` | `json` + validation stage |
| **Retry Logic** | Re-prompt LLM on parse failure with error feedback (max 3 attempts) | `call_llm_with_retry()` | Retry loop in Stage 2 | Retry loop in `extract_variables_live()` |
| **Mock Mode** | Deterministic offline testing with pre-computed LLM responses | `--mock` flag | `--mock` (default) | `--mock` / `--no-mock` |
| **Provider Abstraction** | Same pipeline works with Ollama, LM Studio, OpenAI, Claude, Groq, and xAI Grok | `--provider` flag | `--provider` flag | `--provider` flag |
## Real-World Application
Natural language optimization, conversational planning.
## Technologies
LLM, Solver
## Architecture
```
┌──────────────┐ JSON ┌───────────┐ Structured ┌──────────┐
│ Natural Lang │ ──────────> │ LLM │ ──────────────> │ Solver │
│ Constraints │ prompt │ (or Mock) │ variables + │ (Z3) │
└──────────────┘ └───────────┘ constraints └──────────┘
problem.json │
Optimal Solution
```
**Stage 1 -- Load Problem**: Reads the scenario's `problem.json` containing natural language constraints, system prompt, objective definition, solver configuration, and a pre-computed mock LLM response.
**Stage 2 -- Get Structured Constraints**: In mock mode, uses the pre-defined `mock_llm_response` from `problem.json`. In live mode, sends the system prompt and natural language constraints to an LLM provider, parses the JSON response into variables and constraints arrays, and retries up to 3 times on parse failure.
**Stage 3 -- Validate**: Checks that each variable has a name, type, and domain. Verifies that all constraint variable references point to existing variable names. Filters out invalid constraints and reports warnings.
**Stage 4 -- Solve**: Creates a Z3 solver session, adds variables and constraints, sets the optimization objective, and solves. Falls back to satisfiability check if the objective cannot be applied.
**Stage 5 -- Interpret Results**: Renders solver assignments in scenario-specific human-readable format (table assignments, dungeon map, trip itinerary).
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/llm-solver-hybrid`:
cd rust && cargo build
cd go && make build
```
## Run
### Go
```bash
cd go
make build
./bin/llm-solver-hybrid --scenario seating
./bin/llm-solver-hybrid --scenario dungeon --verbose
./bin/llm-solver-hybrid --scenario road-trip --step
```
Or directly:
```bash
cd go
go run . --scenario seating
```
### Rust
```bash
cd rust
cargo run -- --scenario seating
cargo run -- --scenario dungeon --verbose
cargo run -- --scenario road-trip --step
```
### Python
```bash
cd python
python3 main.py --scenario seating
python3 main.py --scenario dungeon --verbose
python3 main.py --scenario road-trip --step
```
## Mock vs Live Mode
### Mock Mode (default)
Mock mode uses the pre-computed `mock_llm_response` from each scenario's `problem.json`. No API key or running LLM server is needed. This is the default for Rust, Go, and Python.
```bash
# Go (mock is the default)
go run . --scenario seating
# Rust (mock is the default)
cargo run -- --scenario seating
# Python (mock is the default)
python3 main.py --scenario seating
```
### Live Mode
Live mode calls a real LLM provider to extract structured constraints from natural language. The LLM response is parsed as JSON and validated before being sent to the solver.
```bash
# Go: disable mock with --no-mock
go run . --scenario seating --no-mock --provider ollama --model llama3.2
# Rust: disable mock with --no-mock
cargo run -- --scenario seating --no-mock --provider ollama --model llama3.2
# Python: disable mock with --no-mock
python3 main.py --scenario seating --no-mock --provider ollama --model llama3.2
```
**Supported providers**: `ollama`, `lmstudio`, `openai`, `claude`, `groq`, `xai`
Use `groq` for Groq (`GROQ_API_KEY`) and `xai` for xAI Grok (`XAI_API_KEY`). The provider id `grok` is intentionally not an alias.
**API key setup** (for cloud providers):
```bash
export OPENAI_API_KEY=sk-...
export ANTHROPIC_API_KEY=sk-ant-...
export GROQ_API_KEY=gsk_...
export XAI_API_KEY=xai-...
```
Local providers (Ollama, LM Studio) require the server to be running but no API key.
## Scenarios
### Seating -- Wedding Dinner Arrangement
Assign 12 wedding guests to 3 tables while respecting social constraints: feuding relatives at different tables, couples together, ex-partners separated, language requirements, and table capacity limits. The solver maximizes a happiness score based on social preferences.
- **Variables**: 12 integer variables (one per guest, domain 1--3)
- **Constraints**: 4 (not-equal, equal, linear capacity)
- **Objective**: maximize happiness
### Dungeon -- Game Level Layout
Generate a 5-room dungeon with boss placement, treasure rooms, and progressive difficulty. The boss must be in the last room, treasure rooms cannot overlap with the boss, and difficulty increases as the player goes deeper.
- **Variables**: 9 integer variables (room assignments, difficulty levels)
- **Constraints**: 5 (equality, not-equal, linear progression)
- **Objective**: maximize total challenge
### Road Trip -- National Park Itinerary
Plan a 14-day road trip visiting 5 national parks (Yosemite, Yellowstone, Zion, Glacier, Grand Canyon). Constraints include minimum days at large parks, geographic ordering (visit nearby parks consecutively), and the total day budget.
- **Variables**: 10 integer variables (days-at and visit-order per park)
- **Constraints**: 4 (linear budget, minimum days, ordering)
- **Objective**: maximize total experience
## Interactive Modes
All examples support debugging flags for inspecting pipeline internals:
```bash
# Verbose mode - show raw LLM responses, parsed JSON, solver details
cargo run -- --scenario seating --verbose # Rust
go run . --scenario seating --verbose # Go
# Step mode - pause at each pipeline stage with explanations
cargo run -- --scenario dungeon --step # Rust
go run . --scenario dungeon --step # Go
# Combined mode
cargo run -- --scenario road-trip --verbose --step
go run . --scenario road-trip --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Retry Logic
When running in live mode, the LLM extraction step uses a retry loop (max 3 attempts):
1. **Attempt 1**: Send the system prompt and natural language constraints to the LLM, requesting JSON output with `variables` and `constraints` arrays.
2. **Parse and validate**: Check that the response is valid JSON, contains non-empty `variables` and `constraints` arrays, and that variables have required fields.
3. **On failure**: Append the failed response and an error-feedback message to the conversation, then re-prompt the LLM. The feedback describes the specific parse error (invalid JSON, empty arrays, missing fields).
4. **After 3 failures**: Fall back to the mock response from `problem.json` and continue the pipeline.
This retry-with-feedback pattern is effective because the LLM sees its own previous attempt and the specific error, allowing it to self-correct.
## Scenario Data Format
Each scenario is defined by a single `problem.json` file in `scenarios//`:
| Field | Type | Purpose |
|-------|------|---------|
| `description` | string | Human-readable scenario description |
| `natural_language_constraints` | string[] | Plain English constraints sent to the LLM |
| `system_prompt` | string | System message instructing the LLM how to respond |
| `objective` | object | Optimization objective (`name`, `direction`, `expression`, `label`) |
| `solver_config` | object | Solver configuration (e.g., `timeout_ms`) |
| `mock_llm_response` | object | Pre-computed LLM output with `variables` and `constraints` arrays |
Each variable in `mock_llm_response.variables` has:
```json
{
"name": "guest_anna_table",
"var_type": "integer",
"label": "Table assignment for Anna",
"domain": { "min": 1, "max": 3 }
}
```
Each constraint in `mock_llm_response.constraints` has:
```json
{
"name": "martha_bob_apart",
"constraint_type": "not_equal",
"label": "Aunt Martha and Uncle Bob at different tables",
"variables": ["guest_martha_table", "guest_bob_table"],
"parameters": {}
}
```
An `expected-output.json` file alongside each `problem.json` describes the expected pipeline results in mock mode, useful for regression testing.
### Adding a New Scenario
1. Create a new directory under `scenarios/`
2. Write a `problem.json` with natural language constraints and a mock LLM response
3. Add the scenario's result interpretation logic to `interpretResults` (Go) or `interpret_result` (Rust)
4. Create an `expected-output.json` with the expected mock-mode results
## Prompt Engineering Notes
The quality of LLM-extracted constraints depends heavily on the system prompt. Tips for writing effective prompts:
1. **Specify the output format explicitly**: Tell the LLM to return JSON with `variables` and `constraints` arrays. Mention the exact field names expected (`name`, `var_type`, `domain`, `constraint_type`, `parameters`).
2. **Define variable types and domains**: Instruct the LLM what variable types are available (`integer`, `boolean`) and how to express domains (`min`/`max` for integers).
3. **List supported constraint types**: Enumerate the solver's supported constraint types (`equal`, `not_equal`, `linear`) so the LLM does not invent unsupported types.
4. **Use concrete examples**: Include a short example variable and constraint in the system prompt to anchor the LLM's output format.
5. **Keep it focused**: One system prompt per domain. A seating-specific prompt outperforms a generic "convert any constraints" prompt.
6. **Request JSON-only output**: Explicitly state "Respond with JSON only" to prevent the LLM from wrapping the response in explanatory text or markdown code fences.
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
Each scenario includes an `expected-output.json` that describes the expected structure of the pipeline results in mock mode, useful for regression testing and validation.
---
# LM Studio
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/integrations/lmstudio
Connect to a local LM Studio server for desktop LLM inference
> Run LLM inference on your own machine — connect nxusKit to LM Studio and prototype without cloud dependencies or API keys.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Using LM Studio for local inference
- **Scenario:** Connect to a local LM Studio server for desktop LLM inference
- **`tech_tags` in manifest:** `LLM` — example id **`lmstudio`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Developer local testing, offline prototyping
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/lmstudio`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/lmstudio
```
---
# Model Research Harness
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/integrations/model-research-harness
Research, test, score, rank, and report on model/provider fitness with a provider-neutral nxusKit workflow.
> Research model fitness with provider-neutral runs, Promptfoo import, deterministic policy checks, Bayesian confidence, and dry-run lifecycle recommendations.
**Scenarios**: `basic-ticket-routing` · `promptfoo-import` · `software-dev`
## Edition
**Community** - the default path uses provider-neutral LLM calls, mock/local fixtures, CLIPS-style deterministic policy checks, Bayesian confidence scoring, Promptfoo import, external-runner adapters, and dry-run lifecycle recommendations. Optional configs can use nxusKit CLIPS and Bayesian engines when native SDK dependencies are installed, with fixture-safe fallbacks for the public quickstart.
**Edition note:** Runs in Community Edition. Future Pro profiles may add Solver portfolio optimization and ZEN decision tables.
**Optional Pro profile** - future solver-backed portfolio selection and ZEN decision-table policies require a Pro or trial entitlement. The public quickstart below does not execute Pro code.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS · BN
- **Summary:** Python-first model research and compatibility harness.
- **Scenario:** Import or define evaluation configs, run provider/model test matrices, score outputs, apply policy, aggregate confidence, and write reports.
- **`tech_tags` in manifest:** `LLM, CLIPS, BN` - example id **`model-research-harness`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only - see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** Python is authoritative. CLI/Bash is a thin wrapper around the Python runner.
- **Python:** standard library only for the public mock quickstart. The bundled `.yaml` configs use a strict JSON-compatible YAML subset; PyYAML is optional for broader user-authored YAML.
- **Native CLIPS/BN:** use a Python interpreter with `cffi` installed and an SDK with `python/src` plus `lib/libnxuskit.dylib`. The harness automatically adds `$NXUSKIT_SDK_DIR/python/src` when `NXUSKIT_SDK_DIR` is set; on macOS, avoid Apple/Xcode Python for native-engine runs unless `cffi` is installed there. Set `NXUSKIT_PYTHON=/path/to/python3` for the Bash wrapper when needed.
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Model evaluation | Score model candidates against task-specific outputs and report confidence instead of relying on ad hoc impressions |
| Provider comparison | Compare local and cloud providers through one provider-neutral workflow while keeping capability claims honest |
| Lifecycle policy | Generate dry-run pull, pin, keep, or retest recommendations bounded by deterministic policy |
| Software development workflow research | Exercise code analysis, bug finding, bugfixing, generation, refactoring, and review scenarios with public-safe fixtures |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/model-research-harness`:
cd python && python3 main.py --help
cd bash && bash main.sh --help
```
## Run
Mock mode uses checked-in fixtures. It does not require cloud credentials, Promptfoo, Ollama, or a Pro entitlement.
```bash
cd python
python3 main.py --config ../configs/nxuskit-harness-basic.yaml --mode mock --json
python3 main.py --config ../configs/nxuskit-harness-software-dev.yaml --mode mock --output-dir ../.tmp/software-dev
```
Thin CLI/Bash wrapper:
```bash
cd bash
bash main.sh --config ../configs/nxuskit-harness-basic.yaml --mode mock --json
```
Promptfoo import:
```bash
cd python
python3 main.py --import-promptfoo ../configs/promptfoo-basic.yaml --mode import-promptfoo --json
python3 main.py \
--import-promptfoo ../configs/promptfoo-requires-code.yaml \
--compatibility-report ../.tmp/promptfoo-requires-code-report.json \
--json
```
The second command is intentionally fail-closed: it writes a compatibility report that requires `--allow-code` or `--promptfoo-native-reference`.
## Configs
| Config | Purpose |
|--------|---------|
| `nxuskit-harness-basic.yaml` | Minimal mock quickstart for ticket classification |
| `nxuskit-harness-clips-policy.yaml` | Deterministic CLIPS-style required-field and forbidden-value checks |
| `nxuskit-harness-clips-engine.yaml` | Real nxusKit `ClipsSession` policy execution with Python fallback when native CLIPS is unavailable |
| `nxuskit-harness-bayesian-confidence.yaml` | Posterior confidence from sparse weighted evidence |
| `nxuskit-harness-bn-engine.yaml` | Real nxusKit BN inference over model-fitness evidence with beta fallback when native BN is unavailable |
| `nxuskit-harness-local-vs-cloud.yaml` | Local fixture versus cloud-reference fixture comparison |
| `nxuskit-harness-structured-output.yaml` | Native JSON-mode claims versus harness-side schema validation |
| `nxuskit-harness-lifecycle-policy.yaml` | Dry-run cache and lifecycle recommendations |
| `nxuskit-harness-lifecycle-mutation-fixture.yaml` | Public-safe mutation gate fixture requiring both external and lifecycle approval flags |
| `nxuskit-harness-matrix-template.yaml` | Compact prompt/parameter matrix expansion syntax |
| `nxuskit-harness-native-ollama-template.yaml` | Native Ollama schema, image, thinking, and tool-call knobs behind harness scoring |
| `nxuskit-harness-software-dev.yaml` | Code analysis, bug finding, bugfixing, code generation, refactoring, and review scenarios |
| `nxuskit-harness-external-command-fixture.yaml` | Public-safe fixture contract for wrapping operational runners |
| `nxuskit-harness-devops-ollama-parity.yaml` | Opt-in local adapter shape for a private Ollama research harness checkout |
| `promptfoo-basic.yaml` | Promptfoo-compatible config that imports and runs |
| `promptfoo-requires-code.yaml` | Promptfoo config that requires explicit trust or native-reference mode |
Test blocks may include a `matrix` object to expand variants without duplicating config:
```json
{
"id": "format-{{ prompt_variant }}-think-{{ think }}",
"matrix": {
"prompt_variant": ["baseline", "strict"],
"think": ["off", "low"]
}
}
```
Each combination is merged into `test.vars`, so prompts, ids, and adapter placeholders can reference the generated values.
## Operational Adapter Mode
The harness can wrap existing operational research runners through explicit external-command tests. This is useful when a team already has domain-specific scripts for local Ollama inventory, structured extraction, image/document pipelines, cache policy, or row-level fixture scoring.
External commands are fail-closed and never run unless `--allow-external` is supplied:
```bash
cd python
python3 main.py \
--config ../configs/nxuskit-harness-external-command-fixture.yaml \
--allow-external \
--json
```
The fixture config runs only checked-in deterministic fixture commands. The DevOps parity config is a template for private/local use and expects `OLLAMA_MODEL_TESTING_ROOT` to point at an existing `ollama-model-testing` checkout:
```bash
export OLLAMA_MODEL_TESTING_ROOT=/path/to/ollama-model-testing
cd python
python3 main.py \
--config ../configs/nxuskit-harness-devops-ollama-parity.yaml \
--allow-external \
--only-test common-sense-carwash \
--output-dir ../.tmp/devops-parity
```
Use `--exclude-test` to skip expensive tests from a larger config. Both `--only-test` and `--exclude-test` accept comma-separated ids and may be repeated.
The public adapter normalizes DevOps-style report shapes for common-sense curation, prompted/native tool intent, direct structured extraction, two-stage OCR or VLM pipelines, safe-labs row-level scoring, and CSV/TSV comparison helpers. The DevOps parity template also includes non-mutating `ollama-cache status`, `list`, and `plan-evict` checks.
External lifecycle mutation such as pulling, removing, pinning, or evicting models requires a test with `external_command.mutation: true` and both flags:
```bash
python3 main.py \
--config ../configs/nxuskit-harness-lifecycle-mutation-fixture.yaml \
--allow-external \
--allow-lifecycle-mutations
```
Public configs should keep mutation commands behind explicit customer policy bounds.
## Output
Each run can write:
- `result.json`
- `summary.md`
- Promptfoo compatibility report when importing Promptfoo configs
- Scenario-level pass/fail matrix
- Provider/model recommendation table
- Capability truth table
The capability truth table separates native provider guarantees from harness-side validation and repair. For v0.9.4, Groq remains provider id `groq` with `GROQ_API_KEY`; xAI Grok uses provider id `xai` with `XAI_API_KEY`.
## Live Mode
Live mode uses nxusKit provider factories for `ollama`, `lmstudio`, `openai`, `claude`, `groq`, and `xai` when credentials or local services are configured:
```bash
cd python
python3 main.py --config ../configs/nxuskit-harness-basic.yaml --mode live --provider ollama --model llama3.2
```
Strict schema support, native tool calling, and thinking controls vary by provider and model. The harness reports those differences instead of treating every backend as equivalent.
For Ollama features that are not yet normalized across every provider, set `native_ollama: true` on the provider or test. That path uses Ollama's local `/api/chat` API directly and supports `schema`/JSON `format`, `think`, `tools`, image files, `options`, and `num_predict`. If an Ollama build rejects the `think` field, the harness retries once without it and records the observed metadata.
## Promptfoo Compatibility
Portable Promptfoo configs import directly. Prompt/provider matrices expand to harness tests. Configs with executable or provider-native behavior fail closed unless the caller acknowledges the trust boundary:
```bash
python3 main.py --import-promptfoo ../configs/promptfoo-requires-code.yaml --allow-code --json
python3 main.py --import-promptfoo ../configs/promptfoo-requires-code.yaml --promptfoo-native-reference --json
```
With `--allow-code`, JavaScript assertions are executed through `node` when available. Unsupported assertions still fail closed instead of silently disappearing from the score.
## nxusKit Engine Hooks
The default configs are fixture-safe and run with stdlib Python. Engine configs demonstrate how the same harness can call nxusKit-native reasoning providers:
- `policy.engine: "nxuskit-clips"` loads a CLIPS rules file through `ClipsSession`, asserts the model output as a fact, and converts emitted finding facts into policy dispositions. `on_engine_unavailable: "fallback-python"` keeps public smoke tests runnable when native CLIPS dependencies are not installed.
- `bayesian.engine: "nxuskit-bn"` loads a BIF model through nxusKit BN, maps test scores into evidence, and queries a configured posterior. `on_engine_unavailable: "fallback-beta"` keeps reports useful on machines without native BN dependencies.
Native-engine smoke example:
```bash
export NXUSKIT_SDK_DIR="${NXUSKIT_SDK_DIR:-$HOME/.nxuskit/sdk/current}"
export NXUSKIT_LIB_PATH="$NXUSKIT_SDK_DIR/lib/libnxuskit.dylib"
# Pick a Python with cffi installed. On this development Mac, Homebrew Python works.
/opt/homebrew/bin/python3 -c "import cffi"
/opt/homebrew/bin/python3 python/main.py \
--config configs/nxuskit-harness-clips-engine.yaml \
--json
/opt/homebrew/bin/python3 python/main.py \
--config configs/nxuskit-harness-bn-engine.yaml \
--json
```
## Release Notes For Review
- Python is the authoritative implementation. Bash remains a thin wrapper for automation-friendly entry points.
- Promptfoo import covers common portable config shapes, prompt/provider matrices, explicit trust gates for code/native behavior, and JavaScript assertion execution under `--allow-code`.
- CLIPS and Bayesian examples include both deterministic/fallback checks and opt-in nxusKit-native engine execution.
- Operational parity is provided through explicit external-command adapters, not private baked-in assumptions. Public releases should keep private rankings, fixture paths, and cache policy defaults out of bundled configs.
- Lifecycle mutation remains blocked unless both `--allow-external` and `--allow-lifecycle-mutations` are supplied, and customer auto-approval should be bounded in config.
---
# Ollama
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/integrations/ollama
Connect to a local Ollama instance for private LLM inference
> Run open-source LLMs on your own hardware using the same nxusKit interface you already use for Claude and OpenAI.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Using Ollama for local inference
- **Scenario:** Connect to a local Ollama instance for private LLM inference
- **`tech_tags` in manifest:** `LLM` — example id **`ollama`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
On-premise AI deployment, air-gapped inference
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/ollama`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/ollama
```
---
# ZEN Decision Tables -- Personality Variants & Hit Policies
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/integrations/zen-decisions
Demonstrates ZEN JSON Decision Model (JDM) evaluation through three scenarios: a maze-navigating rat with interchangeable personality variants, a potion recipe selector using collect hit policy, and a food truck planner combining decision tables with expression nodes. This is the first nxusKit example built on the ZEN decision engine.
> Evaluate business decision tables in Go, Rust, and Python using the ZEN engine — from pricing rules to eligibility checks, with first-hit and collect hit policies.
**Scenarios**: `maze-rat` · `potion` · `food-truck`
## Edition
**Pro** — requires a Pro (or trial) entitlement for ZEN evaluation APIs.
## What this demonstrates
**Difficulty: Starter** 🟢 · ZEN
- **Summary:** ZEN decision table evaluation via nxusKit SDK
- **Scenario:** Evaluate business decision tables using the ZEN engine
- **`tech_tags` in manifest:** `ZEN` — example id **`zen-decisions`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go |
|---------|-------------|------|-----|
| **ZEN Evaluate** | Stateless JDM evaluation | `nxuskit_zen_evaluate()` | `nxuskit-go.ZenEvaluate()` |
| **First Hit Policy** | Return first matching rule | `"hitPolicy": "first"` | `"hitPolicy": "first"` |
| **Collect Hit Policy** | Return all matching rules | `"hitPolicy": "collect"` | `"hitPolicy": "collect"` |
| **Expression Nodes** | Computed fields in pipeline | `expressionNode` | `expressionNode` |
| **Personality Variants** | Same input, different models | Multiple JDM files | Multiple JDM files |
| **Result Freeing** | Memory management for results | `nxuskit_zen_free_result()` | Automatic (Go wrapper) |
## Real-World Application
Pricing rules, eligibility determination, policy evaluation.
## Technologies
ZEN
## Pipeline Architecture
### Maze Rat (First Hit Policy)
```
┌──────────────────┐
│ cautious JDM │──> action: sniff_around
└──────────────────┘
┌───────────┐ ┌──────────────────┐
│ Input │──┬──>│ greedy JDM │──> action: go_right
│ (shared) │ │ └──────────────────┘
└───────────┘ │ ┌──────────────────┐
└──>│ explorer JDM │──> action: go_right
└──────────────────┘
```
### Potion (Collect Hit Policy)
```
┌───────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Input │──>│ Decision Table │──>│ All Matching │
│ │ │ (collect policy) │ │ Recipes │
└───────────┘ └──────────────────┘ └──────────────────┘
```
### Food Truck (Decision + Expression Pipeline)
```
┌───────────┐ ┌──────────────────┐ ┌──────────────────┐ ┌──────────┐
│ Input │──>│ Decision Table │──>│ Expression Node │──>│ Output │
│ │ │ (location/price) │ │ (menu/restock) │ │ │
└───────────┘ └──────────────────┘ └──────────────────┘ └──────────┘
```
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/zen-decisions`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario maze-rat
cargo run -- --scenario potion --verbose
cargo run -- --scenario food-truck --step
```
### Go
```bash
cd go
make build
./bin/zen-decisions --scenario maze-rat
./bin/zen-decisions --scenario potion --verbose
./bin/zen-decisions --scenario food-truck --step
```
Or directly:
```bash
cd go
go run . --scenario maze-rat
```
## Scenarios
### Maze Rat (Personality Variants)
A maze-navigating rat with three interchangeable personality variants, each encoded as a separate JDM file. All share the same input schema but produce different actions.
**Input fields**: `scent_strength` (1-10), `dead_ends_nearby` (0-5), `hunger_level` (1-10)
**Output fields**: `action` (go_left, go_right, backtrack, sniff_around, rest), `confidence` (0.0-1.0)
| Personality | Strategy | Key Trait |
|-------------|----------|-----------|
| **Cautious** | Avoids dead ends, backtracks when risky | High dead_ends triggers backtrack |
| **Greedy** | Always follows scent, ignores dead ends | Strong scent always means go_right |
| **Explorer** | Seeks new paths, ignores scent | Prefers go_left to explore unknown areas |
With the default input (`scent_strength=7, dead_ends_nearby=2, hunger_level=4`):
- Cautious: sniff_around (0.60 confidence) -- strong scent but hesitant
- Greedy: go_right (0.95 confidence) -- immediately follows strong scent
- Explorer: go_right (0.80 confidence) -- few dead ends, worth exploring right
### Potion (Collect Hit Policy)
A potion recipe selector that returns all matching recipes using the collect hit policy. Multiple recipes can match the same ingredients and desired effect.
**Input fields**: `ingredients` (comma-separated list), `desired_effect` (healing, strength, invisibility, speed), `caution_level` (low, medium, high)
**Output fields**: `recipe_name`, `recipe_steps`, `warnings`
With the default input (`ingredients=mushroom,moonstone, desired_effect=healing, caution_level=medium`):
- Healing Tonic (mushroom + healing matches)
- Unknown Brew (default catch-all also matches under collect policy)
### Food Truck (Expression Nodes)
A food truck location and menu planner that chains a decision table with an expression node. The decision table selects location and base pricing; the expression node computes menu adjustments.
**Input fields**: `time_of_day`, `weather`, `nearby_events`, `inventory_level`
**Output fields**: `location`, `price_multiplier`, `menu_adjustment`, `restock_alert`
With the default input (`time_of_day=lunch, weather=sunny, nearby_events=large, inventory_level=medium`):
- Location: Main Street Park (lunch + sunny + large event)
- Price multiplier: 1.3 (premium for large event)
- Menu: full menu (medium inventory)
- Restock alert: false
## Decision Table Concepts
### Hit Policies
| Policy | Behavior | Use Case |
|--------|----------|----------|
| **first** | Return the first matching rule | Prioritized rules, fallback chains |
| **collect** | Return all matching rules | Multiple recommendations, audit trails |
With **first** hit policy, rule order matters -- the first match wins. With **collect**, all matching rules are returned as an array.
### Expression Nodes
Expression nodes compute derived fields using simple expressions:
```json
{
"type": "expressionNode",
"content": {
"expressions": [
{"key": "output_field", "value": "input_field"},
{"key": "computed", "value": "if condition then 'a' else 'b'"}
]
}
}
```
Expressions support:
- Field references: `field_name` passes through a value
- Conditionals: `if condition then value1 else value2`
- Comparisons: `==`, `!=`, `>`, `<`, `>=`, `<=`
- String literals: `'single quoted'`
### CLIPS vs ZEN Comparison
| Aspect | CLIPS (Rule Engine) | ZEN (Decision Tables) |
|--------|--------------------|-----------------------|
| **Model format** | `.clp` rule files | `.json` JDM files |
| **Evaluation** | Forward-chaining inference | Table lookup + expressions |
| **State** | Working memory (facts) | Stateless per evaluation |
| **Complexity** | Arbitrary rule logic | Structured table/expression |
| **Best for** | Complex reasoning chains | Configuration-driven decisions |
| **Hit policies** | N/A (all matching rules fire) | first, collect |
| **Session management** | Required (create/destroy) | None (stateless) |
## JDM (JSON Decision Model) Format
The JDM format follows the GoRules specification:
```json
{
"contentType": "application/vnd.gorules.decision",
"edges": [
{"id": "e1", "sourceId": "input", "targetId": "dt1", "type": "edge"}
],
"nodes": [
{"id": "input", "type": "inputNode", ...},
{"id": "dt1", "type": "decisionTableNode", "content": {...}},
{"id": "output", "type": "outputNode", ...}
]
}
```
### Supported Node Types
| Type | Description |
|------|-------------|
| `inputNode` | Entry point; passes input data to connected nodes |
| `outputNode` | Exit point; returns the final result |
| `decisionTableNode` | Evaluates input against rules with configurable hit policy |
| `expressionNode` | Computes derived fields from expressions |
| `switchNode` | Routes to different branches based on conditions |
**Note**: `functionNode` (JavaScript) is not supported by the nxusKit ZEN provider.
### Rule Field Formats
- Comparison operators: `> 30`, `<= 10`, `>= 7`, `== 5`, `!= 0`
- String values (in outputs): `"\"cool\""` (double-quoted inside JSON)
- Numeric values: `0.85`, `1.3`
- Boolean values: `true`, `false`
- Empty field: `""` (matches any value / wildcard)
## Interactive Modes
```bash
# Verbose mode -- show raw JSON results
cargo run -- --scenario maze-rat --verbose # Rust
go run . --scenario maze-rat --verbose # Go
# Step mode -- pause at each step with explanations
cargo run -- --scenario potion --step # Rust
go run . --scenario potion --step # Go
# Combined mode
cargo run -- --scenario food-truck --verbose --step
go run . --scenario food-truck --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
Each scenario includes an `expected-output.json` that describes expected results for regression testing.
---
# Auth Helper
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/auth-helper
Demonstrates OAuth login flow and credential management using the nxuskit SDK.
> Wire up OAuth flows and API key credentials across every provider your app supports, with a single unified auth interface.
**Scenarios**: `status` · `set` · `remove` · `dashboard`
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · Auth · OAuth
- **Summary:** OAuth login flow and credential management helper *(from `conformance/examples_manifest.json`: **auth-helper**)*.
- **Scenario:** List providers, check auth status, set credentials, initiate OAuth flows.
- **`tech_tags`:** `Auth`, `OAuth`.
- Listing all supported providers and their authentication methods
- Checking authentication status for individual providers
- Setting and removing API key credentials
- Initiating an OAuth login flow (for OAuth-capable providers)
- Viewing a complete authentication status dashboard
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** Go, Rust (CLI and egui GUI).
## Tier
Community (free)
## Languages
| Language | Path | Description |
|----------|------|-------------|
| Go | [go/](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/auth-helper/go/) | CLI-based auth management |
| Rust (CLI) | [cli/](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/auth-helper/cli/) | Terminal-based OAuth + credential management |
| Rust (core) | [core/](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/auth-helper/core/) | Shared auth library used by CLI and egui |
| Rust (egui) | [egui/](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/auth-helper/egui/) | GUI-based OAuth flow with egui |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# Go
cd go && make build
# Rust CLI
cd cli && cargo build
# Rust GUI (requires egui dependencies)
cd egui && cargo build
```
## Run
```bash
# Go
cd go && ./bin/auth-helper
# Rust CLI
cd cli && cargo run
# Rust GUI
cd egui && cargo run
```
## Notes
- No current providers support OAuth yet (infrastructure is ready for future providers)
- API key authentication works with all providers that require credentials
- The OAuth flow launches a browser and starts a localhost callback server
---
# Basic Chat
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/basic-chat
Send a single chat message and receive a response.
> Send your first LLM chat message in minutes, then swap providers without touching your application code.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Basic chat completion with a simple prompt
- **Scenario:** Send a single chat message and receive a response
- **`tech_tags` in manifest:** `LLM` — example id **`basic-chat`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Customer support chatbot, FAQ assistant
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
## Build
Use an installed SDK (`NXUSKIT_SDK_DIR`); from the repo root, `scripts/test-examples.sh` patches `nxuskit` path deps to that tree and builds this crate.
```bash
cd rust && cargo build
cd ../go && make build
cd ../python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/basic-chat
```
### Python
```bash
cd python
python main.py
```
See also: [`EXAMPLE_README_TEMPLATE.md`](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/examples/EXAMPLE_README_TEMPLATE.md) for the standard README sections.
---
# Bayesian Inference Pattern
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/bayesian-inference
Demonstrates Bayesian Network inference using multiple algorithms: load a BIF model, set observed evidence, and compute posterior probability distributions over unobserved variables using exact and approximate methods.
> Run exact and approximate Bayesian inference on real-world diagnostic models using four algorithms and three themed scenarios — all from a single SDK call.
**Scenarios**: `haunted-house` · `coffee-shop` · `plant-doctor`
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · BN
- **Summary:** Bayesian network inference via nxusKit SDK
- **Scenario:** Build a Bayesian network and perform probabilistic inference
- **`tech_tags` in manifest:** `BN` — example id **`bayesian-inference`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **BIF Model Loading** | Parse Bayesian Interchange Format files into a directed acyclic graph with conditional probability tables |
| **Evidence Setting** | Clamp observed variables to known values before inference |
| **Variable Elimination (VE)** | Exact inference by marginalizing out variables in an optimal elimination order |
| **Junction Tree (JT)** | Exact inference via clique tree message passing with global consistency |
| **Loopy Belief Propagation (LBP)** | Approximate inference via iterative message passing on the factor graph |
| **Gibbs Sampling** | Approximate MCMC inference by sampling each variable conditioned on its Markov blanket |
| **Streaming Results** | Progressive output of posteriors as each algorithm step completes |
| **Algorithm Comparison** | Side-by-side comparison of exact and approximate posteriors with tolerance checking |
**Provider Compatibility**: Uses the nxusKit Bayesian Network provider (no LLM provider required)
## Technologies
BN
## Pattern Overview
Many real-world diagnosis and prediction problems can be modeled as Bayesian Networks -- directed acyclic graphs where nodes represent random variables and edges encode conditional dependencies. Given partial observations (evidence), inference computes updated beliefs (posteriors) about unobserved variables. This pattern walks through four inference algorithms on scenario-driven models loaded from BIF files, comparing exact and approximate results.
## Scenarios
Three themed scenarios are included under `scenarios/`:
- **Haunted House** -- Investigate a supposedly haunted house by observing cold spots, flickering lights, and muddy footprints, then infer the probability of a ghost, raccoon, wiring fault, and cold draft. 8 variables, 8 CPTs.
- **Coffee Shop** -- Diagnose a bad espresso shot by observing bitter taste, no sourness, and no wateriness, then infer extraction level, grind size, water temperature, bean age, and freshness. 8 variables, 8 CPTs.
- **Plant Doctor** -- Diagnose a sick plant by observing yellow leaves, wilting, no spots, and slow growth, then infer overwatering, nutrient deficiency, sunlight issues, disease, and pest infestation. 9 variables, 9 CPTs.
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/bayesian-inference`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario haunted-house
cargo run -- --scenario coffee-shop --verbose
cargo run -- --scenario plant-doctor --step
```
### Go
```bash
cd go
make build
./bin/bayesian-inference --scenario haunted-house
./bin/bayesian-inference --scenario coffee-shop --verbose
./bin/bayesian-inference --scenario plant-doctor --step
```
### Python
```bash
cd python
pip install -e ../../../../packages/nxuskit-py # if not already installed
python main.py --scenario haunted-house
python main.py --scenario coffee-shop --step
```
## Inference Steps
Each run progresses through four algorithm steps:
| Step | Algorithm | Type | What It Does |
|------|-----------|------|--------------|
| 1 | **Variable Elimination** | Exact | Eliminates variables one at a time, computing exact marginal posteriors via factor multiplication and summation |
| 2 | **Junction Tree** | Exact | Builds a clique tree from the model, propagates messages for globally consistent exact posteriors |
| 3 | **Loopy Belief Propagation** | Approximate | Passes messages iteratively on the factor graph until convergence (or max iterations) |
| 4 | **Gibbs Sampling** | Approximate | Draws MCMC samples from the posterior, estimating marginals from sample frequencies |
## Scenario Data Format
Each scenario is a directory containing two files:
### `model.bif` -- Bayesian Interchange Format
Defines the network structure, variable domains, and conditional probability tables:
```bif
network unknown {
}
variable ghost {
type discrete [ 2 ] { yes, no };
}
variable cold_spots {
type discrete [ 2 ] { yes, no };
}
probability ( ghost ) {
table 0.05, 0.95;
}
probability ( cold_spots | ghost, cold_draft ) {
(yes, yes) 0.9, 0.1;
(yes, no) 0.8, 0.2;
(no, yes) 0.6, 0.4;
(no, no) 0.05, 0.95;
}
```
### `evidence.json` -- Observed Variables
Maps variable names to their observed values:
```json
{
"cold_spots": "yes",
"flickering_lights": "yes",
"footprints": "muddy"
}
```
### `expected-output.json` -- Golden Output
Contains exact posteriors from VE/JT and tolerance bounds for LBP/Gibbs, plus qualitative observations about the inference results. Used for automated validation of implementation correctness.
## Algorithm Comparison
| Property | Variable Elimination | Junction Tree | Loopy BP | Gibbs Sampling |
|----------|---------------------|---------------|----------|----------------|
| **Type** | Exact | Exact | Approximate | Approximate |
| **Method** | Factor marginalization | Clique tree message passing | Iterative factor graph messages | MCMC sampling |
| **Guarantees** | Exact posteriors | Exact posteriors | No convergence guarantee on loopy graphs | Converges asymptotically |
| **Speed** | Fast for small networks | Fast after tree construction | Fast per iteration, may need many | Slow (many samples needed) |
| **Memory** | Exponential in treewidth | Exponential in max clique size | Linear in edges | Linear in variables |
| **Best For** | Small-medium networks | Repeated queries on same model | Large networks with weak loops | Complex models, posterior samples |
| **Parameters** | Elimination order | None (automatic) | Max iterations, damping factor | Num samples, burn-in, seed |
VE and JT should produce identical posteriors (both are exact). LBP and Gibbs posteriors should fall within the tolerance bounds specified in `expected-output.json`.
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Haunted House | Fault diagnosis, anomaly detection, sensor fusion from multiple noisy sensors pointing to hidden causes |
| Coffee Shop | Manufacturing quality control, process parameter tuning, root cause analysis in production |
| Plant Doctor | Medical diagnosis, agricultural advisory systems, multi-symptom differential diagnosis |
## Interactive Modes
All implementations support debugging flags:
```bash
# Verbose mode - show CPTs, elimination orders, message schedules, and sample traces
cargo run -- --scenario haunted-house --verbose # Rust
./bin/bayesian-inference --scenario haunted-house --verbose # Go
python main.py --scenario haunted-house --verbose # Python
# Step mode - pause at each algorithm with explanations
cargo run -- --scenario haunted-house --step # Rust
./bin/bayesian-inference --scenario haunted-house --step # Go
python main.py --scenario haunted-house --step # Python
# Combined mode
cargo run -- --scenario haunted-house --verbose --step
```
Or use environment variables (Rust and Go only):
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python
cd python && python -m pytest
```
## Production Considerations
1. **Algorithm selection**: Use VE or JT for small-to-medium networks where exact inference is tractable. Switch to LBP or Gibbs for large networks where treewidth makes exact inference infeasible.
2. **Convergence monitoring**: LBP may not converge on graphs with strong loops. Monitor message deltas and set a maximum iteration count.
3. **Sample size tuning**: For Gibbs sampling, increase `num_samples` and `burn_in` for tighter posterior estimates. Use a fixed seed for reproducibility in testing.
4. **Evidence validation**: Verify that evidence variable names and values match the BIF model before running inference. Mismatched evidence silently produces incorrect posteriors.
---
# Blocking API
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/blocking-api
Make synchronous LLM calls without async runtime
> Call LLMs synchronously from any Rust code — no async runtime required, no await syntax, no tokio dependency to manage.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Synchronous blocking API for simpler use cases
- **Scenario:** Make synchronous LLM calls without async runtime
- **`tech_tags` in manifest:** `LLM` — example id **`blocking-api`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
CLI tools, batch processing scripts
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/blocking-api`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/blocking-api
```
---
# Capability Detection
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/capability-detection
Query provider capabilities before dispatching requests
> Stop hardcoding model names — query provider capabilities at runtime and let task requirements drive model selection across any LLM backend.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Detecting provider capabilities at runtime
- **Scenario:** Query provider capabilities before dispatching requests
- **`tech_tags` in manifest:** `LLM` — example id **`capability-detection`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Adaptive AI middleware, feature-gated UX
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/capability-detection`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/capability-detection
```
---
# Convenience API
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/convenience-api
Use simplified one-liner API for quick LLM calls
> Skip the boilerplate: call any LLM with a single line, letting nxusKit detect your provider and credentials automatically.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** LiteLLM-style convenience API usage
- **Scenario:** Use simplified one-liner API for quick LLM calls
- **`tech_tags` in manifest:** `LLM` — example id **`convenience-api`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Rapid prototyping, scripting with LLM capabilities
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/convenience-api`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/convenience-api
```
---
# Model Router (Cost Tiers) Pattern
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/cost-routing
Demonstrates intelligent routing of requests to different models based on task complexity to optimize cost and quality.
> Route every LLM request to the right model for the job, so you stop paying premium prices for economy-grade tasks.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Cost-aware provider routing and selection
- **Scenario:** Route requests to the cheapest capable provider
- **`tech_tags` in manifest:** `LLM` — example id **`cost-routing`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **Provider Abstraction** | Same interface for all models enables seamless tier switching |
| **Request Portability** | `ChatRequest` works identically across model tiers |
| **Token Normalization** | Consistent token usage tracking for cost calculations |
**Provider Compatibility**: Works with any provider supporting multiple models (OpenAI, Ollama, etc.)
## Pattern Overview
Not all prompts need the most expensive model. This pattern analyzes prompt characteristics and routes requests to an appropriate cost tier, balancing quality requirements with cost efficiency.
## Cost Tiers
| Tier | Model | Use Case | Cost |
|------|-------|----------|------|
| Economy | gpt-4o-mini | Simple queries, lookups | $ |
| Standard | gpt-4o | General tasks, explanations | $$ |
| Premium | gpt-4-turbo | Complex analysis, reasoning | $$$ |
## Classification Heuristics
The example uses simple heuristics to classify tasks:
1. **Premium tier triggers**:
- Keywords: "analyze", "compare", "evaluate", "synthesize", "critique"
- Prompt length > 1000 characters
2. **Standard tier**:
- Prompt length > 200 characters (without premium keywords)
3. **Economy tier**:
- Short, simple prompts
## Real-World Application
Cost-optimized AI platform, budget-aware inference.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/cost-routing`:
cd rust && cargo build
cd go && make build
```
## Library usage
### Rust
```rust
use cost_routing::{classify_task, routed_chat, CostTier};
// Classify without making API call
let tier = classify_task(prompt);
println!("Would use: {} tier", tier.as_str());
// Or route and execute
let result = routed_chat(&provider, prompt).await?;
println!("Used {} tier", result.tier.as_str());
```
### Go
```go
// Classify without making API call
tier := ClassifyTask(prompt)
fmt.Println("Would use:", tier.Name(), "tier")
// Or route and execute
result, err := RoutedChat(ctx, provider, prompt)
fmt.Println("Used", result.Tier.Name(), "tier")
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Advanced Classification
For production, consider more sophisticated approaches:
1. **Intent classification**: Use a small model to classify intent first
2. **Historical data**: Learn from past prompt/tier success rates
3. **User preferences**: Allow users to specify quality requirements
4. **Dynamic pricing**: Adjust tiers based on current API pricing
## Production Considerations
1. **Calibration**: Tune thresholds based on your specific use cases
2. **Monitoring**: Track accuracy and cost savings by tier
3. **Override capability**: Allow manual tier selection for edge cases
4. **A/B testing**: Validate routing decisions improve outcomes
---
# Multi Provider
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/multi-provider
Configure and switch between multiple LLM providers at runtime
> Run the same prompt across Claude, OpenAI, and Ollama simultaneously using one unified interface that normalizes responses and token usage.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Using multiple providers in one application
- **Scenario:** Configure and switch between multiple LLM providers at runtime
- **`tech_tags` in manifest:** `LLM` — example id **`multi-provider`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Multi-vendor AI gateway, provider comparison tool
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/multi-provider`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/multi-provider
```
### Python
```bash
cd python
python main.py
```
---
# Polymorphic
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/polymorphic
Use trait objects and interfaces to abstract over providers
> Swap LLM providers at runtime without touching your application logic — nxusKit's polymorphic patterns keep your code provider-agnostic from day one.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Polymorphic provider patterns with trait objects
- **Scenario:** Use trait objects and interfaces to abstract over providers
- **`tech_tags` in manifest:** `LLM` — example id **`polymorphic`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Plugin architecture, provider-agnostic application layer
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/polymorphic`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/polymorphic
```
---
# Multi-Provider Fallback Pattern
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/retry-fallback
Demonstrates automatic failover between multiple LLM providers for improved reliability.
> Chain multiple LLM providers together so a failed request automatically reroutes to the next available provider without changing your application code.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Retry and fallback strategies across providers
- **Scenario:** Automatically retry failed requests and fall back to alternate providers
- **`tech_tags` in manifest:** `LLM` — example id **`retry-fallback`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **Provider Abstraction** | `LLMProvider` trait/interface enables heterogeneous provider collections |
| **Unified Error Handling** | Same error types across all providers enable consistent fallback logic |
| **Provider Interchangeability** | Swap providers without changing application code |
**Provider Compatibility**: Claude, OpenAI, Ollama, and any custom provider implementing `LLMProvider`
## Pattern Overview
When working with LLM APIs, network issues, rate limits, or provider outages can interrupt service. This pattern chains multiple providers together, automatically falling back to the next provider when one fails.
## Key Features
- Sequential provider chain with automatic failover
- First successful response wins
- Error aggregation for debugging
- Provider-agnostic implementation
## Real-World Application
High-availability AI service, resilient inference pipeline.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/retry-fallback`:
cd rust && cargo build
cd go && make build
```
## Library usage
### Rust
```rust
use retry_fallback::chat_with_fallback;
use nxuskit::prelude::*;
// Create multiple providers (could be different providers in production)
let providers: Vec> = vec![
Box::new(OllamaProvider::builder().base_url("http://primary:11434").model("llama3").build()?),
Box::new(OllamaProvider::builder().base_url("http://secondary:11434").model("llama3").build()?),
];
// Request automatically falls back on failure
let response = chat_with_fallback(&providers, &request).await?;
```
### Go
```go
import llmkit "github.com/llmkit/nxuskit-go"
// Create multiple providers
providers := []llmkit.LLMProvider{provider1, provider2, provider3}
// Request automatically falls back on failure
resp, err := ChatWithFallback(ctx, providers, req)
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
Both implementations include unit tests using mock providers:
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Production Considerations
1. **Provider diversity**: Use different providers (OpenAI, Claude, Ollama) for true redundancy
2. **Timeout handling**: Set appropriate timeouts to avoid long waits before failover
3. **Circuit breakers**: Consider adding circuit breaker pattern for repeated failures
4. **Metrics**: Track which providers are failing to identify systemic issues
---
# Solver Pattern
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/solver
Demonstrates the full solver lifecycle: satisfaction checking, single- and multi-objective optimization, soft constraints, and what-if analysis using push/pop scoping.
> Define variables, add constraints, and solve complex planning problems with Z3 — without leaving your nxusKit workflow.
**Scenarios**: `theme-park` · `space-colony` · `fantasy-draft`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · Solver
- **Summary:** Z3 constraint solver integration via nxusKit SDK
- **Scenario:** Define and solve constraint satisfaction problems with Z3
- **`tech_tags` in manifest:** `Solver` — example id **`solver`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **SolverSession Lifecycle** | Create, build model incrementally, solve, and close via the nxuskit SDK |
| **Variable & Constraint Model** | Define typed variables with domains and add hard/soft constraints |
| **Satisfaction Solving** | Check feasibility before optimizing |
| **Single & Multi-Objective Optimization** | Maximize/minimize one or many weighted objectives |
| **Soft Constraints** | Weighted preferences the solver satisfies when possible |
| **Push/Pop Scoping** | Reversible what-if analysis without rebuilding the model |
**Provider Compatibility**: Uses the nxusKit Z3-based constraint solver (no LLM provider required)
## Technologies
Solver
## Pattern Overview
Many real-world planning problems require finding valid assignments to decision variables that satisfy a set of constraints, then optimizing one or more objectives. This pattern walks through five progressive solver steps using scenario-driven problem definitions loaded from JSON files.
## Scenarios
Three themed scenarios are included under `scenarios/`:
- **Theme Park Planning** -- Decide how many rides to build, staff to hire, land to allocate, and ticket prices to set while staying within budget and space constraints. Objectives: maximize rides, minimize budget.
- **Space Colony Planning** -- Design a self-sustaining colony by balancing population against habitat modules, solar panels, water recyclers, and food domes. What-if: simulate a solar storm that degrades panel efficiency by 30%.
- **Fantasy Sports Draft** -- Build an optimal roster under a $50,000 salary cap by selecting stats across QB, RB, WR, TE, and DEF positions to maximize total fantasy points. What-if: simulate key player injuries.
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/solver`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario theme-park
cargo run -- --scenario space-colony --verbose
cargo run -- --scenario fantasy-draft --step
```
### Go
```bash
cd go
make build
./bin/solver --scenario theme-park
./bin/solver --scenario space-colony --verbose
./bin/solver --scenario fantasy-draft --step
```
### Python
```bash
cd python
pip install -e ../../../../packages/nxuskit-py # if not already installed
python main.py --scenario theme-park
python main.py --scenario fantasy-draft --step
```
## Solver Steps
Each run progresses through five steps (steps are skipped when a scenario lacks the relevant definitions):
| Step | Name | What It Does |
|------|------|--------------|
| 1 | **Satisfaction** | Adds hard constraints and checks whether any feasible assignment exists (`sat` / `unsat`) |
| 2 | **Optimization** | Sets a single objective (maximize or minimize) and finds the optimal assignment |
| 3 | **Multi-objective** | Combines multiple objectives with weights into a single weighted optimization |
| 4 | **Soft constraints** | Adds weighted preference constraints the solver may violate if necessary |
| 5 | **What-if analysis** | Uses `push` / `pop` to temporarily add constraints, solve, then restore the base model |
## Scenario Data Format
Each scenario is a directory containing a `problem.json` file with the following structure:
```jsonc
{
"name": "Scenario Name",
"description": "Human-readable description of the planning problem.",
"variables": [
{
"name": "budget",
"var_type": "integer", // "integer", "real", or "boolean"
"domain": { "min": 50000, "max": 500000 }, // omitted for booleans
"label": "Total budget in dollars"
}
],
"constraints": [
{
"name": "cost_constraint",
"constraint_type": "ge", // "ge", "le", "eq", etc.
"variables": ["budget", "ride_count"],
"parameters": {}, // solver-specific parameters
"expression": "budget >= ride_count * 25000", // human-readable
"label": "Cost constraint"
}
],
"soft_constraints": [
// Same structure as constraints, with an additional "weight" field
{ "weight": 5.0, "..." : "..." }
],
"objectives": [
{
"name": "maximize_rides",
"direction": "maximize", // "maximize" or "minimize"
"expression": "ride_count",
"variable": "ride_count", // primary variable for simple objectives
"weight": 1.0, // relative weight for multi-objective
"priority": 1, // priority ordering
"label": "Maximize the number of rides"
}
],
"what_if_scenarios": [
{
"name": "Add Roller Coaster",
"description": "What happens if we commit to a roller coaster?",
"additional_constraints": [
// Same structure as constraints; added temporarily via push/pop
]
}
]
}
```
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Theme Park Planning | Facility layout, capital budgeting, resource allocation |
| Space Colony Planning | Infrastructure sizing, capacity planning, disaster recovery modeling |
| Fantasy Sports Draft | Portfolio optimization, team composition, auction bidding strategies |
## Interactive Modes
All implementations support debugging flags:
```bash
# Verbose mode - show solver stats, variable details, and intermediate state
cargo run -- --scenario theme-park --verbose # Rust
./bin/solver --scenario theme-park --verbose # Go
python main.py --scenario theme-park --verbose # Python
# Step mode - pause at each phase with explanations
cargo run -- --scenario theme-park --step # Rust
./bin/solver --scenario theme-park --step # Go
python main.py --scenario theme-park --step # Python
# Combined mode
cargo run -- --scenario theme-park --verbose --step
```
Or use environment variables (Rust and Go only):
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python
cd python && python -m pytest
```
## Production Considerations
1. **Timeout handling**: Set `timeout_ms` in `SolverConfig` to bound solve time on large models
2. **Incremental solving**: Add constraints and re-solve rather than rebuilding from scratch
3. **Soft constraint weights**: Calibrate weights based on domain expertise; higher weights are harder to violate
4. **What-if batching**: Use push/pop for rapid scenario comparison without session recreation
---
# Solver What-If Pattern
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/solver-what-if
Demonstrates push/pop scoping, assumption-based solving, and what-if analysis using the nxusKit constraint solver. Each scenario defines a base problem and several what-if variants that temporarily modify the model to explore alternative outcomes.
> Explore alternative outcomes without rebuilding your model — push constraints, solve, compare, and pop back to baseline in one clean pattern.
**Scenarios**: `wedding` · `mars` · `recipe`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · Solver
- **Summary:** What-if scenario analysis with solver streaming
- **Scenario:** Stream solver results for interactive what-if scenario exploration
- **`tech_tags` in manifest:** `Solver, Streaming` — example id **`solver-what-if`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust, python, bash (paths under this directory).
- **Solver entitlement:** Requires a Pro or trial entitlement because it uses the Z3-backed solver. No LLM provider is required.
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **SolverSession Lifecycle** | Create, build model incrementally, solve, and close via the nxuskit SDK |
| **Push/Pop Scoping** | Save and restore model state for reversible experimentation |
| **What-If Analysis** | Add temporary constraints, solve, compare deltas, then restore |
| **Explanation / Unsat Core** | Retrieve constraint labels that cause infeasibility via `Explanation()` |
| **Delta Comparison** | Compare base vs. what-if variable assignments and objective values |
**Provider Compatibility**: Uses the nxusKit Z3-based constraint solver (no LLM provider required)
## Technologies
Solver, Streaming
## Pattern Overview
Real-world planning often involves asking "what if?" -- exploring how changes to assumptions affect the optimal solution. This pattern uses the solver's push/pop mechanism to efficiently evaluate multiple alternative scenarios without rebuilding the model from scratch.
The pipeline for each run:
1. **Load** a problem with base constraints, objective, and what-if scenario definitions
2. **Solve** the base problem to establish a baseline optimal solution
3. **For each what-if scenario**:
- **Push** the current solver state (saves all constraints and objective)
- **Add** temporary constraints that define the alternative scenario
- **Solve** under the modified model
- If UNSAT, **retrieve explanation** (unsat core labels)
- **Compare** the what-if result to the baseline (show variable deltas)
- **Pop** the solver state (restores the base model)
4. **Summarize** all scenarios in a comparison table
## Scenarios
Three themed scenarios are included under `scenarios/`:
- **Wedding Budget Planning** -- Allocate a $25,000 wedding budget across venue, catering, flowers, photography, music, and decor. What-if: splurge on a fancy venue, cut the DJ, or double the budget.
- **Mars Colony Resource Allocation** -- Design a Mars colony by balancing colonists against solar panels, water recyclers, greenhouses, habitats, and power storage under a cargo mass limit. What-if: require 50+ colonists, simulate a dust storm, or get extra cargo capacity.
- **Recipe Scaling** -- Scale a baking recipe by adjusting flour, sugar, eggs, butter, milk, and vanilla while maintaining proper ratios. What-if: limited eggs, go fully vegan (may be UNSAT), or bake for a party.
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/solver-what-if`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
cd bash && make build
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario wedding
cargo run -- --scenario mars --verbose
cargo run -- --scenario recipe --step
```
### Go
```bash
cd go
make build
./bin/solver-what-if --scenario wedding
./bin/solver-what-if --scenario mars --verbose
./bin/solver-what-if --scenario recipe --step
```
### Python
```bash
cd python
python3 main.py --scenario wedding
python3 main.py --scenario mars --verbose
python3 main.py --scenario recipe --step
```
### CLI/Bash
```bash
cd bash
make run
make run ARGS="--scenario mars"
make run ARGS="--scenario recipe --verbose"
```
## Push/Pop Concepts
The solver's push/pop mechanism works like a stack of model snapshots:
```
Base model: [variables + constraints + objective]
|
push() --> saves state
|
add_constraints([temporary constraints])
solve() --> result under modified model
|
pop() --> restores base model (temporary constraints removed)
```
Key properties:
- **Push** creates a new scope level; all subsequent additions are scoped
- **Pop** removes everything added since the last push
- Multiple push/pop levels can be nested
- The solver does not re-initialize -- it reuses learned information for efficiency
## Unsat Core Explanation
When a what-if scenario makes the model infeasible (UNSAT), the solver can report which constraints are responsible:
1. Enable explanation with `ProduceExplanation: true` in the solve config
2. After an UNSAT result, call `Explanation()` to retrieve the unsat core
3. The `unsat_core_labels` array contains the constraint labels that form a minimal conflicting set
This is particularly useful for understanding *why* a scenario is impossible (e.g., the vegan recipe scenario where eggs=0 conflicts with the eggs-per-flour ratio constraint).
## Scenario Data Format
Each scenario is a directory containing a `problem.json` file:
```jsonc
{
"name": "Scenario Name",
"description": "Human-readable description.",
"variables": [
{
"name": "venue_cost",
"var_type": "integer",
"domain": { "min": 5000, "max": 15000 },
"label": "Cost of the venue in dollars"
}
],
"constraints": [
{
"name": "budget_limit",
"constraint_type": "le",
"variables": ["venue_cost", "catering_cost"],
"parameters": { "budget": 25000 },
"expression": "venue_cost + catering_cost <= 25000",
"label": "Budget constraint"
}
],
"objectives": [
{
"name": "maximize_total_quality",
"direction": "maximize",
"expression": "venue_cost + catering_cost",
"variable": "venue_cost",
"weight": 1.0,
"label": "Maximize total quality"
}
],
"what_if_scenarios": [
{
"name": "fancy_venue",
"description": "What if we splurge on a fancy venue?",
"additional_constraints": [
{
"name": "fancy_venue_min",
"constraint_type": "ge",
"variables": ["venue_cost"],
"parameters": { "min_value": 12000 },
"expression": "venue_cost >= 12000",
"label": "Fancy venue minimum"
}
]
}
]
}
```
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Wedding Budget Planning | Event planning, capital budgeting, portfolio allocation |
| Mars Colony Planning | Infrastructure sizing, supply chain planning, disaster preparedness |
| Recipe Scaling | Manufacturing scaling, formulation optimization, process engineering |
## Interactive Modes
All implementations support debugging flags:
```bash
# Verbose mode - show solver stats and constraint details
cargo run -- --scenario wedding --verbose # Rust
./bin/solver-what-if --scenario wedding --verbose # Go
python3 main.py --scenario wedding --verbose # Python
make run ARGS="--scenario wedding --verbose" # CLI/Bash
# Step mode - pause at each phase with explanations
cargo run -- --scenario wedding --step # Rust
./bin/solver-what-if --scenario wedding --step # Go
python3 main.py --scenario wedding --step # Python
make run ARGS="--scenario wedding --step" # CLI/Bash
# Combined mode
cargo run -- --scenario wedding --verbose --step
```
Or use environment variables where supported:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python smoke
cd python && python3 main.py --help
# CLI/Bash
cd bash && make test
```
## Production Considerations
1. **Push/Pop depth**: Keep nesting shallow; deep push/pop stacks add solver overhead
2. **Explanation cost**: Producing unsat cores adds overhead; only enable when needed
3. **Constraint interaction**: What-if constraints are *added* to existing constraints via push, not *replaced*. Design base constraints to be compatible with what-if additions.
4. **Timeout handling**: Set `timeout_ms` in `SolverConfig` to bound solve time on large models
---
# Streaming
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/streaming
Stream tokens from a chat completion as they arrive
> Stream LLM responses token by token with a unified async interface that works across Claude, OpenAI, and Ollama without changing your code.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · LLM · Streaming
- **Summary:** Streaming chat completion with real-time output
- **Scenario:** Stream tokens from a chat completion as they arrive
- **`tech_tags` in manifest:** `LLM, Streaming` — example id **`streaming`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Real-time chat interface, live transcription display
## Technologies
LLM, Streaming
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/streaming`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/streaming
```
### Python
```bash
cd python
python main.py
```
---
# Structured Output (JSON Mode) Pattern
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/structured-output
Demonstrates extracting typed, validated structured data from LLM responses using JSON mode.
> Stop parsing free-form LLM text — get typed, validated JSON structs back every time, across every provider.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** JSON mode and structured output generation
- **Scenario:** Request and parse structured JSON responses from an LLM
- **`tech_tags` in manifest:** `LLM` — example id **`structured-output`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **JSON Mode Abstraction** | nxusKit handles provider-specific JSON mode implementations |
| **Type-Safe Responses** | Strong typing with serde (Rust) / json (Go) for reliability |
| **Provider-Agnostic Schemas** | Same schema works across OpenAI, Claude, and Ollama |
**Provider Compatibility**: Ollama (format parameter), OpenAI (response_format), Claude (via tool use)
## Pattern Overview
LLMs naturally produce unstructured text, but many applications need structured data. This pattern uses JSON mode to ensure valid JSON output, then parses and validates it into typed structures.
## Key Features
- JSON mode ensures valid JSON response
- Type-safe parsing into structs
- Validation of enumerated fields
- Helper functions for testing
## Real-World Application
Data extraction, form auto-fill, API response generation.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/structured-output`:
cd rust && cargo build
cd go && make build
```
## Log Classification Example
The example classifies log entries into structured categories:
```json
{
"severity": "error",
"category": "auth",
"summary": "Failed login attempt for admin user",
"actionable": true
}
```
### Valid Values
- **severity**: `info`, `warning`, `error`, `critical`
- **category**: `auth`, `network`, `system`, `application`
## Library usage
### Rust
```rust
use structured_output::{classify_log, LogClassification};
let classification = classify_log(&provider, "llama3", log_entry).await?;
println!("Severity: {}", classification.severity);
println!("Actionable: {}", classification.actionable);
```
### Go
```go
classification, err := ClassifyLog(ctx, provider, "llama3", logEntry)
fmt.Println("Severity:", classification.Severity)
fmt.Println("Actionable:", classification.Actionable)
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Prompt Engineering Tips
1. **Be explicit**: Specify the exact JSON format in the system prompt
2. **List valid values**: Enumerate allowed values for each field
3. **Provide examples**: Include example JSON in complex cases
4. **Validate output**: Always validate parsed JSON against your schema
## Production Considerations
1. **Retry on validation failure**: LLMs may occasionally produce invalid values
2. **Fallback handling**: Have a default category for edge cases
3. **Schema evolution**: Version your schemas for backward compatibility
4. **Rate limiting**: JSON mode may use more tokens due to formatting
---
# Timeout Config
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/timeout-config
Configure request timeouts and connection pool settings
> Take control of LLM request timing with per-phase timeout configuration that catches network failures fast without killing long-running streams.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Timeout configuration and connection management
- **Scenario:** Configure request timeouts and connection pool settings
- **`tech_tags` in manifest:** `LLM` — example id **`timeout-config`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Latency-sensitive services, SLA-bound AI endpoints
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/timeout-config`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/timeout-config
```
---
# Streaming with Token Budget Pattern
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/token-budget
Demonstrates cost control by enforcing token limits during streaming responses.
> Stop paying for tokens you don't need — enforce real-time streaming budgets and cancel LLM requests the moment your limit is reached.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Token budget management and cost estimation
- **Scenario:** Track and limit token usage across requests
- **`tech_tags` in manifest:** `LLM` — example id **`token-budget`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust, bash (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** CLI/Bash defaults to the `loopback` provider for credential-free smoke tests. Set cloud provider API keys or run **Ollama** locally when using live providers in the **Run** steps.
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **Unified Streaming** | Same streaming interface across all providers (Stream in Rust, channels in Go) |
| **Stream Cancellation** | Graceful cancellation supported by all provider implementations |
| **Token Tracking** | Normalized token usage in final chunk regardless of provider |
**Provider Compatibility**: Any provider supporting streaming (Claude, OpenAI, Ollama)
## Pattern Overview
When streaming LLM responses, you may want to stop generation early to control costs or enforce response length limits. This pattern monitors token usage during streaming and cancels the request when a budget is reached.
## Key Features
- Real-time token estimation during streaming
- Graceful stream cancellation when budget exceeded
- Returns partial content and budget status
- Works with any streaming-capable provider
## Real-World Application
Usage metering, per-user quota enforcement.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
| CLI/Bash | `bash/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/token-budget`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
cd bash && make build
```
## Token Estimation
Since exact token counts aren't available during streaming, we use a simple heuristic:
- ~4 characters per token (works well for English text)
- Adjust this ratio for other languages or specialized content
## Library usage
### Rust
```rust
use token_budget::stream_with_budget;
// Stream with a 100 token budget
let result = stream_with_budget(&provider, &request, 100).await?;
println!("Content: {}", result.content);
println!("Tokens used: {}", result.estimated_tokens);
if result.budget_reached {
println!("Budget limit reached - response truncated");
}
```
### Go
```go
// Stream with a 100 token budget
result, err := StreamWithBudget(ctx, provider, req, 100)
fmt.Println("Content:", result.Content)
fmt.Println("Tokens used:", result.EstimatedTokens)
if result.BudgetReached {
fmt.Println("Budget limit reached - response truncated")
}
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
### Python
```bash
cd python
python3 main.py
```
### CLI/Bash
```bash
cd bash
make run
TOKEN_BUDGET_MAX=40 make run ARGS="ollama"
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
make run ARGS="--verbose" # CLI/Bash
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
make run ARGS="--step" # CLI/Bash
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python smoke
cd python && python3 main.py --help
# CLI/Bash
cd bash && make test
```
## Production Considerations
1. **Calibrate token ratio**: Adjust the 4 chars/token estimate for your specific use case
2. **Buffer margin**: Set budget slightly below hard limits to account for estimation error
3. **User feedback**: Indicate when responses are truncated due to budget
4. **Combine with max_tokens**: Use both streaming budget and API max_tokens for defense in depth
---
# Vision
URL: https://docs.nxus.systems/v0.9.4/nxuskit/examples/patterns/vision
Send images alongside text prompts for multimodal analysis
> Send images alongside text to any LLM provider using one consistent API that handles encoding, formatting, and provider differences for you.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · LLM · Vision
- **Summary:** Vision and multimodal capabilities with images
- **Scenario:** Send images alongside text prompts for multimodal analysis
- **`tech_tags` in manifest:** `LLM, Vision` — example id **`vision`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust, bash (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys for live Claude/OpenAI calls, or run metadata-only CLI/Bash mode with `VISION_RUN_LIVE=0`. Ollama vision models can be selected when the local provider path is available.
## Real-World Application
Image captioning, visual QA, document understanding
## Technologies
LLM, Vision
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
| CLI/Bash | `bash/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/vision`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
cd bash && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/vision
```
### Python
```bash
cd python
python main.py
```
### CLI/Bash
```bash
cd bash
make run
VISION_RUN_LIVE=0 make run
make run ARGS="openai"
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python smoke
cd python && python3 main.py --help
# CLI/Bash
cd bash && make test
```
---
# Authentication
URL: https://docs.nxus.systems/v0.9.4/nxuskit/getting-started/authentication
## Overview
nxusKit supports multiple authentication methods depending on the provider.
This matrix shows which methods are available for each provider and how to
configure them.
## Provider Matrix
| Provider | Auth Required | API Key | OAuth | Env Variable | Dashboard |
|----------|:------------:|:-------:|:-----:|--------------|-----------|
| OpenAI / GPT | Yes | Yes | — | `OPENAI_API_KEY` | [platform.openai.com/api-keys](https://platform.openai.com/api-keys) |
| Anthropic / Claude | Yes | Yes | — | `ANTHROPIC_API_KEY` | [console.anthropic.com/settings/keys](https://console.anthropic.com/settings/keys) |
| xAI Grok | Yes | Yes | — | `XAI_API_KEY` | [console.x.ai](https://console.x.ai/) |
| Groq | Yes | Yes | — | `GROQ_API_KEY` | [console.groq.com/keys](https://console.groq.com/keys) |
| Mistral AI | Yes | Yes | — | `MISTRAL_API_KEY` | [console.mistral.ai/api-keys](https://console.mistral.ai/api-keys) |
| Fireworks AI | Yes | Yes | — | `FIREWORKS_API_KEY` | [fireworks.ai/account/api-keys](https://fireworks.ai/account/api-keys) |
| Together AI | Yes | Yes | — | `TOGETHER_API_KEY` | [api.together.ai/settings/api-keys](https://api.together.ai/settings/api-keys) |
| OpenRouter | Yes | Yes | — | `OPENROUTER_API_KEY` | [openrouter.ai/settings/keys](https://openrouter.ai/settings/keys) |
| Perplexity | Yes | Yes | — | `PERPLEXITY_API_KEY` | [perplexity.ai/settings/api](https://www.perplexity.ai/settings/api) |
| Ollama | No | — | — | `OLLAMA_HOST` | — |
| LM Studio | No | — | — | `LM_STUDIO_HOST` | — |
**Legend**: Yes = supported, — = not applicable/not yet available
## Authentication Methods
### API Key
The standard authentication method for cloud providers. Obtain a key from
the provider's dashboard, then configure via any of these methods:
**Environment variable** (recommended for development and CI/CD):
```bash
export OPENAI_API_KEY="sk-..."
```
**Credential store** (recommended for persistent local development):
```bash
nxuskit-cli provider set openai sk-...
```
This stores the key in the OS credential store (macOS Keychain, Windows
Credential Manager, or Linux secret-service). Falls back to a file-based
store with 0600 permissions if no system store is available.
**Explicit parameter** (for programmatic use):
```python
provider = Provider.create("openai", api_key="sk-...")
```
### OAuth (Infrastructure Ready)
OAuth authentication infrastructure is implemented in v0.9.1 but no current
providers require it. When a provider enables OAuth support, the flow will
be:
```bash
# Start OAuth login
nxuskit-cli provider login
# Check auth status
nxuskit-cli provider status
```
The OAuth flow uses:
- PKCE (SHA-256 code challenge) for security
- Localhost callback on an ephemeral port
- State/CSRF validation
- Automatic browser launch
### No Authentication
Local providers (Ollama, LM Studio) run on the local machine and do not
require authentication. The host env variable is optional and defaults to
`localhost` on the provider's default port.
## Credential Precedence
When multiple credential sources exist, the SDK uses this precedence order:
| Priority | Source | Example |
|----------|--------|---------|
| 1 (highest) | Explicit API parameter | `Provider.create("openai", api_key="sk-...")` |
| 2 | Environment variable | `OPENAI_API_KEY=sk-...` |
| 3 (lowest) | OS credential store | Via `nxuskit-cli provider set` |
## Checking Auth Status
View authentication status for all providers:
```bash
nxuskit-cli provider status
```
For a specific provider:
```bash
nxuskit-cli provider status openai
```
JSON output (for scripts):
```bash
nxuskit-cli provider status --json
```
Example output:
```
Provider Status Source Auth Methods
─────────────────────────────────────────────────────────────
openai Authenticated env api_key
claude Authenticated store api_key
xai Not authenticated — api_key
groq Not authenticated — api_key
ollama Not required — —
lm-studio Not required — —
```
## Managing Credentials
```bash
# Store a credential
nxuskit-cli provider set
# Remove a stored credential
nxuskit-cli provider remove
# View status
nxuskit-cli provider status [provider]
```
## Per-Language Configuration
### Rust
```rust
use nxuskit::{auth_status, auth_set_credential, auth_resolve};
// Check status
let status = auth_status("openai")?;
// Store credential
auth_set_credential("openai", "sk-...")?;
// Resolve credential (follows precedence chain)
let resolution = auth_resolve("openai", None)?;
```
### Go
```go
import "github.com/nxus-SYSTEMS/nxuskit-go"
// Check status
status, err := nxuskit.AuthStatus("openai")
// Store credential
err = nxuskit.AuthSetCredential("openai", "sk-...")
// Resolve credential
resolution, err := nxuskit.AuthResolve("openai", "")
```
### Python
```python
from nxuskit import auth_status, auth_set_credential, auth_resolve
# Check status
status = auth_status("openai")
# Store credential
auth_set_credential("openai", "sk-...")
# Resolve credential
resolution = auth_resolve("openai")
```
---
# First Call
URL: https://docs.nxus.systems/v0.9.4/nxuskit/getting-started/first-call
This guide assumes you have installed the SDK and configured at least one
provider credential. If you have not done that yet, start with
[Installation](/v0.9.4/nxuskit/getting-started/installation/) and
[Authentication](/v0.9.4/nxuskit/getting-started/authentication/).
## Fastest Path: CLI
Set a provider API key, then send a single chat request:
```bash
export OPENAI_API_KEY="sk-..."
nxuskit-cli chat \
--provider openai \
--model gpt-4o \
"Say hello from nxusKit in one sentence."
```
For structured shell workflows, use the Level 1 `call` command:
```bash
echo '{"provider":"openai","model":"gpt-4o","prompt":"Say hello from nxusKit."}' \
| nxuskit-cli call --input - --format json
```
## Rust
Use the Rust wrapper bundled with the SDK as a path dependency:
```toml
# Cargo.toml
[dependencies]
nxuskit = { path = "/absolute/path/to/nxuskit-sdk-{version}-{platform}/rust" }
```
```rust
use nxuskit::{ChatRequest, Message, NxuskitProvider, ProviderConfig};
fn main() -> Result<(), nxuskit::NxuskitError> {
let provider = NxuskitProvider::new(ProviderConfig {
provider_type: "openai".into(),
..Default::default()
})?;
let request = ChatRequest::new("gpt-4o")
.with_message(Message::user("Say hello from Rust."))
.with_max_tokens(100);
let response = provider.chat(request)?;
println!("{}", response.content);
Ok(())
}
```
## Go
Add the Go wrapper and alias the package as `nxuskit` in your import block:
```bash
go get github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go
```
```go
package main
import (
"context"
"fmt"
"os"
nxuskit "github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go"
)
func main() {
provider, err := nxuskit.NewOpenAIProvider(
nxuskit.WithAPIKey(os.Getenv("OPENAI_API_KEY")),
)
if err != nil {
panic(err)
}
req := nxuskit.ChatRequest{
Model: "gpt-4o",
Messages: []nxuskit.Message{
{Role: nxuskit.RoleUser, Content: "Say hello from Go."},
},
}
resp, err := provider.Chat(context.Background(), req)
if err != nil {
panic(err)
}
fmt.Println(resp.Content)
}
```
## Python
Install the Python wrapper, then create a provider and call it:
```bash
pip install nxuskit-py
```
```python
from nxuskit import Provider
provider = Provider.create("openai")
response = provider.chat(
model="gpt-4o",
messages=[{"role": "user", "content": "Say hello from Python."}],
max_tokens=100,
)
print(response.content)
```
## C
The SDK bundle includes `include/nxuskit.h` and platform libraries under
`lib/`. Compile against those files and set the provider API key in the
environment:
```bash
export OPENAI_API_KEY="sk-..."
cc -I "$NXUSKIT_SDK_DIR/include" \
-o basic_chat basic_chat.c \
-L "$NXUSKIT_SDK_DIR/lib" \
-lnxuskit \
-Wl,-rpath,"$NXUSKIT_SDK_DIR/lib"
```
Use the [C ABI Reference](/v0.9.4/nxuskit/reference/api-reference/) for function,
ownership, and error-handling details.
## Local Providers
Local providers do not require API keys:
```bash
# Ollama default
export OLLAMA_HOST="http://localhost:11434"
# LM Studio default
export LMSTUDIO_HOST="http://localhost:1234/v1"
```
Use [Local LLM Providers](/v0.9.4/nxuskit/reference/providers/local-llms/) for model
setup and provider-specific options.
## Next Steps
| Goal | Read |
|------|------|
| Configure credentials | [Authentication](/v0.9.4/nxuskit/getting-started/authentication/) |
| Browse runnable projects | [Examples](/v0.9.4/nxuskit/examples/) |
| Stream responses | [Streaming](/v0.9.4/nxuskit/guides/streaming/) |
| Choose a provider | [Provider Model](/v0.9.4/nxuskit/concepts/provider-model/) |
| Use CLI JSON contracts | [CLI Input Format Reference](/v0.9.4/nxuskit/reference/cli-reference/) |
| Integrate through native boundaries | [C ABI Reference](/v0.9.4/nxuskit/reference/api-reference/) |
---
# Installation
URL: https://docs.nxus.systems/v0.9.4/nxuskit/getting-started/installation
This guide walks you through downloading, installing, and using the nxuskit SDK
to call LLM providers from Rust, Go, Python, or the C ABI.
## Prerequisites
- [GitHub CLI](https://cli.github.com/) (`gh`) installed
- Optional: authenticate with `gh auth login` for CI reliability, higher API
limits, or entitlement-gated/private assets
## 1. Download and Install the SDK
The examples below download Community Edition from the public
`nxus-SYSTEMS/nxusKit` release. Current release asset names use `oss` for the
Community Edition archive segment. Pro users can replace `oss` with `pro` in the
asset patterns and extracted directory names after activating or receiving a Pro
entitlement.
### macOS (Apple Silicon)
```bash
# Download, extract, and remove macOS quarantine in one go
gh release download --repo nxus-SYSTEMS/nxusKit \
--pattern "nxuskit-sdk-*-oss-macos-arm64.tar.gz" \
--pattern "nxuskit-sdk-*-oss-macos-arm64.tar.gz.sha256"
shasum -a 256 -c nxuskit-sdk-*-oss-macos-arm64.tar.gz.sha256
tar xzf nxuskit-sdk-*-oss-macos-arm64.tar.gz
xattr -dr com.apple.quarantine nxuskit-sdk-*/
```
The `xattr` step removes the Gatekeeper quarantine flag that macOS applies to
downloaded files. Without it you'll get "can't be opened because Apple cannot
check it for malicious software" when loading the dylib.
### Linux (x86_64)
```bash
gh release download --repo nxus-SYSTEMS/nxusKit \
--pattern "nxuskit-sdk-*-oss-linux-x86_64.tar.gz" \
--pattern "nxuskit-sdk-*-oss-linux-x86_64.tar.gz.sha256"
sha256sum -c nxuskit-sdk-*-oss-linux-x86_64.tar.gz.sha256
tar xzf nxuskit-sdk-*-oss-linux-x86_64.tar.gz
```
### Windows (x86_64)
```powershell
gh release download --repo nxus-SYSTEMS/nxusKit `
--pattern "nxuskit-sdk-*-oss-windows-x86_64.zip" `
--pattern "nxuskit-sdk-*-oss-windows-x86_64.zip.sha256"
# Extract
Expand-Archive nxuskit-sdk-*-oss-windows-x86_64.zip -DestinationPath .
```
### Set SDK Path
After extracting, set the SDK path. **Use an absolute path** — relative paths
can fail because `cargo` and other tools may change the working directory during
builds.
```bash
# Get the absolute path to the extracted SDK directory
export NXUSKIT_SDK_DIR="$(cd nxuskit-sdk-*/ && pwd)"
echo "NXUSKIT_SDK_DIR=${NXUSKIT_SDK_DIR}"
```
To persist across sessions, add to your shell profile (`~/.bashrc`, `~/.zshrc`,
etc.):
```bash
export NXUSKIT_SDK_DIR="/absolute/path/to/nxuskit-sdk-0.9.4-oss-macos-arm64"
```
For CI systems, see [Download via PAT](#download-via-pat) below.
### CLI shell completions (optional)
The bundle includes `nxuskit-cli`. Generate shell completions with:
```bash
nxuskit-cli completions bash > /usr/local/etc/bash_completion.d/nxuskit-cli
nxuskit-cli completions zsh > ~/.zfunc/_nxuskit-cli # add ~/.zfunc to $fpath
nxuskit-cli completions fish > ~/.config/fish/completions/nxuskit-cli.fish
```
Supported shells for `completions` in v0.9.4: **bash**, **zsh**, **fish**.
PowerShell completion is **not generated** in v0.9.4 (the `completions` command
accepts only those three shell names). JSON schemas referenced by the CLI ship
under the bundle's `include/` (the C header) and `conformance/` (packet/pipeline
schemas) directories; see [SDK Bundle Contents](#2-sdk-bundle-contents) above.
## 2. SDK Bundle Contents
```
nxuskit-sdk-{version}-{edition}-{platform}/
├── include/
│ └── nxuskit.h # C header — all API declarations
├── lib/
│ ├── libnxuskit.so # Shared library (Linux)
│ │ libnxuskit.dylib # Shared library (macOS)
│ │ nxuskit.dll # Shared library (Windows)
│ ├── libnxuskit.a # Static library (Linux/macOS)
│ │ nxuskit.lib # Static library (Windows)
│ └── nxuskit.dll.lib # Import library (Windows only)
├── rust/ # nxuskit Rust SDK wrapper (use as path dependency)
├── docs/ # This documentation
└── examples/ # Working examples in C, Rust, Go, Python
```
## 3. First Example — C
Set your provider API key, then compile and run:
```bash
export OPENAI_API_KEY="sk-..." # or ANTHROPIC_API_KEY, etc.
cd nxuskit-sdk-*/examples/c
make basic_chat
./bin/basic_chat
```
See [nxusKit examples](/v0.9.4/nxuskit/examples/) for the source.
## 4. First Example — Go
```bash
export OPENAI_API_KEY="sk-..."
cd nxuskit-sdk-*/examples/go
go run basic_chat.go
```
See [nxusKit examples](/v0.9.4/nxuskit/examples/) for the source.
## 5. First Example — Rust
The SDK bundles `nxuskit`, a safe Rust wrapper. Add it as a path dependency
in your `Cargo.toml` using the **absolute path** to the SDK's `rust/` directory:
```toml
# Cargo.toml
[dependencies]
nxuskit = { path = "/Users/you/nxuskit-sdk-0.9.4-oss-macos-arm64/rust" }
```
Then set your environment and run:
```bash
# NXUSKIT_SDK_DIR tells the wrapper where to find libnxuskit at runtime.
# Must be an absolute path (relative paths are unreliable across tools).
export NXUSKIT_SDK_DIR="/Users/you/nxuskit-sdk-0.9.4-oss-macos-arm64"
export OPENAI_API_KEY="sk-..."
cargo run
```
```rust
use nxuskit::{ChatRequest, Message, NxuskitProvider, ProviderConfig};
fn main() -> Result<(), nxuskit::NxuskitError> {
let provider = NxuskitProvider::new(ProviderConfig {
provider_type: "openai".into(),
..Default::default()
})?;
let request = ChatRequest::new("gpt-4o")
.with_message(Message::user("Hello from Rust!"))
.with_max_tokens(100);
let response = provider.chat(request)?;
println!("{}", response.content);
Ok(())
}
```
**Path troubleshooting:** If you see `LibraryNotFound`, verify:
1. `NXUSKIT_SDK_DIR` is set and is an absolute path (check with `echo $NXUSKIT_SDK_DIR`)
2. The `lib/` subdirectory exists: `ls $NXUSKIT_SDK_DIR/lib/`
3. On macOS: quarantine was removed (see Step 1 above)
See [nxusKit examples](/v0.9.4/nxuskit/examples/) for a runnable project, and
[Rust SDK API documentation](/v0.9.4/nxuskit/reference/api/) for the full nxuskit API documentation.
## 6. First Example — Python
```bash
pip install nxuskit-py
export OPENAI_API_KEY="sk-..."
python examples/python/basic_chat.py
```
See [nxusKit examples](/v0.9.4/nxuskit/examples/) for the source.
## Core Concepts
### JSON-in / JSON-out
All data crosses the FFI boundary as JSON strings. You send a JSON config to
create a provider, send a JSON request for chat, and receive a JSON response.
### Provider Lifecycle
```
create_provider(config_json) → provider handle
↓
chat(provider, request_json) → response handle → response_json(response) → JSON
↓
free_response(response)
free_provider(provider)
```
### Streaming
```
chat_stream(provider, request_json, on_chunk, on_done, user_data) → stream handle
↓ (callbacks fire from background thread)
on_chunk(chunk_json, user_data) ← called per chunk
on_done(final_json, user_data) ← called once at end
↓
free_stream(stream)
```
### Thread Safety
- All `nxuskit_*` functions are thread-safe
- Provider handles can be shared across threads
- Error messages are thread-local (`nxuskit_last_error()`)
### Supported Providers
| Provider | Config `provider_type` | Required Env Var |
|----------|----------------------|------------------|
| OpenAI | `openai` | `OPENAI_API_KEY` |
| Anthropic Claude | `claude` | `ANTHROPIC_API_KEY` |
| Ollama | `ollama` | `OLLAMA_HOST` (optional) |
| LM Studio | `lmstudio` | — |
| xAI Grok | `xai` | `XAI_API_KEY` |
| Groq | `groq` | `GROQ_API_KEY` |
| Fireworks | `fireworks` | `FIREWORKS_API_KEY` |
| Together | `together` | `TOGETHER_API_KEY` |
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` |
| Perplexity | `perplexity` | `PERPLEXITY_API_KEY` |
| Mistral | `mistral` | `MISTRAL_API_KEY` |
| CLIPS | `clips` | — |
| MCP | `mcp` | — |
| Mock (testing) | `mock` | — |
| Loopback (testing) | `loopback` | — |
`xai` is xAI Grok and uses `XAI_API_KEY`. `groq` is Groq, Inc.'s provider and
uses `GROQ_API_KEY`. There is no `grok` provider alias.
### CLIPS Quick Start
CLIPS runs in-process (no API key needed). Create a provider with
`provider_type: "clips"` and `model` pointing to your rules directory. Send
facts as JSON in the user message:
```c
const char *input = "{\"facts\": [{\"template\": \"sensor\", \"values\": {\"name\": \"temp\", \"value\": 150}}]}";
// ... create provider, build request with input as user message, call nxuskit_chat()
```
The user message must conform to the `ClipsInput` schema — see the
[Rule Authoring Guide](/v0.9.4/nxuskit/guides/clips-rule-authoring/#clipsinput-json-reference) for the full
field reference. CLIPS also provides a session API for direct engine access; see
the [API Reference](/v0.9.4/nxuskit/reference/api-reference/#clips-session-api).
## Linking Reference
### GCC / Clang (dynamic)
```bash
cc -I sdk/include -o myapp myapp.c -L sdk/lib -lnxuskit -Wl,-rpath,sdk/lib
```
### GCC / Clang (static)
```bash
cc -I sdk/include -o myapp myapp.c sdk/lib/libnxuskit.a -lpthread -ldl -lm
```
### MSVC (dynamic — recommended)
```
cl /I sdk\include myapp.c /link sdk\lib\nxuskit.dll.lib
```
### MSVC (static)
```
cl /I sdk\include myapp.c /link sdk\lib\nxuskit.lib ucrt.lib userenv.lib ntdll.lib ws2_32.lib bcrypt.lib advapi32.lib
```
### CGo
```go
// #cgo CFLAGS: -I${SRCDIR}/sdk/include
// #cgo linux LDFLAGS: -L${SRCDIR}/sdk/lib -lnxuskit -Wl,-rpath,${SRCDIR}/sdk/lib
// #cgo darwin LDFLAGS: -L${SRCDIR}/sdk/lib -lnxuskit -Wl,-rpath,${SRCDIR}/sdk/lib
// #cgo windows LDFLAGS: -L${SRCDIR}/sdk/lib -lnxuskit
// #include "nxuskit.h"
import "C"
```
### Python (cffi)
```python
from cffi import FFI
ffi = FFI()
ffi.cdef(open("sdk/include/nxuskit.h").read())
lib = ffi.dlopen("sdk/lib/libnxuskit.so") # or .dylib / .dll
```
## Download via PAT
For CI systems that can't use `gh`, or that need authenticated GitHub API
access:
1. Create a fine-grained PAT at https://github.com/settings/personal-access-tokens
- **Repository access**: Select `nxus-SYSTEMS/nxusKit`
- **Permissions**: Contents → Read-only
2. Use the token:
```bash
export GH_TOKEN="github_pat_..."
# List available SDK releases
curl -H "Authorization: Bearer $GH_TOKEN" \
"https://api.github.com/repos/nxus-SYSTEMS/nxusKit/releases?per_page=5" \
| jq '.[].tag_name'
# Download a specific asset
curl -L -H "Authorization: Bearer $GH_TOKEN" \
-H "Accept: application/octet-stream" \
"https://api.github.com/repos/nxus-SYSTEMS/nxusKit/releases/assets/{ASSET_ID}" \
-o nxuskit-sdk.tar.gz
```
## Next Steps
- [API Reference](/v0.9.4/nxuskit/reference/api-reference/) — full C ABI documentation
- [Provider Reference](/v0.9.4/nxuskit/reference/providers/cloud-llms/) — provider-specific configuration
- [Rule Authoring Guide](/v0.9.4/nxuskit/guides/clips-rule-authoring/) — writing, testing, and deploying custom CLIPS rules
- [nxusKit examples](/v0.9.4/nxuskit/examples/) — working code for SDK languages and C ABI workflows
---
# CLIPS Rule Authoring Guide
URL: https://docs.nxus.systems/v0.9.4/nxuskit/guides/clips-rule-authoring
This guide explains how to write, test, and deploy custom CLIPS rules with the nxusKit SDK.
## CLIPS Rule Syntax
nxusKit uses CLIPS 6.4, a forward-chaining inference engine. Rules follow the pattern:
```clips
(defrule rule-name
"Documentation string"
;; LHS: conditions (pattern matching)
(template-name (slot-name ?variable))
(test (< ?variable 100))
=>
;; RHS: actions (assertions, side effects)
(assert (alert
(alert-type "threshold_exceeded")
(severity "warning")
(message (str-cat "Value " ?variable " is out of range"))
(recommendation "Check your input data")
(entity-id ?id)
(rule-name "rule-name")
(module-name "data-qc"))))
```
## Defining Templates
Templates define the fact schemas your rules operate on. Define them in shared template files loaded before any module rules:
```clips
;;; shared/000-core.clp — Core templates
(deftemplate input-data
"A single data record to evaluate"
(slot record-id (type INTEGER))
(slot value (type FLOAT))
(slot category (type STRING))
(slot confidence (type FLOAT) (range 0.0 1.0)))
(deftemplate threshold-config
"Configurable thresholds for QC checks"
(slot value-min (type FLOAT))
(slot value-max (type FLOAT))
(slot confidence-min (type FLOAT) (default 0.5)))
(deftemplate alert
"Output: a raised alert from rule inference"
(slot alert-type (type STRING))
(slot severity (type STRING)) ;; "critical", "high", "warning", "info"
(slot message (type STRING))
(slot recommendation (type STRING))
(slot entity-id (type INTEGER))
(slot rule-name (type STRING))
(slot module-name (type STRING)))
```
## Modules
CLIPS modules provide namespace isolation for rules. Each module groups related rules:
```clips
;;; In data-qc/bounds-check.clp
(defmodule data-qc (export ?ALL))
(defrule bounds-check
"Flag records outside configured bounds"
(threshold-config (value-min ?vmin) (value-max ?vmax))
(input-data (record-id ?rid) (value ?v&:(or (< ?v ?vmin) (> ?v ?vmax))))
=>
(assert (alert
(alert-type "out_of_bounds")
(severity "high")
(message (str-cat "Record " ?rid " value " ?v " outside [" ?vmin "-" ?vmax "]"))
(recommendation "Verify input data or adjust thresholds")
(entity-id ?rid)
(rule-name "bounds-check")
(module-name "data-qc"))))
```
## Directory Structure
Organize rules with shared templates loaded first, then per-module rule files:
```
rules/
shared/ # Shared templates (loaded first, alphabetically)
000-core.clp # input-data, threshold-config, alert
010-domain.clp # Additional domain-specific templates
data-qc/ # Data quality checks
bounds-check.clp
confidence-check.clp
classification/ # Classification rules
category-classifier.clp
custom/ # User-defined rules
my-custom-check.clp
```
## CLIPS Integration Paths
nxusKit provides two ways to use CLIPS:
- **Provider chat** — CLIPS as a standard chat provider. Send `ClipsInput` JSON
as the user message; receive `ClipsOutput` JSON in the response content.
Best for request/response workflows and cross-language portability.
- **Session API** — Direct engine access via `ClipsSession` (Rust, Go, Python)
or the C ABI (`nxuskit_clips_session_*`). Best for interactive, multi-step
rule authoring, debugging, and fine-grained fact manipulation.
This guide focuses on the **provider chat** path. For the session API, see the
[API Reference](/v0.9.4/nxuskit/reference/api-reference/#clips-session-api).
## ClipsInput JSON Reference
The user message JSON must conform to the `ClipsInput` schema. Unknown fields
are rejected (the engine uses strict deserialization).
```json
{
"facts": [
{"template": "sensor", "values": {"name": "temp-1", "value": 150}}
],
"templates": [
{"name": "alert", "slots": [{"name": "type", "type": "STRING"}, {"name": "severity", "type": "STRING"}]}
],
"rules": [
{"name": "high-temp", "source": "(defrule high-temp (sensor (value ?v&:(> ?v 100))) => (assert (alert (type \"over-threshold\") (severity \"high\"))))"}
],
"config": {
"max_rules": 1000,
"include_trace": true,
"derived_only_new": true
},
"focus": ["data-qc"],
"globals": {"*threshold*": 100}
}
```
All fields are optional. The minimal valid input is `{}` (empty object).
| Field | Type | Description |
|-------|------|-------------|
| `facts` | array of `{template, values}` | Facts to assert before running inference |
| `templates` | array of `{name, slots}` | Templates to create (if not in rule base) |
| `rules` | array of `{name, source}` or `{name, conditions, actions}` | Rules to create programmatically |
| `config` | object | Request-level overrides (see below) |
| `focus` | array of strings | Module focus stack (controls which rules fire) |
| `globals` | object | Global variable values to set |
| `command` | string | Special command: `"reset"`, `"clear"`, `"retract"` |
| `modules` | array of `{name, doc, imports}` | Modules to create |
| `policy_id` | string | Cache key for session reuse |
**Config fields:**
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `max_rules` | integer | -1 (unlimited) | Maximum rules to fire |
| `include_trace` | boolean | false | Include rule firing trace in output |
| `derived_only_new` | boolean | false | Only return newly derived facts |
| `output_templates` | array of strings | all | Only return facts matching these templates |
## Rule Loading
nxusKit's CLIPS provider loads rules through the `ClipsInput` configuration. Rules can be loaded from:
1. **Text strings** — CLIPS source passed directly via `rules_text`
2. **File paths** — `.clp` files loaded at runtime via `rules` array
3. **Binary images** — Pre-compiled `.bin` files via `binary_rules`
### Loading Order
1. Shared templates are loaded first (alphabetically by filename)
2. Module rules are loaded next, in the order specified by the `focus` configuration
3. User override rules are loaded last (taking precedence)
### Rust Example
```rust
use nxuskit::{AsyncProvider, ChatRequest, Message, NxuskitProvider, ProviderConfig};
let config = ProviderConfig {
provider_type: "clips".into(),
model: Some("/path/to/rules".into()),
..Default::default()
};
let provider = NxuskitProvider::new(config)?;
let request = ChatRequest::new("clips")
.with_message(Message::user(r#"{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 150.0}}]}"#))
.with_provider_options(serde_json::json!({
"focus": ["data-qc"],
"derived_only_new": true
}));
let response = provider.chat(request).await?;
println!("Alerts: {}", response.content);
```
### Go Example
```go
import "github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go"
config := nxuskit-go.ProviderConfig{
ProviderType: "clips",
Model: strPtr("/path/to/rules"),
}
provider, _ := nxuskit-go.NewProvider(config)
request := nxuskit-go.NewChatRequest("clips").
AddMessage(nxuskit-go.UserMessage(`{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 150.0}}]}`))
request.ProviderOptions = map[string]interface{}{
"focus": []string{"data-qc"},
"derived_only_new": true,
}
response, _ := provider.Chat(ctx, request)
fmt.Println("Alerts:", response.Content)
```
### Python Example
```python
from nxuskit-py import create_provider, Message
provider = create_provider("clips", model="/path/to/rules")
response = provider.chat(
model="clips",
messages=[Message.user('{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 150.0}}]}')],
provider_options={
"focus": ["data-qc"],
"derived_only_new": True,
},
)
print("Alerts:", response.content)
```
## Writing Custom Rules
### 1. Create a Rule File
Place your `.clp` file in the appropriate module directory:
```
/path/to/my-rules/data-qc/my-custom-check.clp
```
### 2. Reference Shared Templates
Do NOT redefine templates. Use templates from the shared `shared/*.clp` files:
```clips
;;; my-custom-check.clp
;;; Custom confidence check for strict environments
(defrule strict-confidence-check
"Flag records with confidence below 0.8"
(input-data (record-id ?rid) (confidence ?c&:(< ?c 0.8)))
=>
(assert (alert
(alert-type "low_confidence")
(severity "warning")
(message (str-cat "Record " ?rid " confidence " ?c " below threshold 0.8"))
(recommendation "Review data source quality")
(entity-id ?rid)
(rule-name "strict-confidence-check")
(module-name "data-qc"))))
```
### 3. Use Configurable Thresholds
Reference the `threshold-config` fact instead of hard-coding values:
```clips
(defrule configurable-bounds-check
"Flag records outside configured bounds"
(threshold-config (value-min ?vmin) (value-max ?vmax))
(input-data (record-id ?rid) (value ?v&:(or (< ?v ?vmin) (> ?v ?vmax))))
=>
(assert (alert
(alert-type "value_out_of_bounds")
(severity "high")
(message (str-cat "Record " ?rid " value " ?v " outside [" ?vmin "-" ?vmax "]"))
(recommendation "Check data or adjust threshold configuration")
(entity-id ?rid)
(rule-name "configurable-bounds-check")
(module-name "data-qc"))))
```
### 4. Naming Conventions
- **File names**: `NNN-descriptive-name.clp` (NNN = numeric prefix for load order)
- **Rule names**: `kebab-case`, descriptive of what is being checked
- **Alert types**: `snake_case`, machine-readable identifiers
- **Module names**: `kebab-case`, matching the directory name
## Testing Custom Rules
### Rust
```rust
use nxuskit::{AsyncProvider, ChatRequest, Message, MockProvider};
// Unit test with MockProvider (no SDK binary required)
#[tokio::test]
async fn test_with_mock() {
let provider = MockProvider::new(r#"{"alerts": [{"type": "low_confidence"}]}"#);
let request = ChatRequest::new("clips")
.with_message(Message::user("test input"));
let response = provider.chat(request).await.unwrap();
assert!(response.content.contains("low_confidence"));
}
// Integration test with real CLIPS engine (requires SDK binary)
#[tokio::test]
#[ignore = "requires libnxuskit runtime"]
async fn test_with_clips_engine() {
use nxuskit::{NxuskitProvider, ProviderConfig};
let config = ProviderConfig {
provider_type: "clips".into(),
model: Some("tests/rules".into()),
..Default::default()
};
let provider = NxuskitProvider::new(config).unwrap();
let request = ChatRequest::new("clips")
.with_message(Message::user(r#"{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 999.0}}]}"#));
let response = provider.chat(request).await.unwrap();
assert!(response.content.contains("out_of_bounds"));
}
```
### Go
```go
func TestRulesWithMock(t *testing.T) {
provider := nxuskit-go.NewMockProvider(
nxuskit-go.WithResponse(`{"alerts": [{"type": "low_confidence"}]}`),
)
req := nxuskit-go.NewChatRequest("clips").
AddMessage(nxuskit-go.UserMessage("test input"))
resp, err := provider.Chat(context.Background(), req)
require.NoError(t, err)
assert.Contains(t, resp.Content, "low_confidence")
}
```
### Python
```python
import pytest
from nxuskit-py import create_provider, Message
def test_rules_with_mock():
provider = create_provider("mock", responses=["low_confidence alert fired"])
response = provider.chat(
model="clips",
messages=[Message.user("test input")],
)
assert "low_confidence" in response.content
```
## Debugging Rules
### Enable Tracing
Set the `RUST_LOG` environment variable when using the Rust SDK:
```bash
RUST_LOG=nxuskit=debug cargo test -- --nocapture
```
This shows:
- Which rule files are loaded
- Module loading order and file counts
- Warnings for syntax errors
### Inspect CLIPS Facts
Access the CLIPS session API directly (Rust SDK):
```rust
use nxuskit::ClipsSession;
let session = ClipsSession::create()?;
session.load_string("(deftemplate input-data (slot record-id (type INTEGER)) (slot value (type FLOAT)))")?;
session.load_string("(deftemplate alert (slot alert-type (type STRING)) (slot severity (type STRING)))")?;
session.load_string(r#"(defrule check (input-data (record-id ?rid) (value ?v&:(> ?v 100.0))) =>
(assert (alert (alert-type "over-threshold") (severity "high"))))"#)?;
session.reset()?;
session.assert_string(r#"(input-data (record-id 1) (value 150.0))"#)?;
session.run(-1)?;
// List facts by template
let facts_json = session.facts_by_template("alert")?;
println!("Alert facts: {}", facts_json);
// Drop destroys the session automatically
```
### Step Limit Debugging
If inference hits the step limit, check for rule cycles. Common causes:
- Rules that assert facts matching their own LHS (infinite loop)
- Missing `not` patterns allowing rules to fire repeatedly
- Very large fact sets with cross-product patterns
Increase the step limit if needed:
```rust
session.run(500000)?; // Pass -1 to run until agenda exhausted
```
## Best Practices
1. **Keep rules simple** — One check per rule. Complex logic should be split across multiple rules.
2. **Use configurable thresholds** — Reference threshold facts instead of hard-coding values.
3. **Document every rule** — Use the CLIPS documentation string for a brief description.
4. **Test in isolation** — Load only shared templates and the single rule file under test.
5. **Use meaningful names** — Rule names should describe what is checked, not how.
6. **Set appropriate salience** — Use `(declare (salience N))` to control firing order when needed.
---
# CLIPS Excluded Capabilities & Workarounds
URL: https://docs.nxus.systems/v0.9.4/nxuskit/guides/clips-workarounds
Four CLIPS capabilities are intentionally excluded from the Session API.
This document explains why and provides working alternatives.
## 1. User-Defined Functions (UDFs)
**What it is:** CLIPS allows registering C functions callable from rule RHS actions
(`(my-custom-fn ?arg)`).
**Why excluded:** UDFs require raw C function pointers — exposing this through the
session-based FFI would bypass safety guarantees and create ABI fragility.
**Workaround:** Use `nxuskit_clips_eval()` to call built-in CLIPS functions, or
encode custom logic as rules:
```c
// Instead of a UDF that computes weighted score:
// (my-weighted-score ?base ?multiplier)
// Use a rule that computes and asserts the result:
nxuskit_clips_session_load_string(s,
"(defrule compute-weighted-score"
" (input (base ?b) (multiplier ?m))"
" =>"
" (assert (result (score (* ?b ?m)))))");
```
For complex custom functions, pre-compute values in your host language and assert
them as facts:
```c
// Compute in C, assert as fact
double score = my_complex_calculation(base, mult);
char buf[256];
snprintf(buf, sizeof(buf), "(result (score %f))", score);
nxuskit_clips_fact_assert_string(s, buf);
```
## 2. I/O Routers
**What it is:** CLIPS uses I/O routers to redirect `printout`, `read`, and other
I/O operations to custom handlers.
**Why excluded:** Router registration requires persistent C callbacks with
environment-specific state — incompatible with the session handle model.
**Workaround:** Use dribble logging to capture output:
```c
// Capture all CLIPS output to a file
nxuskit_clips_dribble_on(s, "/tmp/clips-output.log");
nxuskit_clips_session_run(s, -1);
nxuskit_clips_dribble_off(s);
// Read /tmp/clips-output.log for captured output
```
For structured output, use facts instead of `printout`:
```c
// Instead of: (printout t "Result: " ?value crlf)
// Use: (assert (output (message (str-cat "Result: " ?value))))
// Then query output facts:
char *outputs = nxuskit_clips_facts_by_template(s, "output");
// Parse JSON array of output facts
nxuskit_free_string(outputs);
```
## 3. Periodic Functions
**What it is:** CLIPS supports registering functions that execute between rule
firings (e.g., for progress callbacks or heartbeat checks).
**Why excluded:** Requires raw function pointers called from within the CLIPS
engine loop — cannot be safely exposed through FFI session handles.
**Workaround:** Use batch `run()` with a step limit and poll between batches:
```c
// Instead of a periodic callback, run in controlled batches
int64_t total_fired = 0;
while (true) {
int64_t fired = nxuskit_clips_session_run(s, 100); // 100 rules per batch
if (fired <= 0) break;
total_fired += fired;
// Your "periodic" logic here:
printf("Progress: %lld rules fired\n", total_fired);
// Check if we should halt
if (should_stop()) {
nxuskit_clips_session_halt(s);
break;
}
}
```
For thread-safe cancellation from another thread:
```c
// Thread 1: run inference
int64_t fired = nxuskit_clips_session_run(s, -1);
// Thread 2: signal halt after timeout
sleep(5);
nxuskit_clips_session_halt(s); // Thread-safe
```
## 4. External Addresses
**What it is:** CLIPS external addresses allow storing opaque C pointers as slot
values, enabling rules to reference host-language objects.
**Why excluded:** External address values are raw `void*` pointers — they cannot
be safely serialized through JSON and would create dangling pointer risks across
session boundaries.
**Workaround:** Use string or integer keys as indirect references:
```c
// Instead of storing a pointer to a connection object:
// (connection (handle ))
// Store an integer key and maintain a lookup table in your host code:
nxuskit_clips_session_load_string(s,
"(deftemplate connection (slot handle (type INTEGER)) (slot status (type SYMBOL)))");
// In C: maintain a mapping
int handle_id = register_connection(conn); // Your lookup table
char buf[128];
snprintf(buf, sizeof(buf), "(connection (handle %d) (status active))", handle_id);
nxuskit_clips_fact_assert_string(s, buf);
// When a rule fires referencing the handle, look up the real object:
// (defrule process-connection
// (connection (handle ?h) (status active))
// =>
// (assert (connection-result (handle ?h) (processed TRUE))))
```
## Summary
| Capability | Status | Workaround Pattern |
|------------|--------|-------------------|
| User-Defined Functions | Excluded | Encode as rules or pre-compute in host language |
| I/O Routers | Excluded | Dribble logging or output facts |
| Periodic Functions | Excluded | Batch `run()` with step limit + polling |
| External Addresses | Excluded | Integer/string keys with host-side lookup table |
All four exclusions are by design — they involve raw C pointers or callbacks that
cannot be safely exposed through the session-handle FFI boundary. The workarounds
provide equivalent functionality using the session API's safe data exchange patterns.
---
# Streaming
URL: https://docs.nxus.systems/v0.9.4/nxuskit/guides/streaming
## Overview
Streaming lets your application receive partial model output as it is produced.
Use it for chat UIs, long-running responses, progress reporting, and command-line
tools that should show output immediately instead of waiting for the final
message.
Most LLM providers support token-by-token streaming. Deterministic providers
such as CLIPS and Z3 may emit a single result chunk or a small number of status
updates, depending on the operation.
## When to Use Streaming
| Use streaming when | Use a regular call when |
|--------------------|-------------------------|
| Users should see output immediately | You need one complete JSON response |
| Responses may be long | Responses are small and predictable |
| You want progress or partial results | You need simpler error handling |
| You are building CLI or chat interfaces | You are running batch jobs |
## Rust
```rust
use futures::StreamExt;
use nxuskit::{completion_stream, NxuskitError};
#[tokio::main]
async fn main() -> Result<(), NxuskitError> {
let mut stream = completion_stream("gpt-4o", "Count from one to five.").await?;
while let Some(chunk) = stream.next().await {
print!("{}", chunk?);
}
Ok(())
}
```
## CLI
```bash
nxuskit-cli chat \
--provider openai \
--model gpt-4o \
--stream \
"Explain streaming responses in one paragraph."
```
For machine-readable output, use the Level 1 `call` command with JSONL:
```bash
echo '{"provider":"openai","model":"gpt-4o","prompt":"Count to five."}' \
| nxuskit-cli call --input - --format jsonl --stream
```
## Stream Events
Streaming APIs generally emit:
- **Content chunks** — Partial text or structured deltas.
- **Metadata** — Provider, model, token usage, timing, or trace information when available.
- **Completion** — Final status, finish reason, or terminal error.
The exact fields vary by provider. Code that handles multiple providers should
append content chunks as they arrive and treat metadata as optional.
## Error Handling
Handle errors in the stream loop, not only at stream creation time. A provider
can accept a request and still fail later because of rate limits, network
interruptions, token limits, or a cancelled operation.
## Related Reference
- [Provider Model](/v0.9.4/nxuskit/concepts/provider-model/)
- [Cloud LLM Providers](/v0.9.4/nxuskit/reference/providers/cloud-llms/)
- [Local LLM Providers](/v0.9.4/nxuskit/reference/providers/local-llms/)
- [CLI Input Format Reference](/v0.9.4/nxuskit/reference/cli-reference/)
---
# CLIPS Session Migration
URL: https://docs.nxus.systems/v0.9.4/nxuskit/migration/clips-session-migration
This guide covers migrating from the legacy `ClipsEnvironment` / `nxuskit_clips_env_*` API
to the new `ClipsSession` / `nxuskit_clips_session_*` API introduced in SDK v0.9.1.
## What Changed
| Aspect | Old API | New API |
|--------|---------|---------|
| Handle type | Opaque pointer (`NxuskitClipsEnv*`) | `uint64_t` session handle |
| Safety | Manual pointer management | Generational index (use-after-free protection) |
| Fact builder | Separate `NxuskitClipsFactBuilder` type | `nxuskit_clips_fact_assert_structured()` (JSON slots) |
| Fact iteration | Pointer chain (`first_fact` → `fact_next`) | `nxuskit_clips_facts_by_template()` (JSON array) |
| Template lookup | `nxuskit_clips_find_template()` → pointer | `nxuskit_clips_template_exists()` / `template_list()` |
| Thread safety | Not guaranteed | Session registry with RwLock; `session_halt()` for cross-thread signalling |
## Who Needs to Migrate
- **Chat provider users** (`NxuskitProvider` / `ChatRequest`): **No changes needed.** The Chat provider interface is unchanged.
- **Direct C ABI users** (`nxuskit_clips_env_*` functions): **Must migrate.** Old functions are removed.
- **Rust SDK users** (`nxuskit::ClipsEnvironment`): **Must migrate** to `nxuskit::ClipsSession`.
## C ABI Migration
### Session Lifecycle
```c
// OLD
struct NxuskitClipsEnv *env = nxuskit_clips_env_create();
nxuskit_clips_env_load_file(env, "rules.clp");
nxuskit_clips_env_reset(env);
nxuskit_clips_env_run(env, -1);
nxuskit_clips_env_destroy(env);
// NEW
uint64_t s = nxuskit_clips_session_create();
nxuskit_clips_session_load_file(s, "rules.clp");
nxuskit_clips_session_reset(s);
nxuskit_clips_session_run(s, -1);
nxuskit_clips_session_destroy(s);
```
### Asserting Facts
```c
// OLD — string-based
nxuskit_clips_env_assert_string(env, "(sensor (name \"t1\") (value 42))");
// OLD — fact builder
struct NxuskitClipsFactBuilder *fb = nxuskit_clips_fb_create(env, "sensor");
nxuskit_clips_fb_put_string(fb, "name", "t1");
nxuskit_clips_fb_put_integer(fb, "value", 42);
nxuskit_clips_fb_assert(fb);
// NEW — string-based (unchanged pattern)
nxuskit_clips_fact_assert_string(s, "(sensor (name \"t1\") (value 42))");
// NEW — structured (replaces fact builder)
nxuskit_clips_fact_assert_structured(s, "sensor",
"{\"name\":\"t1\",\"value\":42}");
```
### Querying Facts
```c
// OLD — pointer iteration
struct NxuskitClipsTemplate *tmpl = nxuskit_clips_find_template(env, "sensor");
struct NxuskitClipsFact *fact = nxuskit_clips_template_first_fact(tmpl);
while (fact) {
char *slot = nxuskit_clips_fact_get_slot(fact, "value");
// use slot...
nxuskit_free_string(slot);
struct NxuskitClipsFact *next = nxuskit_clips_fact_next(fact);
nxuskit_clips_fact_destroy(fact);
fact = next;
}
nxuskit_clips_template_destroy(tmpl);
// NEW — JSON array
char *facts = nxuskit_clips_facts_by_template(s, "sensor");
// facts is a JSON array of fact objects — parse with your JSON library
nxuskit_free_string(facts);
```
## Rust SDK Migration
### Basic Usage
```rust
// OLD
use nxuskit::ClipsEnvironment;
let env = ClipsEnvironment::new()?;
env.load_from_string("(deftemplate sensor (slot name) (slot value))")?;
env.reset()?;
env.assert_string("(sensor (name \"t1\") (value 42))")?;
env.run(None)?;
if let Some(tmpl) = env.find_template("sensor")? {
for fact in tmpl.facts().flatten() {
println!("{:?}", fact.get_slot("value")?);
}
}
// NEW
use nxuskit::ClipsSession;
let session = ClipsSession::create()?;
session.load_string("(deftemplate sensor (slot name) (slot value))")?;
session.reset()?;
session.assert_string("(sensor (name \"t1\") (value 42))")?;
session.run(-1)?;
let facts = session.facts_by_template("sensor")?;
println!("{}", facts);
// session is destroyed on drop
```
### FBP (Fact-Based Processing) Pattern
```rust
use nxuskit::ClipsSession;
// Create a persistent session for iterative processing
let session = ClipsSession::create()?;
session.load_file("rules/shared/000-core.clp")?;
session.load_file("rules/data-qc/bounds-check.clp")?;
// Cycle 1: Load initial data
session.reset()?;
session.assert_string(r#"(input-data (record-id 1) (value 150.0))"#)?;
session.run(-1)?;
let alerts = session.facts_by_template("alert")?;
// Cycle 2: New data, same rules (facts persist unless reset)
session.assert_string(r#"(input-data (record-id 2) (value 200.0))"#)?;
session.run(-1)?;
let more_alerts = session.facts_by_template("alert")?;
```
### LKS (Load-知識-Solve) Pattern
```rust
use nxuskit::ClipsSession;
// Load once, solve many times
let session = ClipsSession::create()?;
session.load_file("expert-system.clp")?;
for case in cases {
session.reset()?; // Clear facts, keep rules
session.assert_string(&format!("(case-data (id {}) (symptoms {}))",
case.id, case.symptoms))?;
session.run(-1)?;
let diagnosis = session.facts_by_template("diagnosis")?;
println!("Case {}: {}", case.id, diagnosis);
}
```
## New Capabilities (No Old Equivalent)
These features are only available in the Session API:
| Feature | Function | Description |
|---------|----------|-------------|
| Session halt | `session_halt()` | Thread-safe inference cancellation |
| Session cache | `session_preload()` / `get_cached()` | Named session caching |
| Fact retraction | `fact_retract()` / `fact_retract_by_template()` | Targeted fact removal |
| Rule debugging | `rule_breakpoint_set()` / `rule_times_fired()` | Rule-level debugging |
| Global variables | `global_get_value()` / `global_set_value()` | Defglobal access |
| Watch/dribble | `watch()` / `dribble_on()` | Tracing and logging |
| Strategy control | `strategy_get()` / `strategy_set()` | Conflict resolution |
| Module focus | `focus_push()` / `focus_pop()` | Module execution control |
| Structured assert | `fact_assert_structured()` | JSON-based fact assertion |
| Binary save/load | `session_save_binary()` / `load_binary()` | Fast environment serialization |
---
# Logprobs Migration
URL: https://docs.nxus.systems/v0.9.4/nxuskit/migration/logprobs-migration
**Audience:** SDK consumers that previously needed to request token log
probabilities through `provider_options` because the SDK had no first-class
field.
## What Changed in v0.9.3
The Rust wrapper, Python SDK, Go SDK, and the C ABI now expose first-class
unary chat logprobs:
- **Request side:** `ChatRequest.logprobs: Option` and
`ChatRequest.top_logprobs: Option` (Rust); equivalents in Python and
the C ABI envelope. Use the Rust builders `with_logprobs(true)` /
`with_top_logprobs(n)`, the Python `ChatRequest(..., logprobs=True,
top_logprobs=5)`, or set the JSON fields directly when calling the C ABI.
- **Response side:** `ChatResponse.logprobs: Option` with
typed `TokenLogprob` (selected token + bytes) and `TopLogprob` (each
alternative + bytes). The wire path is `logprobs.content[]` (matches
OpenAI; pinned by
`packages/nxuskit-engine/crates/nxuskit-core/tests/logprobs_abi_passthrough_test.rs`).
- **Engine behavior:** `parameter_adapter.rs::adapt_logprobs` performs
warn-and-drop when a provider's `ProviderCapabilities.supports_logprobs`
is `false`, emits a structured `Info` warning with
`parameter == "logprobs"`, and drops both first-class fields. It does
**not** tunnel logprobs through `provider_options`.
## Migration For Existing Callers
If you previously stuffed logprobs into `provider_options` to work around
the missing first-class field:
```rust
// OLD (pre-v0.9.3) — pattern still parses but never reaches the provider
let req = ChatRequest::new("gpt-5.4")
.with_message(Message::user("..."))
.with_provider_options(serde_json::json!({
"logprobs": true,
"top_logprobs": 5,
}));
```
Switch to the first-class fields:
```rust
// NEW (v0.9.3+) — first-class, capability-gated, surfaces typed response
let req = ChatRequest::new("gpt-5.4")
.with_message(Message::user("..."))
.with_logprobs(true)
.with_top_logprobs(5);
```
Python:
```python
from nxuskit import ChatRequest
req = ChatRequest(
model="gpt-5.4",
messages=[{"role": "user", "content": "..."}],
logprobs=True,
top_logprobs=5,
)
```
C ABI / direct JSON:
```json
{
"model": "gpt-5.4",
"messages": [{"role": "user", "content": "..."}],
"logprobs": true,
"top_logprobs": 5
}
```
## Why The Switch Matters
- **Capability gating:** the engine only forwards logprobs to providers
whose capability map enables it. The legacy `provider_options` path
bypasses this check and silently dies on unsupported providers.
- **Typed responses:** `ChatResponse.logprobs` returns a typed
`LogprobsData` rather than raw provider JSON. Selected token and
alternative tokens are addressable as fields, including UTF-8 bytes
when present.
- **Cross-language parity:** Rust, Python, Go, and the C ABI all use the
same wire shape (`logprobs.content[]` with `token`, `logprob`, `bytes`,
`top_logprobs`). Switching once works everywhere.
- **No silent drops:** unsupported providers now emit a structured
warning instead of swallowing the request, so callers can detect and
fall back.
## v0.9.4 update
- **Streaming logprobs shipped in v0.9.4** (sprint S1 / branch 098).
`StreamChunk` now carries `logprobs: Option` (Rust),
`Logprobs *StreamLogprobsDelta` (Go), `logprobs: Optional[StreamLogprobsDelta]`
(Python) - additive, defaults to `None`/`nil` for non-supporting providers.
`ProviderCapabilities.supports_streaming_logprobs` gates it (with
`supports_streaming_logprobs => supports_logprobs` enforced). OpenAI is the
only provider with `supports_streaming_logprobs = true` per fixture evidence;
all others are `false` per the evidence-first rule. See the v0.9.4 CHANGELOG
entry for the cross-language parity harness.
- **`CapabilityManifest` v2** - a public preview subset for provider/model
capability discovery was introduced in v0.9.4 (sprint S2/S3 / branch 099);
the full internal manifest is unchanged. The publication decision is recorded
in the 099 artifacts.
---
# Upgrade Path
URL: https://docs.nxus.systems/v0.9.4/nxuskit/migration/upgrade-path
## Overview
When a Pro feature is called without valid authorization, the SDK returns
a specific error type with an actionable message. This document maps every
error to its cause and resolution.
## Error Reference
### `FeatureUnavailable`
**Message**: varies by context (see sub-cases below)
This is the umbrella error returned when a Pro feature cannot be accessed.
The message text tells you exactly what to do.
---
### `LicenseRequired`
**Returned when**: A Pro feature is called but no valid license token was
found in the resolution chain (env var → file → API parameter).
**Message**:
```
License installation required.
```
**Resolution**:
1. Authenticate: `nxuskit-cli license login`
2. Activate your license: `nxuskit-cli license activate --key `
3. For CI/CD: set `NXUSKIT_LICENSE_TOKEN` environment variable with your
deployment token
4. To start a trial: `nxuskit-cli license login` then `nxuskit-cli license activate --trial`
---
### `LicenseExpired`
**Returned when**: The developer token's subscription period has ended.
**Message**:
```
License installation required.
```
**Resolution**:
1. Renew your subscription at your account dashboard
2. After renewal, run `nxuskit-cli license activate --key ` to get a
fresh token
3. Community features continue working during the gap
---
### `EditionInsufficient`
**Returned when**: You have a valid token but the binary is the Community
edition, which does not include Pro code.
**Message**:
```
This feature requires Pro edition.
```
**Resolution**:
1. Download the Pro edition binary (requires authenticated access)
2. Replace your Community binary with the Pro binary
3. Your existing license token will be recognized automatically
---
### `VersionCeilingExceeded`
**Returned when**: A deployment token's version ceiling is lower than the
running SDK version.
**Message**:
```
Deployment token covers up to v{ceiling}. Update your deployment token for v{current}+ support.
```
**Resolution**:
1. If you have an active support subscription, request an updated
deployment token from your account dashboard
2. Alternatively, pin the SDK version to stay within the token ceiling
3. Contact **support@nxus.systems** if you need help
---
### `TrialSuspended`
**Returned when**: A trial token was issued but not activated within
the 7-day grace period.
**Message**:
```
License installation required.
```
**Resolution**:
1. Run `nxuskit-cli license login` to authenticate
2. Run `nxuskit-cli license activate --trial` to resume the trial
3. This extends Pro access for the remainder of the 30-day trial period
---
### `TrialExpired`
**Returned when**: The 30-day trial period has ended.
**Message**:
```
License installation required.
```
**Resolution**:
1. Purchase a Pro license
2. Community features continue working without interruption
3. All Pro features will be restored immediately after activation
---
### `TrialIssuanceFailed`
**Returned when**: The SDK attempted to issue a trial token but could
not complete the operation.
**Message**:
```
License installation required.
```
**Resolution**:
1. Run `nxuskit-cli license login` to authenticate first
2. Then run `nxuskit-cli license activate --trial`
3. Community features remain available regardless
---
## Error Handling by Language
### Rust
```rust
use nxuskit::{FeatureUnavailableError, LicenseExpiredError, LicenseRequiredError};
match nxuskit::zen_evaluate(&table, &input) {
Ok(result) => { /* success */ }
Err(e) if e.is::() => {
eprintln!("{}", e); // "License installation required."
}
Err(e) if e.is::() => {
eprintln!("{}", e); // "License installation required."
}
Err(e) => { /* other errors */ }
}
```
### Python
```python
from nxuskit import zen_evaluate
from nxuskit import LicenseRequiredError, LicenseExpiredError, FeatureUnavailableError
try:
result = zen_evaluate(table_path, input_data)
except LicenseRequiredError as e:
print(e.message) # "License installation required."
except LicenseExpiredError as e:
print(e.message) # "License installation required."
except FeatureUnavailableError as e:
print(e.message) # generic feature gate
```
### Go
```go
import "github.com/nxus-SYSTEMS/nxuskit-go"
result, err := nxuskit.ZenEvaluate(table, input)
if err != nil {
switch {
case errors.Is(err, nxuskit.ErrLicenseRequired):
fmt.Println(err) // "License installation required."
case errors.Is(err, nxuskit.ErrLicenseExpired):
fmt.Println(err) // "License installation required."
default:
fmt.Println(err)
}
}
```
## Quick Decision Tree
```
Pro feature called
│
├─ No token found? → "License installation required."
├─ Token expired? → "License installation required."
├─ Community binary? → EditionInsufficient → download Pro binary
├─ Version ceiling hit? → VersionCeilingExceeded → update deployment token
├─ Trial not activated? → "License installation required."
├─ Trial past 30 days? → "License installation required."
├─ Can't reach service? → "License installation required."
└─ Valid token + Pro binary? → Success
```
---
# API Reference
URL: https://docs.nxus.systems/v0.9.4/nxuskit/reference/api
## Overview
nxusKit APIs are organized around a small set of shared contracts:
- **Provider configuration** creates a backend connection.
- **Chat requests** carry model names, messages, and provider options.
- **Chat responses** return content, metadata, usage, and errors.
- **Streaming calls** emit incremental chunks for interactive workflows.
- **Specialized providers** such as CLIPS and Z3 use structured JSON payloads
inside the same request/response pattern.
Use this page as the entry point for API-level reference material.
## Core References
| Reference | Use for |
|-----------|---------|
| [C ABI Reference](/v0.9.4/nxuskit/reference/api-reference/) | C functions, ownership rules, FFI handles, CLIPS session calls, and memory management. |
| [CLI Input Format Reference](/v0.9.4/nxuskit/reference/cli-reference/) | Structured JSON/YAML/JSONL input contracts for `nxuskit-cli`. |
| [Cloud LLM Providers](/v0.9.4/nxuskit/reference/providers/cloud-llms/) | Provider configuration for hosted LLM APIs. |
| [Local LLM Providers](/v0.9.4/nxuskit/reference/providers/local-llms/) | Ollama, LM Studio, and in-process local model configuration. |
| [Expert System & Utility Providers](/v0.9.4/nxuskit/reference/providers/expert-systems/) | CLIPS, MCP, Mock, and Loopback configuration. |
| [Z3 Constraint Satisfaction Provider](/v0.9.4/nxuskit/reference/providers/z3-solver/) | Z3 input, output, optimization, and streaming contracts. |
## Shared Chat Shape
The language wrappers expose native types, but the shared request shape is:
```json
{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "You are concise."},
{"role": "user", "content": "Summarize nxusKit."}
],
"max_tokens": 512,
"temperature": 0.2,
"stream": false
}
```
Responses include provider content plus optional metadata:
```json
{
"content": "nxusKit is a multi-language SDK...",
"model": "gpt-4o",
"finish_reason": "stop",
"usage": {
"input_tokens": 24,
"output_tokens": 12
}
}
```
Provider-specific options belong in the configuration object or provider options
map. See the provider reference pages before relying on a field across multiple
backends.
## Memory and Ownership
When calling through the C ABI, every returned provider handle, response handle,
stream handle, and allocated string has an explicit free function. Use the
[ownership summary](/v0.9.4/nxuskit/reference/api-reference/#ownership-summary) before
integrating from C, C++, Go FFI, Python FFI, or another native boundary.
---
# C ABI Reference
URL: https://docs.nxus.systems/v0.9.4/nxuskit/reference/api-reference
All functions are declared in `nxuskit.h`. The ABI uses opaque handles and JSON
strings for all data exchange. Every function is thread-safe unless noted.
## Version
### `nxuskit_version`
```c
const char *nxuskit_version(void);
```
Returns the library version string (e.g., `"0.9.4"`). The returned pointer is
static and valid for the process lifetime. Never returns NULL.
## Provider Lifecycle
### `nxuskit_create_provider`
```c
struct NxuskitProvider *nxuskit_create_provider(const char *config_json);
```
Creates a provider from a JSON configuration string.
**Parameters:**
- `config_json` — JSON string with at minimum `{"provider_type": "..."}`.
See [Provider Reference](../providers/cloud-llms/) for provider-specific fields.
**Returns:** Opaque provider handle, or NULL on failure. On failure, call
`nxuskit_last_error()` for the error message.
**Ownership:** Caller owns the returned handle. Must call `nxuskit_free_provider()`
when done.
**Config JSON fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `provider_type` | string | Yes | Provider identifier (see providers list) |
| `api_key` | string | Varies | API key for cloud providers |
| `model` | string | No | Default model name |
| `base_url` | string | No | Custom API endpoint |
| `timeout_ms` | integer | No | Request timeout in milliseconds |
**Example:**
```c
const char *config = "{\"provider_type\":\"openai\",\"api_key\":\"sk-...\"}";
struct NxuskitProvider *p = nxuskit_create_provider(config);
if (!p) {
fprintf(stderr, "Error: %s\n", nxuskit_last_error());
}
```
### `nxuskit_free_provider`
```c
void nxuskit_free_provider(struct NxuskitProvider *provider);
```
Frees a provider handle. Safe to call with NULL (no-op).
**Parameters:**
- `provider` — Handle from `nxuskit_create_provider()`, or NULL.
## Synchronous Chat
### `nxuskit_chat`
```c
struct NxuskitResponse *nxuskit_chat(
struct NxuskitProvider *provider,
const char *request_json
);
```
Sends a synchronous chat request. Blocks until the response is complete.
**Parameters:**
- `provider` — Provider handle (must not be NULL)
- `request_json` — JSON chat request string
**Returns:** Response handle, or NULL on failure.
**Ownership:** Caller owns the returned handle. Must call `nxuskit_free_response()`.
**Request JSON fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `model` | string | Yes | Model identifier |
| `messages` | array | Yes | Array of `{role, content}` objects |
| `temperature` | float | No | Sampling temperature (0.0–2.0) |
| `max_tokens` | integer | No | Maximum tokens in response |
| `top_p` | float | No | Nucleus sampling parameter |
| `stop` | array | No | Stop sequences |
| `stream` | boolean | No | Must be `false` for sync (default) |
| `response_format` | object | No | Response format constraints |
**Message object:**
| Field | Type | Description |
|-------|------|-------------|
| `role` | string | `"system"`, `"user"`, or `"assistant"` |
| `content` | string | Message content |
### `nxuskit_response_json`
```c
const char *nxuskit_response_json(const struct NxuskitResponse *response);
```
Returns the JSON string from a response handle.
**Parameters:**
- `response` — Response handle from `nxuskit_chat()` (must not be NULL)
**Returns:** JSON string pointer. Valid only while the response handle exists.
Do **not** free this pointer — it is owned by the response handle.
**Response JSON fields:**
| Field | Type | Description |
|-------|------|-------------|
| `content` | string | The model's response text |
| `model` | string | Model used |
| `provider` | string | Provider name |
| `usage` | object | Token usage (if available) |
| `usage.prompt_tokens` | integer | Input tokens |
| `usage.completion_tokens` | integer | Output tokens |
| `usage.total_tokens` | integer | Total tokens |
| `finish_reason` | string | Why generation stopped |
| `warnings` | array | Provider warnings (if any) |
### `nxuskit_free_response`
```c
void nxuskit_free_response(struct NxuskitResponse *response);
```
Frees a response handle. Safe to call with NULL.
## Streaming Chat
### Callback Types
```c
typedef int32_t (*NxuskitStreamCallback)(
const char *chunk_json,
void *user_data
);
typedef void (*NxuskitStreamDoneCallback)(
const char *final_json,
void *user_data
);
```
**`NxuskitStreamCallback`** is called for each streaming chunk. Return 0 to
continue, non-zero to request cancellation.
**`NxuskitStreamDoneCallback`** is called exactly once when streaming completes
(success, error, or cancellation).
**Important:** Callbacks fire from a **background thread**. The caller must
ensure `user_data` is thread-safe.
### `nxuskit_chat_stream`
```c
struct NxuskitStream *nxuskit_chat_stream(
struct NxuskitProvider *provider,
const char *request_json,
NxuskitStreamCallback on_chunk,
NxuskitStreamDoneCallback on_done,
void *user_data
);
```
Starts a streaming chat request. Returns immediately; chunks arrive via callbacks.
**Parameters:**
- `provider` — Provider handle (must not be NULL)
- `request_json` — JSON chat request string
- `on_chunk` — Called for each chunk (from background thread)
- `on_done` — Called once when streaming ends (from background thread)
- `user_data` — Opaque pointer passed to both callbacks
**Returns:** Stream handle, or NULL on failure.
**Chunk JSON fields:**
| Field | Type | Description |
|-------|------|-------------|
| `delta` | string | Incremental text content |
| `index` | integer | Chunk sequence number (0-based) |
| `thinking` | string | Chain-of-thought reasoning (if enabled, optional) |
| `finish_reason` | string | Why generation stopped (set on final chunk, optional) |
| `usage` | object | Token usage statistics (typically only on final chunk, optional) |
| `tool_calls` | array | Tool call deltas (if applicable, optional) |
**Done JSON fields:** Same as synchronous response JSON, plus optional `error`:
| Field | Type | Description |
|-------|------|-------------|
| `error.error_type` | string | Error category |
| `error.message` | string | Error description |
### `nxuskit_cancel_stream`
```c
void nxuskit_cancel_stream(struct NxuskitStream *stream);
```
Cancels a streaming request. Blocks until all pending callbacks have completed.
After this call returns, no further callbacks will fire.
Safe to call with NULL.
### `nxuskit_free_stream`
```c
void nxuskit_free_stream(struct NxuskitStream *stream);
```
Frees a stream handle. Must be called after the stream completes or is cancelled.
Safe to call with NULL.
**Typical lifecycle:**
```c
stream = nxuskit_chat_stream(provider, request, on_chunk, on_done, data);
// ... callbacks fire ...
// After on_done fires (or if you want to cancel):
nxuskit_cancel_stream(stream); // optional — ensures no more callbacks
nxuskit_free_stream(stream); // required — frees resources
```
## Model Discovery
### `nxuskit_list_models`
```c
char *nxuskit_list_models(struct NxuskitProvider *provider);
```
Returns a JSON array of available models.
**Parameters:**
- `provider` — Provider handle (must not be NULL)
**Returns:** JSON string (caller-owned), or NULL on failure.
**Ownership:** Caller must free the returned string with `nxuskit_free_string()`.
**Response format:**
```json
[
{"id": "gpt-4o", "name": "GPT-4o"},
{"id": "gpt-4o-mini", "name": "GPT-4o Mini"}
]
```
## Error Handling
### `nxuskit_last_error`
```c
const char *nxuskit_last_error(void);
```
Returns the last error message for the **calling thread**. Returns NULL if no
error has occurred on this thread.
**Thread-local:** Each thread has its own error state. Calling any `nxuskit_*`
function may overwrite the previous error on that thread.
**Lifetime:** The returned pointer is valid until the next `nxuskit_*` call on
the same thread.
## Memory Management
### `nxuskit_free_string`
```c
void nxuskit_free_string(char *ptr);
```
Frees a caller-owned string returned by any `nxuskit_*` function that returns
`char*` (e.g., `nxuskit_list_models()`, `nxuskit_clips_facts_list()`,
`nxuskit_clips_eval()`). Safe to call with NULL.
**Important:** Only use this for strings documented as "caller-owned". Do not
use it for strings from `nxuskit_response_json()` (those are owned by the
response handle) or `nxuskit_version()` (static).
## Ownership Summary
| Function | Returns | Owned By | Free With |
|----------|---------|----------|-----------|
| `nxuskit_version()` | `const char*` | Library (static) | Never free |
| `nxuskit_create_provider()` | `NxuskitProvider*` | Caller | `nxuskit_free_provider()` |
| `nxuskit_chat()` | `NxuskitResponse*` | Caller | `nxuskit_free_response()` |
| `nxuskit_response_json()` | `const char*` | Response handle | Freed with response |
| `nxuskit_chat_stream()` | `NxuskitStream*` | Caller | `nxuskit_free_stream()` |
| `nxuskit_list_models()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_last_error()` | `const char*` | Thread-local | Never free |
## CLIPS Session API
Direct access to the CLIPS 6.4.2 rule engine via session-based handles — create
sessions, load rules, assert facts, run inference, and inspect results without
going through the provider/chat abstraction.
All CLIPS operations use opaque `uint64_t` session handles (generational indices
that prevent use-after-free). Return conventions:
- `int32_t` functions return 0 on success, -1 on error
- `char*` functions return a JSON string (caller-owned, free with `nxuskit_free_string()`) or NULL on error
- `bool` functions return the queried value; check `nxuskit_last_error()` on unexpected results
### Session Lifecycle
#### `nxuskit_clips_session_create`
```c
uint64_t nxuskit_clips_session_create(void);
```
Creates a new isolated CLIPS session. Returns a non-zero session handle, or 0 on
failure (check `nxuskit_last_error()`).
#### `nxuskit_clips_session_destroy`
```c
void nxuskit_clips_session_destroy(uint64_t session);
```
Destroys a session and frees all resources. No-op if the handle is invalid.
#### `nxuskit_clips_session_reset`
```c
int32_t nxuskit_clips_session_reset(uint64_t session);
```
Resets the session: clears all facts, preserves rules, restores initial-fact.
#### `nxuskit_clips_session_clear`
```c
int32_t nxuskit_clips_session_clear(uint64_t session);
```
Clears everything (facts, rules, templates) — returns the session to a pristine state.
#### `nxuskit_clips_session_info`
```c
char *nxuskit_clips_session_info(uint64_t session);
```
Returns session metadata as a JSON object (module count, rule count, fact count, etc.).
### Loading Constructs
#### `nxuskit_clips_session_load_file`
```c
int32_t nxuskit_clips_session_load_file(uint64_t session, const char *path);
```
Loads constructs from a `.clp` file.
#### `nxuskit_clips_session_load_string`
```c
int32_t nxuskit_clips_session_load_string(uint64_t session, const char *constructs);
```
Loads constructs from an in-memory string.
**Example:**
```c
uint64_t s = nxuskit_clips_session_create();
nxuskit_clips_session_load_string(s,
"(deftemplate sensor (slot name) (slot value))");
```
#### `nxuskit_clips_session_load_binary`
```c
int32_t nxuskit_clips_session_load_binary(uint64_t session, const char *path);
```
Loads a pre-compiled binary image (`.bin` file created with `save_binary`).
#### `nxuskit_clips_session_save_binary`
```c
int32_t nxuskit_clips_session_save_binary(uint64_t session, const char *path);
```
Saves the current session state as a binary image for fast reloading.
#### `nxuskit_clips_session_build`
```c
int32_t nxuskit_clips_session_build(uint64_t session, const char *construct);
```
Builds a single CLIPS construct (deftemplate, defrule, etc.) from a string.
#### `nxuskit_clips_session_batch`
```c
int32_t nxuskit_clips_session_batch(uint64_t session, const char *path);
```
Executes a batch file of CLIPS commands.
#### `nxuskit_clips_session_load_json`
```c
int32_t nxuskit_clips_session_load_json(uint64_t session, const char *json);
```
Loads constructs from a JSON specification (templates, rules, facts in one call).
### Session Cache
#### `nxuskit_clips_session_preload`
```c
int32_t nxuskit_clips_session_preload(const char *name, const char *rules_json);
```
Preloads a named session into the cache. The session is created, rules are loaded,
and the session is stored for later retrieval via `get_cached`.
#### `nxuskit_clips_session_get_cached`
```c
uint64_t nxuskit_clips_session_get_cached(const char *name);
```
Returns a cached session handle by name. Returns 0 if not found.
#### `nxuskit_clips_session_cache_remove`
```c
int32_t nxuskit_clips_session_cache_remove(const char *name);
```
Removes a named session from the cache and destroys it.
### Fact Operations
#### `nxuskit_clips_fact_assert_string`
```c
int64_t nxuskit_clips_fact_assert_string(uint64_t session, const char *fact_string);
```
Asserts a fact using CLIPS syntax. Returns the fact index (>= 0) on success, or -1 on error.
**Example:**
```c
int64_t idx = nxuskit_clips_fact_assert_string(s,
"(sensor (name \"temp-1\") (value 150))");
```
#### `nxuskit_clips_fact_assert_structured`
```c
int64_t nxuskit_clips_fact_assert_structured(
uint64_t session,
const char *template_name,
const char *slots_json
);
```
Asserts a fact using a JSON slot specification. Returns the fact index or -1.
**Example:**
```c
int64_t idx = nxuskit_clips_fact_assert_structured(s, "sensor",
"{\"name\":\"temp-1\",\"value\":150}");
```
#### `nxuskit_clips_fact_retract`
```c
int32_t nxuskit_clips_fact_retract(uint64_t session, int64_t fact_index);
```
Retracts a fact by its index.
#### `nxuskit_clips_fact_retract_by_template`
```c
int32_t nxuskit_clips_fact_retract_by_template(uint64_t session, const char *template_name);
```
Retracts all facts of a given template.
#### `nxuskit_clips_fact_exists`
```c
bool nxuskit_clips_fact_exists(uint64_t session, int64_t fact_index);
```
Returns true if the fact index refers to an existing fact.
#### `nxuskit_clips_fact_get_slot`
```c
char *nxuskit_clips_fact_get_slot(uint64_t session, int64_t fact_index, const char *slot_name);
```
Returns a slot value as a type-tagged JSON string (e.g., `{"type":"integer","value":42}`).
**Slot JSON types:**
| CLIPS Type | JSON `type` | JSON `value` |
|------------|-------------|--------------|
| INTEGER | `"integer"` | number |
| FLOAT | `"float"` | number |
| STRING | `"string"` | string |
| SYMBOL | `"symbol"` | string |
| MULTIFIELD | `"multifield"` | array of typed values |
#### `nxuskit_clips_fact_slot_values`
```c
char *nxuskit_clips_fact_slot_values(uint64_t session, int64_t fact_index);
```
Returns all slot values as a JSON object.
#### `nxuskit_clips_fact_pp_form`
```c
char *nxuskit_clips_fact_pp_form(uint64_t session, int64_t fact_index);
```
Returns the pretty-printed CLIPS representation of a fact.
#### `nxuskit_clips_fact_index`
```c
int64_t nxuskit_clips_fact_index(uint64_t session, int64_t fact_index);
```
Returns the canonical CLIPS fact index, or -1 on error.
#### `nxuskit_clips_facts_list`
```c
char *nxuskit_clips_facts_list(uint64_t session);
```
Returns all facts as a JSON array.
#### `nxuskit_clips_facts_by_template`
```c
char *nxuskit_clips_facts_by_template(uint64_t session, const char *template_name);
```
Returns all facts matching a template as a JSON array.
#### `nxuskit_clips_fact_duplication_get` / `set`
```c
bool nxuskit_clips_fact_duplication_get(uint64_t session);
int32_t nxuskit_clips_fact_duplication_set(uint64_t session, bool allow);
```
Query or set whether duplicate facts are allowed.
### Template Operations
#### `nxuskit_clips_template_exists`
```c
bool nxuskit_clips_template_exists(uint64_t session, const char *name);
```
Returns true if the named template exists in the session.
#### `nxuskit_clips_template_list`
```c
char *nxuskit_clips_template_list(uint64_t session);
```
Returns all template names as a JSON array.
#### `nxuskit_clips_template_slot_names`
```c
char *nxuskit_clips_template_slot_names(uint64_t session, const char *template_name);
```
Returns slot names for a template as a JSON array.
#### `nxuskit_clips_template_slot_info`
```c
char *nxuskit_clips_template_slot_info(uint64_t session, const char *template_name);
```
Returns detailed slot information (types, defaults, constraints) as JSON.
#### `nxuskit_clips_template_facts`
```c
char *nxuskit_clips_template_facts(uint64_t session, const char *template_name);
```
Returns all facts of a template as a JSON array.
#### `nxuskit_clips_template_pp_form`
```c
char *nxuskit_clips_template_pp_form(uint64_t session, const char *template_name);
```
Returns the pretty-printed CLIPS definition of a template.
### Inference Engine
#### `nxuskit_clips_session_run`
```c
int64_t nxuskit_clips_session_run(uint64_t session, int64_t limit);
```
Runs inference. Pass `limit = -1` to run until the agenda is exhausted.
Returns the number of rules fired, or -1 on error.
#### `nxuskit_clips_session_halt`
```c
int32_t nxuskit_clips_session_halt(uint64_t session);
```
Signals the session to halt inference (thread-safe — can be called from another thread).
#### `nxuskit_clips_agenda_size`
```c
int64_t nxuskit_clips_agenda_size(uint64_t session);
```
Returns the number of activations on the agenda.
#### `nxuskit_clips_agenda_clear`
```c
int32_t nxuskit_clips_agenda_clear(uint64_t session);
```
Removes all activations from the agenda.
#### `nxuskit_clips_agenda_reorder`
```c
int32_t nxuskit_clips_agenda_reorder(uint64_t session);
```
Reorders the agenda using the current conflict resolution strategy.
#### `nxuskit_clips_strategy_get` / `set`
```c
char *nxuskit_clips_strategy_get(uint64_t session);
int32_t nxuskit_clips_strategy_set(uint64_t session, const char *strategy);
```
Get or set the conflict resolution strategy. Valid values: `"depth"`, `"breadth"`,
`"simplicity"`, `"complexity"`, `"lex"`, `"mea"`, `"random"`.
#### `nxuskit_clips_salience_mode_get` / `set`
```c
char *nxuskit_clips_salience_mode_get(uint64_t session);
int32_t nxuskit_clips_salience_mode_set(uint64_t session, const char *mode);
```
Get or set the salience evaluation mode.
### Rule Operations
#### `nxuskit_clips_rule_exists`
```c
bool nxuskit_clips_rule_exists(uint64_t session, const char *name);
```
Returns true if the named rule exists.
#### `nxuskit_clips_rule_list`
```c
char *nxuskit_clips_rule_list(uint64_t session);
```
Returns all rule names as a JSON array.
#### `nxuskit_clips_rule_times_fired`
```c
int64_t nxuskit_clips_rule_times_fired(uint64_t session, const char *rule_name);
```
Returns how many times a rule has fired, or -1 on error.
#### `nxuskit_clips_rule_breakpoint_set` / `remove` / `has_breakpoint`
```c
int32_t nxuskit_clips_rule_breakpoint_set(uint64_t session, const char *rule_name);
int32_t nxuskit_clips_rule_breakpoint_remove(uint64_t session, const char *rule_name);
bool nxuskit_clips_rule_has_breakpoint(uint64_t session, const char *rule_name);
```
Manage breakpoints on rules for debugging.
#### `nxuskit_clips_rule_refresh`
```c
int32_t nxuskit_clips_rule_refresh(uint64_t session, const char *rule_name);
```
Refreshes a rule, placing its activations back on the agenda.
#### `nxuskit_clips_rule_pp_form`
```c
char *nxuskit_clips_rule_pp_form(uint64_t session, const char *rule_name);
```
Returns the pretty-printed CLIPS definition of a rule.
#### `nxuskit_clips_rule_delete`
```c
int32_t nxuskit_clips_rule_delete(uint64_t session, const char *rule_name);
```
Deletes a rule from the session.
### Module Operations
#### `nxuskit_clips_module_exists`
```c
bool nxuskit_clips_module_exists(uint64_t session, const char *name);
```
Returns true if the named module exists.
#### `nxuskit_clips_module_list`
```c
char *nxuskit_clips_module_list(uint64_t session);
```
Returns all module names as a JSON array.
#### `nxuskit_clips_module_current_get` / `set`
```c
char *nxuskit_clips_module_current_get(uint64_t session);
int32_t nxuskit_clips_module_current_set(uint64_t session, const char *name);
```
Get or set the current module.
#### `nxuskit_clips_focus_push` / `get` / `pop` / `clear`
```c
int32_t nxuskit_clips_focus_push(uint64_t session, const char *module_name);
char *nxuskit_clips_focus_get(uint64_t session);
int32_t nxuskit_clips_focus_pop(uint64_t session);
int32_t nxuskit_clips_focus_clear(uint64_t session);
```
Manage the module focus stack (controls which module's rules are eligible to fire).
### Global Variables
#### `nxuskit_clips_global_exists`
```c
bool nxuskit_clips_global_exists(uint64_t session, const char *name);
```
Returns true if the named defglobal exists.
#### `nxuskit_clips_global_list`
```c
char *nxuskit_clips_global_list(uint64_t session);
```
Returns all global variable names as a JSON array.
#### `nxuskit_clips_global_get_value` / `set_value`
```c
char *nxuskit_clips_global_get_value(uint64_t session, const char *name);
int32_t nxuskit_clips_global_set_value(uint64_t session, const char *name, const char *value_json);
```
Get or set a global variable value. Values use the type-tagged JSON format.
#### `nxuskit_clips_reset_globals_get` / `set`
```c
bool nxuskit_clips_reset_globals_get(uint64_t session);
int32_t nxuskit_clips_reset_globals_set(uint64_t session, bool reset);
```
Query or set whether globals are reset when `session_reset` is called.
### Evaluation
#### `nxuskit_clips_eval`
```c
char *nxuskit_clips_eval(uint64_t session, const char *expression);
```
Evaluates a CLIPS expression and returns the result as a type-tagged JSON string.
#### `nxuskit_clips_function_call`
```c
char *nxuskit_clips_function_call(uint64_t session, const char *function_name, const char *args);
```
Calls a CLIPS function by name with optional arguments string.
### Debugging
#### `nxuskit_clips_watch` / `unwatch`
```c
int32_t nxuskit_clips_watch(uint64_t session, const char *item);
int32_t nxuskit_clips_unwatch(uint64_t session, const char *item);
```
Enable or disable tracing for a watch item. Valid items: `"facts"`, `"rules"`,
`"activations"`, `"compilations"`, `"statistics"`, `"globals"`, `"focus"`, `"all"`.
#### `nxuskit_clips_dribble_on` / `off`
```c
int32_t nxuskit_clips_dribble_on(uint64_t session, const char *path);
int32_t nxuskit_clips_dribble_off(uint64_t session);
```
Start or stop logging all CLIPS I/O to a file.
### CLIPS Ownership Summary
| Function | Returns | Owned By | Free With |
|----------|---------|----------|-----------|
| `nxuskit_clips_session_create()` | `uint64_t` | Session registry | `nxuskit_clips_session_destroy()` |
| `nxuskit_clips_session_get_cached()` | `uint64_t` | Session cache | `nxuskit_clips_session_cache_remove()` |
| `nxuskit_clips_session_info()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_fact_get_slot()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_fact_slot_values()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_fact_pp_form()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_facts_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_facts_by_template()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_slot_names()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_slot_info()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_facts()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_pp_form()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_rule_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_rule_pp_form()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_module_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_module_current_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_focus_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_global_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_global_get_value()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_strategy_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_salience_mode_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_eval()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_function_call()` | `char*` | Caller | `nxuskit_free_string()` |
### Complete Example
```c
#include "nxuskit.h"
#include
int main(void) {
// Create session
uint64_t s = nxuskit_clips_session_create();
if (!s) {
fprintf(stderr, "Error: %s\n", nxuskit_last_error());
return 1;
}
// Load rules
nxuskit_clips_session_load_string(s,
"(deftemplate sensor (slot name (type STRING)) (slot value (type INTEGER)))");
nxuskit_clips_session_load_string(s,
"(defrule high-temp"
" (sensor (name ?n) (value ?v&:(> ?v 100)))"
" =>"
" (printout t \"ALERT: \" ?n \" = \" ?v crlf))");
// Assert facts and run
nxuskit_clips_session_reset(s);
nxuskit_clips_fact_assert_string(s, "(sensor (name \"temp-1\") (value 150))");
int64_t fired = nxuskit_clips_session_run(s, -1);
printf("Rules fired: %lld\n", fired);
// Inspect results
char *facts = nxuskit_clips_facts_list(s);
printf("Facts: %s\n", facts);
nxuskit_free_string(facts);
// Cleanup
nxuskit_clips_session_destroy(s);
return 0;
}
```
## Error Types
Errors returned in response JSON or via `nxuskit_last_error()`:
| Error Type | Description |
|------------|-------------|
| `configuration` | Invalid config, missing API key, version mismatch |
| `invalid_request` | Malformed request JSON, missing required fields |
| `authentication` | Invalid or expired API key |
| `rate_limit` | Provider rate limit exceeded |
| `provider` | Provider-side error (server error, model not found) |
| `timeout` | Request timed out |
| `stream` | Streaming error (connection lost, cancelled) |
| `internal` | Unexpected internal error |
---
# Changelog
URL: https://docs.nxus.systems/v0.9.4/nxuskit/reference/changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
Public SDK release tags begin at `sdk-v0.9.0`. Earlier entries preserve
pre-public development history with normalized pre-public version numbers after
historical version resets.
## [Unreleased]
## [0.9.4] - 2026-05-11
> v0.9.4 release candidate. Provider-capability modernization and release
> hardening, consolidating sprints S1 (streaming logprobs, branch 098),
> S2/S3 (provider capability modernization + Capability Manifest v2 decision,
> branch 099), and S4-S6 (CLI Level 2 completion, examples & bundle alignment,
> docs & release candidate, branch 100). Lockstep version bump `0.9.3 -> 0.9.4`
> across all components. **No C ABI signature changes** in this release.
### Added - S1: Streaming Logprobs + Capability Metadata (branch 098)
- `StreamLogprobsDelta` type (Rust engine + wrapper, Go, Python) carrying
per-chunk `TokenLogprob` entries on streaming responses.
- `StreamChunk.logprobs: Option` (Rust),
`StreamChunk.Logprobs *StreamLogprobsDelta` (Go), and
`StreamChunk.logprobs: Optional[StreamLogprobsDelta]` (Python) - additive,
defaults to `None`/`nil` for non-supporting providers.
- `ProviderCapabilities.supports_streaming_logprobs: bool` flag with
`debug_assert!` enforcing `supports_streaming_logprobs => supports_logprobs`.
- GPT-5.4 reasoning-compat warn-and-drop guard: when `reasoning.effort != "none"`,
`temperature`, `top_p`, and `logprobs` are dropped with a warning rather than
passed through.
- CLI `provider info` exposes the `streaming_logprobs` row (human + JSON).
- Cross-language parity harness at
`internal/tests/parity/stream_logprobs/run_parity.sh`.
- OpenAI: `supports_streaming_logprobs = true` (only supporting provider per
fixture evidence); all other providers `false` per the evidence-first rule.
### Added - S2/S3: Provider Capability Modernization + Manifest v2 (branch 099)
- Provider capability surface modernized; `CapabilityProvider` / "capability
provider" vocabulary introduced (no breaking `LLMProvider` rename).
- xAI Grok runtime provider support under canonical provider id `xai`
(`XAI_API_KEY`, default base URL `https://api.x.ai/v1`); `groq` remains
Groq, Inc. and no confusing `grok` alias is registered.
- `CapabilityManifest` v2 concept with a public preview subset for
provider/model capability discovery (full internal manifest unchanged); the
publication decision is recorded in the 099 artifacts.
- OpenAI remains Chat-Completions-first (no full Responses API migration).
### Added - S4: CLI Level 2 completion & stabilization (branch 100)
- **`nxuskit-cli zen validate`** (Pro) - structural validation of a ZEN JSON
Decision Model (JDM): rejects `functionNode` (JavaScript), checks decision
table node shape, attempts expression compilation, and reports
node/decision-table/rule counts. Backed by a new pure
`nxuskit_engine::providers::zen::validate(model_json) -> Result`
engine entry point. Exit 0 = valid; exit 5 = `parse_error` (unparseable input)
or `zen_validate_error` (structurally invalid, with a `problems[]` report);
exit 4 = `entitlement_denied`.
- **`nxuskit-cli zen test`** (Pro) - run a ZEN decision table against a fixture
set `{table, cases: [{name, input, expected}]}` and compare each actual
output to `expected`; on mismatch emits a structured diff report (exit 5,
`zen_test_mismatch`), a per-case eval error is `zen_test_eval_error`, a
fixture parse error is `parse_error`.
- **`nxuskit-cli bn learn`** - parameter learning (MLE / Bayesian) of a
Bayesian network's CPDs from a CSV dataset given the network skeleton; output
is the learned network, BIF-exportable. **`nxuskit-cli bn evidence`** -
validate/normalize an observations map against a network. (Community edition.)
- `solver what-if --compare` and the unsatisfiable-assumptions path are now
covered by non-`#[ignore]`d, entitlement-aware tests (skip-with-reason in CE,
assertions run in the Pro CI lane `.github/workflows/ci-pro.yml`).
- `CliError::CommandValidation { code, message, details }` - exit 5 with a
command-specific `code` string + structured `details` (used by the new ZEN
commands; exit-code *set* unchanged, FR-001 / Article IV).
- Shell support policy documented (`completions`: bash, zsh, fish supported;
PowerShell not generated in v0.9.4; helper snippets + schema bundle locations).
### Added - S5: Examples repo & bundle alignment (branch 100)
- Examples portfolio bundle-instruction refs bumped to v0.9.4;
`PYTHON_EXAMPLES_STATUS.md` records the v0.9.4 Python-parity scope (minimal
slice: the SDK-side `packages/nxuskit-py` FFI version-guard alignment is in
scope; the 17 already-passing Python examples stay; new examples remain
examples-team backlog). Rust vision example confirmed using the v0.9.2
multimodal wrapper API with no text-only caveat.
### Changed
- `nxuskit-py` `_ffi.py` `EXPECTED_VERSION` aligned to the package version
(`0.9.1` -> `0.9.4`) - the cffi loader requires the linked library's
`nxuskit_version()` to match; this unblocks the Python FFI examples that were
previously `broken-upstream` against the v0.9.3 mismatch.
- Lockstep version bump `0.9.3 -> 0.9.4`: Rust workspace + `nxuskit` crate, C
ABI version constant (`nxuskit-core`), Go `nxuskit-go` (`Version` +
`ExpectedNxuskitVersion`), Python `nxuskit-py` (`__version__` + pyproject).
### Compatibility
- **No C ABI signature changes** in v0.9.4 - only the ABI version constant
moves (`0.9.3 -> 0.9.4`); function signatures and struct layouts are frozen
(Article XIV).
- All v0.9.4 additions are additive. The CLI exit-code *set* (0/1/2/3/4/5/130)
is unchanged; the new ZEN commands introduce new `code` strings within exit 5.
- S1/S2/S3 baseline behavior (streaming logprobs, provider capability metadata)
is preserved.
## [0.9.3] - 2026-04-29
> Published SDK release `sdk-v0.9.3`. Production licensing real-purchase
> activation/recovery, PR readiness, and supported-platform SDK build checks
> passed before release publication.
### Added
- **Production licensing cutover** (Phase 4):
- Release builds embed the production ES256 public key with
`kid: es256-v1`.
- Release default endpoint is `https://nxus.systems/licensing-api/v1`.
- `nxuskit-cli license status --json` exposes endpoint, environment, and
signing-key diagnostics.
- SDK accepts `real_purchase` and `leased` token kinds even while
`nxus-licensing-client` lags on its enum (ES256 fallback verifier).
- Stable licensing errors include `authentication_required`,
`environment_mismatch`, `wrong_product_identifier`, etc.
- Activation timeouts extended to 30s on both client and proxy
(`EXTENDED_TIMEOUT_SECS = 30`) for cold-start activation paths.
- **First-class unary chat logprobs** (Phase 5, US2):
- **Rust wrapper** (`nxuskit`): `ChatRequest::with_logprobs(bool)` and
`with_top_logprobs(u8)`; typed `ChatResponse.logprobs: LogprobsData`
with `TokenLogprob` (selected token + bytes) and `TopLogprob`
(alternative + bytes). Doctests on `with_logprobs` and `LogprobsData`.
- **Python SDK** (`nxuskit-py`): new `ChatRequest` dataclass with
`logprobs` / `top_logprobs` kwargs; `LogprobsData`, `TokenLogprob`,
`TopLogprob` exported from top-level `nxuskit`. FFI response decode
populates typed logprobs.
- **C ABI**: round-trip preserves `logprobs.content[]`, alternative
tokens, and UTF-8 bytes. Wire path is `logprobs.content[]` (matches
OpenAI; pinned by
`tests/logprobs_abi_passthrough_test.rs::response_envelope_uses_content_field_for_logprobs_token_array`).
- **Engine**: `parameter_adapter.rs::adapt_logprobs` performs warn-and-
drop when a provider lacks `supports_logprobs`, with structured Info
warning. `provider_options` does **not** tunnel logprobs.
- **Migration guide:** The [logprobs migration guide](/v0.9.4/nxuskit/migration/logprobs-migration/) covers
Rust + Python + C ABI before/after with capability-gating rationale.
- **ABI / version consistency** (Phase 3):
- Workspace, Rust wrapper, Python package, Go markers, C ABI version
constant, capabilities ABI JSON, current SDK docs, and `Cargo.lock`
all bumped to v0.9.3.
- Pre-logprobs v0.9.2 fixture compatibility tests (Rust + Python) prove
requests without logprobs serialize byte-identically to v0.9.2.
- Stale-version guard: `scripts/check-version-inventory.sh`.
### Changed
- `data-model.md` corrected: logprobs response token array is `content`
(matches Rust/Python/C ABI implementations and OpenAI wire format),
not the earlier draft's `tokens`. Pinned by ABI passthrough test.
### Test counts (logprobs surface, cumulative)
- 7 Rust wrapper (mock_provider) + 6 ABI passthrough + 6 engine
warn-drop + 3 streaming-scope + 18 Python = **40 logprobs tests** green
across all SDK surfaces.
## [0.9.2] - 2026-04-13
### Added
- **CLI Level 2 request surface**: richer JSON request construction across chat/call flows, including multimodal image input handling where supported.
- **Provider diagnostics**: provider ping/status improvements for checking SDK environment readiness from the CLI.
- **Python SDK hardening**: runtime library discovery deprecation warning and SecurityValidator coverage for common unsafe input patterns.
- **Release confidence checks**: conformance, parity, performance, and packaging checks expanded for the supported SDK surfaces.
### Changed
- CLI and runtime-loading documentation refreshed for v0.9.2 behavior.
- Test fixtures and CI checks hardened so SDK builds can validate without relying on local native-library side effects.
- Workspace and lockfile versions bumped to v0.9.2.
## [0.9.1] - 2026-04-05
### CLI Level 1 Semantic Remediation
- **Real Engine Integration**: `zen eval`, `solver solve`, `clips eval`, and `bn infer` now execute real engine logic - no more placeholder/stub responses
- **Pipeline Execution**: `pipeline run` dispatches all stage types (LLM, CLIPS, ZEN, solver, BN) through real engines with output handoff and partial results on failure
- **Call Envelope**: `call` propagates tool definitions and includes `tool_calls` and `inference_metadata` in responses
- **Artifact Deep Merge**: `artifact merge` performs recursive deep merge with dot-notation conflict paths
- **Models Capabilities**: `models --supports` filter uses real capability inference from model metadata
- **Provider Auth**: `provider status` uses structured auth subsystem; `provider logout` is provider-scoped
- **Judge/Branch**: `judge select` returns structured errors; `branch compare` produces field-level diffs
### CLI Documentation and Solver Format Compatibility
- **CLI Input Reference**: New `docs/user/cli-input-reference.md` covering all 13 Level 1 commands with JSON schemas, working examples, and common errors
- **Enhanced Help Text**: Every engine command's `--help` now shows input format structure
- **Solver Format Compatibility**: `solver solve` accepts library API format (ConstraintInput with `var_type`, structured constraints, domains, objectives) directly from shared `problem.json` scenario files - no format conversion needed
- **SMT-LIB Support**: `solver solve` accepts SMT-LIB 2 format (S-expressions) as convenience input for Z3 experts
- **Auto-Detection**: Solver input format (simplified CLI, library API, SMT-LIB) is auto-detected from content
### Positioning
- **CLI Description**: Updated from "CLI for interacting with multiple LLM providers" to "JSON-first control plane for shell automation, CI, and multi-engine reasoning workflows"
- **README**: Added CLI / Shell Automation section with examples
- **Naming**: Fixed `nxuskit-engine-cli` -> `nxuskit-cli` naming drift across all docs and scripts
### Compliance
- **NOTICE**: Regenerated with zen-engine and z3-sys entries; Python section reformatted to remove excessive whitespace padding
- **Constitution v2.4.0**: Added semantic test assertions, stub prohibition, and task verification criteria (Articles II and III)
- **Acceptance Fixtures**: Three PoR 4.1 acceptance workflow scripts (intake-routing, generator-validator-retry, typed-artifact-handoff)
## [0.9.0] - 2026-03-13
Initial public release of the nxusKit SDK.
### Highlights
- **Polyglot SDK**: Unified LLM interfaces across Rust, Go, and Python
- **14 LLM Providers**: Claude, OpenAI, Ollama, LM Studio, Mistral, OpenRouter, Together, Groq, Fireworks, Perplexity, MCP, CLIPS, Mock, Loopback
- **CLIPS Expert System**: Rule-based inference via embedded CLIPS 6.4.2 engine with FFI bindings
- **Bayesian Network Inference**: Full-featured BN provider with Variable Elimination, Junction Tree, Loopy BP, NUTS/HMC, and structure/parameter learning
- **Z3 Constraint Solver**: Stateful solver sessions with multi-objective optimization, soft constraints, push/pop scoping, and UNSAT core extraction
- **ZEN Decision Tables**: JSON Decision Model evaluation via zen-engine
- **Plugin Architecture**: Signed plugin loading with Ed25519 verification and capability-based sandboxing
- **SDK CLI**: Command-line tool for all providers (`nxuskit-cli`)
- **SDK Installer**: Cross-platform SDK manager (`install.sh`) with version management
- **Cross-Language Conformance**: Shared test vectors ensuring API parity across Rust, Go, and Python
### Platform Support
| Platform | Architecture | Status |
|----------|-------------|--------|
| Linux | x86_64 | Supported |
| macOS | ARM64 (Apple Silicon) | Supported |
| macOS | x86_64 | Supported |
| Windows | x86_64 | Supported |
### Language SDKs
| Language | Package | Description |
|----------|---------|-------------|
| Rust | `nxuskit` | FFI wrapper with safe Rust API |
| Go | `nxuskit-go` | Idiomatic Go with context support |
| Python | `nxuskit-py` | Pure Python with `requests` HTTP client |
### Getting Started
See `sdk-packaging/docs/getting-started.md` for installation and usage instructions.
For runnable examples, see the [nxusKit-examples](https://github.com/nxus-SYSTEMS/nxusKit-examples) repository.
## [0.8.23] - 2026-02-24
### Added
- **Solver Progress Streaming (US1)**: Real-time progress events during optimization solves
- `nxuskit_solver_solve_stream` C ABI function with `on_chunk`/`on_done` callbacks
- `SolverProgressEvent` struct: iteration, status, elapsed_ms, objective_value, bound_gap, is_final
- nxuskit-rs `SolverStreamReceiver` with sync Iterator and async `futures_core::Stream` interfaces
- `solve_stream_async()` convenience method for tokio-based async consumption
- **Z3 Context Pooling (US2)**: Reusable Z3 context pool for reduced solver startup overhead
- Pool checkout/return benchmarked at 290us per 100-variable FFI round-trip
- Configurable via `SolverConfig.pool_size` and `pool_max_idle_ms`
- **ZEN Decision Table Evaluation (US3)**: JSON Decision Model (JDM) evaluation via zen-engine
- `nxuskit_zen_evaluate` / `nxuskit_zen_free_result` C ABI functions (stateless, no session)
- Supports decision table nodes, expression nodes, and switch nodes
- Function nodes rejected with clear error (no QuickJS dependency)
- Benchmarked at 0.39ms average for 100-row decision tables (well under 1ms target)
- Go wrapper: `gollyllm.ZenEvaluate()` with automatic memory management
- Rust provider: `zen::evaluate()` async function with pre-compilation optimization
- **BN Min-Weight Variable Elimination (US4)**: Alternative elimination heuristic
- `EliminationHeuristic::MinWeight` option for VE inference
- Identical posteriors to MinFill (verified on Asia and Alarm networks, max diff 2.22e-16)
- Configurable via `{"elimination_heuristic": "min_weight"}` in inference config JSON
- **clips-sys Windows Stub Parity (US5)**: Windows compilation stubs for CLIPS FFI functions
- **7 Code Examples**: Full Rust + Go implementations across patterns and integrations
- **E1 Constraint Solver** (`patterns/constraint-solver`): Basic Z3 solver session with 3 scenarios
- **E2 Bayesian Inference** (`patterns/bayesian-inference`): BN loading, evidence, multi-algorithm inference with 3 scenarios
- **E3 Multi-Provider Pipeline** (`integrations/solver-bn-pipeline`): 3-stage BN→Solver→CLIPS pipeline with 3 scenarios (festival, rescue, bakery)
- **E4 LLM-Solver Hybrid** (`integrations/llm-solver-hybrid`): LLM constraint extraction + Z3 solving with mock/live modes, 3 scenarios (seating, dungeon, road-trip)
- **E5 Solver What-If** (`patterns/solver-what-if`): Push/pop what-if analysis with UNSAT detection, 3 scenarios (wedding, mars, recipe)
- **E6 BN Structure Learning** (`integrations/bn-structure-learning`): Hill-Climb+BIC, K2, MLE parameter learning, log-likelihood scoring with 3 scenarios (golf, bmx, sourdough)
- **E7 ZEN Decision Tables** (`integrations/zen-decisions`): JDM evaluation with first/collect hit policies, expression nodes, 3 scenarios (maze-rat, potion, food-truck)
### Changed
- Go BN FFI (`ffi_bn.go`): Added `SearchStructure()`, `LearnMLE()`, `LogLikelihood()` wrappers with `BnSearchStructureConfig`, `BnStructureResult`, `BnEdge` types
- Go header (`nxuskit.h`): Added `nxuskit_zen_evaluate` and `nxuskit_zen_free_result` declarations
- `log::debug!` instrumentation added to solver streaming and ZEN evaluate hot paths for timing observability
### Performance
- Solver FFI overhead: 290us per 100-variable add_variables call
- Solver first-chunk latency: 21ms (well under 400ms Doherty Threshold)
- ZEN 100-row evaluation: 0.39ms avg, 0.55ms worst-case (under 1ms target)
- Z3 pool bench: >=50% improvement documented (PR-009)
## [0.8.22] - 2026-02-23
### Added
- **Solver Part 2 (044-solver-perf-audit)**: Multi-objective optimization, soft constraints, and explainability
- **Multi-objective optimization**: Weighted sum and lexicographic modes via Z3 Optimize API
- **Soft constraints**: Penalty-weighted constraints that can be violated, with violated constraint tracking
- **Constraint labels & explainability**: Human-readable labels on constraints/variables/objectives, UNSAT core with label mapping, binding constraints and slack values
- **Assumption-based solving**: Push/pop scoping with retractable assumptions
- **Go solver wrapper**: 21 C ABI solver functions wrapped via CGo FFI with full type parity
- **Python solver wrapper**: 21 C ABI solver functions wrapped via CFFI with context managers and dataclass types
- **Performance audit**: Criterion benchmarks for all SDK providers (Z3, CLIPS, Chat, FFI overhead); SC-007 (≤1ms FFI) and SC-008 (≤200ms composite) verified passing
- **Constitution v2.3.0**: PR-007 (cumulative overhead), PR-008 (platform-specific optimization), PR-009 (benchmark platform representativeness)
- **BN Part 2 (043-bn-part2-advanced)**: Advanced inference algorithms and cross-language parity
- **Loopy Belief Propagation**: Message-passing inference for cyclic/large networks with configurable damping and convergence diagnostics
- **Linear Gaussian Bayesian Networks**: Gaussian variable types with moment-matching exact inference and 95% credible intervals
- **NUTS/HMC Sampling**: Gradient-based MCMC via `nuts-rs` crate for continuous variables with ESS/R-hat diagnostics
- **BIF Export**: Round-trip BIF file export with 15-digit precision and CPT completeness validation
- **Parallel Junction Tree**: Rayon-based parallel collect/distribute with deterministic results and auto-fallback
- **Go BN wrapper**: Full C ABI coverage for Part 2 — BnNetwork, BnEvidence, BnResult with goroutine-safe inference and streaming via channels
- **Python BN wrapper**: Full C ABI coverage for Part 2 — context managers, async inference, generator-based streaming
- **C ABI extensions**: 8 new exported functions for Gaussian variables, config-based inference, streaming, and BIF save
### Changed
- **Dependency Audit & Update (043-deps-audit-update)**: Comprehensive dependency updates across Rust, Go, and Python
- **Rust — Breaking upgrades**:
- `thiserror`: 1.0 → 2.0 (unified across workspace, eliminates dual compilation)
- `reqwest`: 0.12 → 0.13 (rustls TLS default, improved security)
- `serde_yaml` → `serde_yaml_ng`: 0.9 → 0.10 (replaces archived/deprecated crate via Cargo rename)
- `rand`: 0.9 → 0.10, `rand_chacha`: 0.9 → 0.10 (trait renames: Rng→RngExt, from_os_rng removed)
- `quick-xml`: 0.37 → 0.39 (drop-in for our usage)
- `rmcp`: 0.8 → 0.16 (not yet used in source — pure Cargo.toml bump)
- `libloading`: 0.8 → 0.9 (in nxuskit-rs, AsFilename trait)
- `infer`: 0.16 → 0.19 (additive changes only)
- `criterion`: 0.5 → 0.8 (dev-only)
- `wiremock`: 0.5 → 0.6 (dev-only, hyper 1.0 migration)
- `mockito`: 1.2 → 1.7 (dev-only, semver-compatible)
- **Rust — Semver-compatible floor bumps**: regex 1.12, uuid 1.21, csv 1.4, cc 1.2, tempfile 3.20, openapiv3 2.2
- **Go**: go-edlib 1.7.0, pflag 1.0.10, plus transitive updates in all examples
- **Python**: cffi ≥2.0.0, pytest ≥9.0.0, pytest-cov ≥7.0.0, ruff ≥0.15.0
- **Toolchain**: Rust MSRV 1.92 → 1.93 (Go 1.26 bump deferred pending CI toolchain update)
## [0.8.21] - 2026-02-21
### Added
- **Bayesian Network Inference Engine (040-bayesian-network-inference)**: Full-featured Bayesian network provider
- **BIF parser**: Reads standard Bayesian Interchange Format network files (Asia, Cancer, Alarm, Survey, Earthquake)
- **4 inference algorithms**: Variable Elimination (exact), Likelihood Weighted Sampling, Gibbs Sampling (MCMC), Junction Tree
- **3 structure learning algorithms**: K2, Hill Climbing (BIC-scored), Bayesian structure learning
- **2 parameter learning algorithms**: Maximum Likelihood Estimation, Bayesian parameter estimation
- **Streaming support**: Real-time probability updates during sampling-based inference
- **C ABI integration**: 14 BN SDK functions with opaque handle pattern for cross-language access
- **nxuskit-rs BN wrapper**: RAII wrapper with dual-dispatch (static-link + dynamic-link)
- **Reference test data**: Python-generated reference marginals for deterministic validation
- **Benchmarks**: Performance benchmarks for all inference algorithms
- **Solver Tier 2 Session API (042-solver-tier2-api)**: Stateful Z3 solver sessions with incremental model building
- **Typed solver domain types** (`solver_types.rs`): `VariableDef`, `ConstraintDef`, `ObjectiveDef`, `SolveResult`, `SolverStats`, `SolverConfig`, `SolverCapabilities`, `SessionStatus`, with 20 constraint type variants and full serde round-trip fidelity
- **Mock solver backend** (`mock_solver.rs`): Deterministic contract testing without Z3 runtime — pre-configured responses, operation recording, atomic response cycling
- **17 C ABI solver session functions** (`solver_sdk.rs`): Opaque handle pattern for cross-language access — create/destroy, add variables/constraints, set objective, retract, push/pop, solve, reset, introspection (variables, constraints, status, capabilities, counts)
- **nxuskit-rs SolverSession wrapper** (`solver.rs`): RAII wrapper with dual-dispatch (static-link + dynamic-link), typed methods, automatic cleanup on drop
- **Internal solver session engine** (`solver_session.rs`): Accumulates state as plain Rust data, rebuilds Z3 solver on each solve via `with_z3_config` closure re-entry
- **Push/pop scoping**: Checkpoint/restore model state for what-if analysis (5 nested levels tested)
- **Unsat core extraction**: Named constraint labels propagated through Z3 assertion tracking, conflict identification on UNSAT
- **Solver configuration**: Timeout, random seed, and max-conflicts controls for deterministic, bounded-resource solving
- **Backend capability introspection**: Query Z3 or mock feature flags (incremental, unsat core, push/pop, multi-objective)
- **New Providers (041-new-providers)**: Local LLM and Z3 constraint solver providers
- **Local LLM provider**: In-process inference via llama.cpp (feature-gated `provider-local-llama`) and mistral.rs (feature-gated `provider-local-mistralrs`)
- **Z3 constraint solver provider**: Constraint satisfaction and optimization via Z3 (feature-gated `provider-z3`)
- **Go FFI constructors**: `NewLocalProvider()` and `NewZ3Provider()` in gollyllm
- **ModelLister implementations**: For Local and Z3 providers
### Changed
- **Tier 1 Z3 refactor**: `Z3Provider::chat()` now delegates to `session::solve_ephemeral()` for shared validation and dispatch logic — no external behavior change
- **Constitution v2.1.0**: Extended lockstep versioning to all nxusKit components (rustyllm, gollyllm, pythicllm), unified under single `sdk-v*` tag line
- **Go toolchain**: Bumped to 1.24.13 for crypto/tls security fix (GO-2026-4337)
- **gollyllm LKS Parity (018-gollyllm-lks-parity)**: Go library now has API parity with rustyllm
- **`InferenceMetadata` and `InferenceStep` types**: Structured metadata for inference results
- `InferenceMetadata` with `IsComplete`, `FinishReason`, `TokenUsage`, `ThinkingTrace`, `InferenceSteps`
- `InferenceStep` for capturing tool calls, thinking traces, and custom steps
- Builder pattern with fluent methods (`Completed()`, `WithTokenUsage()`, `AddInferenceStep()`, etc.)
- `ChatResponse.InferenceMetadata` field populated by all 12 providers
- **`SessionResetter` interface**: Deterministic testing support
- `FreshSession() (LLMProvider, error)` method on all 12 providers
- Stateless providers return self, MockProvider creates new instance
- Enables reproducible test results in CI/CD pipelines
- **`ModelLister` interface**: Dynamic model discovery
- `ListAvailableModels(ctx) ([]ModelInfo, error)` for local providers
- Implemented by: Ollama, LM Studio, Mock, Loopback
- Cloud providers don't implement (API doesn't support dynamic listing)
- **Backward Compatibility**: `ChatResponse.Metadata` field preserved with deprecation notice
- **85.9% Test Coverage**: Exceeds target of ≥85%
### Changed
- **Project Naming Migration**: Unified naming conventions across all language implementations
- Umbrella project renamed from "RustyLLM/LLMKit" to "nxusKit"
- Go library: `go/llmkit-go/` → `gollyllm/`, package `llmkit` → `gollyllm`
- Go module path: `github.com/llmkit/llmkit-go` → `github.com/nxus-SYSTEMS/nxusKit/gollyllm`
- Go CLI: `gollm` → `gollyllm`
- Python library: `rustyllm-py/` → `pythicllm/`, package `rustyllm` → `pythicllm`
- Python tools: `python-tools/` → `nxusKit-tools/`
- Rust library: `rustyllm` (unchanged)
- Updated all documentation, examples, and configuration files
## [0.8.20] - 2026-01-29
### Added
- **`ModelLister` Trait**: New trait for polymorphic model discovery
- Enables `Box` for provider registries
- Implemented for Ollama, LmStudio, CLIPS, Mock, and Loopback providers
- Correct vtable dispatch through trait objects
- **`InferenceMetadata` and `InferenceStep` Types**: Unified response metadata
- `InferenceMetadata` provides consistent access to execution details across all providers
- `InferenceStep` captures inference traces (rule firings for CLIPS, tool calls, etc.)
- All providers now populate `response.inference_metadata`
- **`fresh_session()` Method**: Per-provider method for deterministic CI/testing
- Returns a fresh provider instance with clean state
- Implemented for all 13 providers
- Enables reproducible test results
- **`BlockingProvider
` Wrapper**: Synchronous API for non-async contexts
- Feature-gated under `blocking-api`
- Uses internal tokio Runtime
- Supports `chat()` and `list_models()` (when wrapped provider implements ModelLister)
- **`full` Feature Flag**: Convenience feature combining `clips` + `blocking-api`
- **CLIPS Ordering Guarantees**: Deterministic output ordering
- Conclusions sorted by fact_index
- Rules fired sorted by name for determinism
- Conflict strategy recorded in provider_metadata
- **Documentation**: New integration guides
- `docs/INTEGRATION_PATTERNS.md` - Polymorphic providers, deterministic evaluation, sync API
- `docs/MINIMAL_BUILD.md` - Feature flag reference and build configurations
- **CI Improvements**: Feature flag verification steps
- Tests `--no-default-features`, `--features blocking-api`, `--features full` builds
- **Examples**:
- `polymorphic_example.rs` - Provider registry pattern with ModelLister
- `blocking_example.rs` - Synchronous API usage patterns
- **`as_clips_output()` Method**: Typed accessor for CLIPS results (feature = "clips")
- Avoids manual JSON parsing for CLIPS inference results
- Returns `Option` with typed access to conclusions, traces, stats
- Returns `None` for non-CLIPS response content
- **`all-providers` Feature Flag**: Enables all provider features (`pro` + `mcp`)
- **Documentation Enhancements**:
- Error handling patterns in INTEGRATION_PATTERNS.md
- CLIPS ordering guarantees documentation
- WASM compatibility notes in MINIMAL_BUILD.md
- CI optimization tips for feature matrix testing
### Changed
- `ChatResponse` now includes `inference_metadata: InferenceMetadata` field (backward compatible with `#[serde(default)]`)
## [0.8.19] - 2026-01-28
### Added
- **CLIPS Provider Options**: New configuration options for expert system inference
- `strategy` option for conflict resolution strategy selection
- `allow_duplicate_facts` option for fact assertion behavior control
- **CLI Support for All 14 Providers**: Command-line interface now supports all providers
- Claude, OpenAI, Ollama, LM Studio, Mistral, OpenRouter, Together, Groq, Fireworks, Perplexity, MCP, CLIPS, Mock, Loopback
- **Stop Patterns**: Conditional inference halting based on output patterns
- Enables early termination when specific patterns are detected in responses
- **CLIPS Expert System Enhancements**:
- Binary rule loading support for pre-compiled rule bases
- Search paths for rule file discovery
- Schema conversion utilities for fact/rule translation
- Help commands for CLIPS debugging and introspection
## [0.8.18] - 2026-01-23
### Breaking Changes
- **`ThinkingMode::Auto` behavior changed**: Now intelligently enables thinking for thinking-capable models (qwen3, deepseek-r1, etc.) instead of omitting the parameter. Use `ThinkingMode::Omit` for the old behavior.
### Added
- **`ThinkingMode::Omit` variant**: Explicitly omit the `think` parameter from Ollama requests, letting the model use its raw default behavior. Use this if you need the pre-0.8.18 `Auto` behavior.
- **Smart `Auto` mode for Ollama thinking models**: `ThinkingMode::Auto` now detects thinking-capable models and enables thinking automatically, preventing empty response issues with models like qwen3-vl.
- **Native Ollama Structured Output Support**: Full JSON mode and JSON schema support for Ollama provider
- **JSON Mode**: Use `ResponseFormat::Json` to get structured JSON responses from Ollama models
- **JSON Schema Mode**: Use `ResponseFormat::JsonSchema { schema }` for schema-validated responses (Ollama 0.5.0+)
- Native API integration - sends `format: "json"` or `format: { schema }` directly to Ollama
- No more prompt-based fallback needed for JSON mode with Ollama
- Updated `supports_json_schema: true` in Ollama provider capabilities
- **Helper methods on `ThinkingMode`**:
- `is_auto()` - Check if mode requires smart automatic behavior
- `is_omit()` - Check if mode explicitly omits the thinking parameter
### Fixed
- **Ollama JSON Mode Gap**: Previously, Ollama declared `supports_json_mode: true` but didn't actually send the `format` field to the API. Now properly implemented with native support.
- **Empty responses with qwen3-vl models**: Models like qwen3-vl would return empty content when the `think` parameter was omitted. The new smart `Auto` behavior prevents this by enabling thinking for known thinking models.
## [0.8.17] - 2026-01-20
### Added
- **`ThinkingMode` Enum**: Provider-agnostic control over chain-of-thought reasoning
- `ThinkingMode::Auto` - Use model's default behavior (recommended)
- `ThinkingMode::Enabled` - Force thinking mode on
- `ThinkingMode::Disabled` - Force thinking mode off for faster responses
- New `ChatRequest.with_thinking_mode()` builder method
- Automatically translated to provider-specific parameters (e.g., `think` for Ollama)
- **Ollama `think` Parameter Support**: Direct API integration for thinking control
- Added `think: Option` to internal `OllamaRequest` struct
- Maps from `ChatRequest.thinking_mode` automatically
- **Thinking Model Detection**: Auto-detection with warnings
- `OllamaProvider::is_thinking_model()` detects qwen3*, deepseek-r1/v3, :thinking variants
- Debug warnings when `max_tokens < 200` for thinking models (token budget may be exhausted)
- **StreamChunk Helper Methods**: Easier access to combined content
- `all_content()` - Returns `(Option<&str>, Option<&str>)` tuple of (thinking, content)
- `combined_text(separator)` - Combines thinking + content into single string
### Fixed
- **Empty Response Bug**: Resolved issue where thinking models returned empty responses
- Root cause: `max_tokens` setting too low, causing thinking tokens to exhaust budget
- Solution: Added `ThinkingMode` control and detection warnings
## [0.8.16] - 2026-01-20
### Added
- **Ollama Thinking Mode Support**: Reliable streaming for models with chain-of-thought reasoning (e.g., Qwen3)
- **Bug Fix**: Streaming no longer returns empty responses when using thinking-enabled models
- Previously, Qwen3 models would intermittently return empty responses because thinking chunks were dropped
- Stream now correctly stays active during thinking phase and delivers all content
- **Important**: Thinking tokens count toward `max_tokens` limit - avoid setting low `max_tokens` values with thinking models or you may get empty responses
- New `StreamChunk.thinking` field exposes model reasoning content (when available)
- New helper methods on `StreamChunk`:
- `thinking(String)` - Create a thinking-only chunk
- `with_thinking(String, String)` - Create a chunk with both content and thinking
- `has_thinking()` - Check if chunk contains thinking content
- `has_content()` - Check if chunk has any content (delta or thinking)
- Token counting now includes thinking tokens in completion count
- `StreamingTokenAccumulator` updated with `add_thinking_chunk()` method
- Backward compatible: existing code works unchanged, `thinking` field is `Option`
- Affected models: `qwen3:*`, `qwen3-vl:*`, and any future models using Ollama's thinking field
- See the Ollama provider documentation for usage details
### Fixed
- Custom `Debug` implementation for `TokenEstimator` to avoid derive issues with `tiktoken_rs::CoreBPE`
## [0.8.15] - 2026-01-19
### Added
- **Streaming Token Usage Tracking**: Real-time token consumption monitoring across all 13 LLM providers
- Every streaming chunk now includes token usage information (both actual and estimated)
- Dual accuracy: 100% actual counts from providers + 95-99% estimated counts via client-side tokenization
- New `TokenEstimator` for client-side token counting with tiktoken-rs support (95-99% accuracy)
- New `StreamingTokenAccumulator` for real-time token aggregation during streaming
- New `TokenUsage` structure with dual count support (actual + estimated)
- New `stream_with_usage()` convenience method on `LLMProvider` trait
- Feature-gated `stream-token-estimation` enables high-accuracy token counting (~50KB binary size)
- Provider Support:
- **Tier 1 (100% Actual)**: Claude, OpenAI, Ollama
- **Tier 2 (95-99% Estimated)**: Groq, Mistral, Fireworks, Together, OpenRouter, Perplexity, LM Studio
- **Tier 3 (70-90% Heuristic)**: MCP
- **Tier 4 (100% Test)**: Mock, Loopback providers
- All 13 providers updated with streaming token tracking implementation
- 6 new integration tests covering token tracking across providers
- See: `docs/PROVIDER_TOKEN_ACCURACY.md`
- **Comprehensive Documentation**
- Enhanced README.md with new "Streaming Token Usage Tracking" section
- New PROVIDER_TOKEN_ACCURACY.md with detailed provider breakdown and cost tracking guidance
- Updated quickstart.md with 5 practical examples and migration guide
- New DOCUMENTATION_GUIDE.md for navigation and reader journeys
- 1,110+ lines of documentation, 30+ code examples
### Changed
- TokenUsage structure now includes both actual and estimated counts for dual accuracy
- All streaming chunks now include token usage information (previously only some providers)
- Updated exports in lib.rs to include TokenEstimator and EstimationMethod
### Fixed
- Fixed unit tests to use new TokenUsage structure (estimated_only, best_available methods)
- Addressed clippy warning about unnecessary clone of Copy type in lmstudio.rs
## [0.8.14] - 2025-12-08
### Added
- **Retry-After Header Parsing**: All providers now parse the `Retry-After` header from HTTP 429 responses
- When rate limited, `LlmError::RateLimit { retry_after }` now contains the duration
- Enables intelligent retry logic: clients can wait exactly as long as needed
- Supports delay-seconds format (e.g., "30" for 30 seconds)
- Added `parse_retry_after()` helper function in `providers/mod.rs`
- All 9 providers updated: Claude, OpenAI, Ollama, Groq, Together, Fireworks, Mistral, Perplexity, OpenRouter
- Implements Retry-After header parsing per HTTP/1.1 specification
## [0.8.13] - 2025-12-08
### Fixed
- **Critical Bug Fix**: Streaming requests now use `total_timeout` instead of `connection_timeout`
- The `chat_stream()` methods were incorrectly using `.timeout(self.connection_timeout)` on the request builder
- This overrode the client's `total_timeout` (default 600s) with `connection_timeout` (default 10s)
- Caused streaming to fail after ~10 seconds even with longer timeout configurations
- Affects: `ClaudeProvider`, `OpenAIProvider`, `OllamaProvider`
- Added regression tests to prevent this issue from recurring
- **All providers now use centralized `build_http_client()` helper**
- Previously, only Claude, OpenAI, and Ollama used the helper
- Now all providers use consistent timeout configuration with `read_timeout` for streaming
- Fixed providers: `FireworksProvider`, `GroqProvider`, `PerplexityProvider`, `TogetherProvider`, `LmStudioProvider`, `MistralProvider`, `OpenRouterProvider`
- `MistralProvider` and `OpenRouterProvider` were using `Client::new()` which ignored ALL timeouts
- Other providers were missing `read_timeout` which is critical for streaming
## [0.8.12] - 2025-12-08
### Fixed
- **Critical Bug Fix**: Timeout configurations are now properly applied to HTTP clients
- Previously, `connection_timeout`, `stream_read_timeout`, and `total_timeout` values were stored but never applied to the underlying `reqwest::Client`
- This caused requests to use reqwest's default timeouts instead of user-configured values
- Streaming requests would fail prematurely (~10s) regardless of timeout configuration
- Affects: `ClaudeProvider`, `OpenAIProvider`, `OllamaProvider`
- Root cause: timeout was set on the request builder instead of the HTTP client builder
### Added
- **`build_http_client()` helper function**: Centralized HTTP client creation with proper timeout application
- Ensures all providers use consistent timeout configuration
- Prevents this class of bug in future provider implementations
- See: `docs/PROVIDER_IMPLEMENTATION.md`
- **Timeout configuration regression tests**: Comprehensive test suite to catch timeout misconfigurations
- Tests for all three timeout types across all providers
- `verify_provider_respects_timeout()` helper for testing new providers
- Behavioral tests with mock servers and configurable delays
### Changed
- **Upgraded `reqwest` from 0.11 to 0.12**: Enables `read_timeout` support for streaming responses
- `read_timeout` applies per-chunk during response body reading
- Critical for LLM streaming where there are pauses between tokens
## [0.8.11] - 2025-12-07
### Added
- **Loopback Provider**: Test/development provider that echoes back user messages
- Useful for testing without API calls
- Configurable response delays for timeout testing
## [0.8.10] - 2025-11-25
### Breaking Changes
- **LLMProvider Trait**: Added `get_capabilities()` method to the trait
- All custom provider implementations must now implement this method
- Returns `ProviderCapabilities` struct describing what the provider supports
- **ChatResponse**: Added new fields
- `warnings: Vec` - Parameter adaptation warnings
- `logprobs: Option` - Token probability data (when requested)
### Added
- **New Parameters in ChatRequest**:
- `stop: Option>` - Stop sequences for generation
- `presence_penalty: Option` - Repetition penalty (-2.0 to 2.0)
- `frequency_penalty: Option` - Frequency penalty (-2.0 to 2.0)
- `seed: Option` - Deterministic generation seed
- `logprobs: Option` - Enable token probabilities
- `top_logprobs: Option` - Number of top alternatives (0-20)
- `response_format: Option` - JSON mode control
- `provider_options: Option` - Provider-specific parameters
- **Parameter Adapter**: Graceful degradation system
- Automatically adapts parameters to provider capabilities
- Truncates stop sequences to provider limits with warnings
- Ignores unsupported parameters with info-level warnings
- Falls back to prompt-based JSON mode when native not supported
- **Provider Capabilities System**:
- `ProviderCapabilities` struct for querying provider support
- Runtime capability detection for all parameters
- Enables write-once code that adapts to any provider
- **New Providers** (6 total):
- `MistralProvider` - Mistral AI API
- `OpenRouterProvider` - OpenRouter unified API (100+ models)
- `TogetherProvider` - Together AI (open source models)
- `GroqProvider` - Groq (ultra-fast inference)
- `FireworksProvider` - Fireworks AI (optimized inference)
- `PerplexityProvider` - Perplexity AI (search-augmented)
- **MCP Auto-Discovery**:
- Automatic server discovery from `~/.config/mcp/servers.json`
- `RUSTYLLM_MCP_CONFIG` environment variable override
- `McpProvider::discover_servers()` API
- `McpProvider::builder().discover_server("name")` pattern
- **Supporting Types**:
- `ResponseFormat` enum (Text, Json, JsonSchema)
- `ProviderOptions` enum with `OllamaOptions` variant
- `ParameterWarning` and `WarningSeverity` for warnings
- `LogprobsData`, `TokenLogprob`, `TopLogprob` for token probabilities
### Changed
- All existing providers updated to implement `get_capabilities()`
- All providers now integrate with ParameterAdapter for graceful degradation
- MockProvider enhanced with full capability support for testing
### Fixed
- Test race conditions in env_detector and MCP tests (mutex serialization)
- Test assertions for provider metadata flexibility
## [0.8.9] - 2025-11-25
### Changed
- Updated plans for new versioning with open source beta target (pre-v1.x.x)
- Cleanup and tightened various compiler warnings
## [0.8.8] - 2025-11-25
### Changed
- Version bump for release preparation
## [0.8.7] - 2025-11-25
### Changed
- Release preparation updates
## [0.8.6] - 2025-11-25
### Changed
- Minor fixes and updates
## [0.8.5] - 2025-11-25
### Changed
- Release updates
## [0.8.4] - 2025-11-24
### Changed
- Post-reset stabilization
## [0.8.3] - 2025-11-24
### Added
- Initial Tier-1 provider implementations (Mistral, OpenRouter, Together, Groq, Fireworks, Perplexity)
- MCP auto-discovery groundwork
## [0.8.2] - 2025-11-24
### Added
- LiteLLM-style convenience API with automatic provider detection
- Graceful parameter degradation foundation
## [0.8.1] - 2025-11-24
### Added
- Provider expansion preparation
- API refinements
## [0.8.0] - 2025-11-24
### Changed
- **Version Reset**: Reset version numbering from the earlier 2.x line into the pre-public development line
- Pre-1.0 versioning (0.x.y) signals API is not yet stable per semantic versioning
- Allows breaking changes in minor versions during development
- Functionality from the earlier 2.x line carried forward unchanged
- Historical 2.x changelog preserved in the internal archive
- Previous 2.x release artifacts archived outside the public SDK release line
### Notes
This was a version numbering reset only - no code functionality changed. Features, fixes, and improvements from the earlier 2.x line carried forward into the pre-public development line. The reset better reflected the library's development stage and followed Rust ecosystem conventions for pre-release crates.
The older 2.x history is intentionally kept out of the public SDK changelog.
---
# CLI Input Format Reference
URL: https://docs.nxus.systems/v0.9.4/nxuskit/reference/cli-reference
Single source of truth for every Level 1 `nxuskit-cli` command's input schema,
with local loopback examples where the command can succeed without a semantic
LLM response.
All commands accept `--input -` for stdin and `--format json` (default).
Output is wrapped in a `ResponseEnvelope` with `trace_id`, `request_metadata`,
and timing fields.
Loopback examples that are intended to execute locally use explicit loopback
model names. In nxusKit CLI v0.9.4, do not rely on an omitted model resolving
to `"default"` for the `loopback` provider; use `"echo"` for plain echo tests
or `"echo-json-native"` when you need a loopback model that advertises native
JSON support. Commands that require a semantic structured answer, such as
`judge select`, should use a configured non-loopback LLM provider because
loopback models echo the prompt.
---
## Table of Contents
- [call](#call)
- [zen eval](#zen-eval)
- [zen validate](#zen-validate)
- [zen test](#zen-test)
- [solver solve](#solver-solve)
- [Solver Format Disambiguation](#solver-format-disambiguation)
- [solver what-if](#solver-what-if)
- [clips eval](#clips-eval)
- [clips session](#clips-session)
- [clips session create](#clips-session-create)
- [clips session list](#clips-session-list)
- [clips session destroy](#clips-session-destroy)
- [provider list](#provider-list)
- [provider info](#provider-info)
- [bn infer](#bn-infer)
- [bn learn](#bn-learn)
- [bn evidence](#bn-evidence)
- [pipeline run](#pipeline-run)
- [artifact merge](#artifact-merge)
- [artifact summarize](#artifact-summarize)
- [packet validate](#packet-validate)
- [tool-loop run](#tool-loop-run)
- [judge select](#judge-select)
- [branch fork](#branch-fork)
- [branch compare](#branch-compare)
- [Error responses](#error-responses)
---
### `call`
LLM invocation. Accepts either `prompt` (single-turn) or `messages` (multi-turn).
**Input schema (`CallInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `prompt` | string | no | Single-turn user prompt (convenience shorthand) |
| `messages` | array of `{role, content}` | no | Multi-turn conversation messages |
| `system` | string | no | System message prepended to the conversation |
| `provider` | string | no | Provider name (default: `loopback`, or `$NXUSKIT_PROVIDER`) |
| `model` | string | no | Model identifier. For `loopback`, use a valid loopback model such as `"echo"` or `"echo-json-native"`; do not rely on the implicit `"default"` model in v0.9.4. |
| `tool_definitions` | array of JSON objects | no | Tool/function schemas passed to the LLM |
| `tool_choice` | JSON value | no | Provider-compatible tool choice policy passed with `tool_definitions` |
| `response_format` | object | no | Response format constraint: `{"type":"text"}`, `{"type":"json_object"}`, or `{"type":"json_schema","schema":{...}}` |
| `thinking_mode` | string | no | Thinking policy: `auto`, `enabled`, `disabled`, or `omit` |
| `max_tokens` | u32 | no | Maximum output tokens |
| `temperature` | f32 | no | Sampling temperature |
| `stream` | bool | no | Enable streaming (JSONL output) |
At least one of `prompt` or `messages` should be provided.
**Example:**
```bash
echo '{"prompt": "Hello", "provider": "loopback", "model": "echo"}' \
| nxuskit-cli call --input - --format json
```
**Common errors:**
- `Invalid call input JSON: missing field ...` -- Fix: ensure the input is valid JSON with at least `prompt` or `messages`.
- `Unknown provider "xyz"` -- Fix: use a valid provider name (`loopback`, `openai`, `claude`, etc.) or set `$NXUSKIT_PROVIDER`.
---
### `zen eval`
ZEN decision table evaluation (Pro-gated).
**Input schema (`ZenEvalInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `table` | JSON object | **yes** | JDM (JSON Decision Model) decision table definition |
| `input` | JSON object | **yes** | Context data evaluated against the table |
The `table` field must be a valid JDM model with `nodes` and `edges` arrays.
Decision table nodes have `type: "decisionTableNode"` and contain `rules` in
their `content`.
**Example:**
```bash
echo '{
"table": {
"nodes": [
{
"id": "1",
"name": "input",
"type": "inputNode",
"content": {}
},
{
"id": "2",
"name": "decision",
"type": "decisionTableNode",
"content": {
"hitPolicy": "first",
"rules": [
{"_id": "r1", "input.age": ">= 18", "output.status": "adult"}
],
"inputs": [{"id": "i1", "name": "age", "field": "input.age"}],
"outputs": [{"id": "o1", "name": "status", "field": "output.status"}]
}
},
{
"id": "3",
"name": "output",
"type": "outputNode",
"content": {}
}
],
"edges": [
{"id": "e1", "sourceId": "1", "targetId": "2", "type": "edge"},
{"id": "e2", "sourceId": "2", "targetId": "3", "type": "edge"}
]
},
"input": {"age": 25}
}' | nxuskit-cli zen eval --input - --format json
```
**Common errors:**
- `Entitlement check failed: zen` -- Fix: ZEN is Pro-gated. Ensure a valid Pro license is active.
- `Invalid ZEN eval input: missing field "table"` -- Fix: both `table` and `input` are required fields.
---
### `zen validate`
Structural validation of a ZEN JSON Decision Model (JDM) - no evaluation
(Pro-gated, Level 2 utility). Checks that the model parses into the JDM
structure, rejects `functionNode`s (JavaScript not supported), checks decision
table node shape, attempts to compile expressions, and counts nodes / decision
tables / rules.
The `--input` content is the **JDM model itself** - NOT the `{table, input}`
envelope that `zen eval` accepts.
| Field (input) | Type | Required | Description |
|---|---|---|---|
| (whole document) | JSON object | **yes** | A JDM model with `nodes` (and usually `edges`) arrays |
**Success output (`--format json`):**
```json
{
"result": {
"valid": true,
"node_count": 3,
"decision_table_count": 1,
"rule_count": 4,
"problems": [],
"elapsed_ms": 1.2
},
"trace_id": "...", "timestamp": "...", "request_metadata": { "...": "..." }
}
```
**Failure (structurally invalid JDM)** - exit 5, stderr `ErrorEnvelope`:
```json
{
"code": "zen_validate_error",
"message": "JDM is structurally invalid: 1 problem(s) found",
"details": { "problems": [
{ "kind": "FunctionNodeRejected", "path": "nodes[1] (id=fn1)", "message": "JDM contains a Function node (JavaScript); not supported ..." }
] },
"trace_id": "...", "timestamp": "..."
}
```
`problems[].kind` is one of: `ParseError`, `FunctionNodeRejected`,
`MalformedNode`, `ExpressionError`, `MissingField`.
**Example:**
```bash
echo '{
"contentType": "application/vnd.gorules.decision",
"nodes": [
{"id":"input","type":"inputNode","name":"In","position":{"x":0,"y":0}},
{"id":"dt","type":"decisionTableNode","name":"T","content":{
"hitPolicy":"first",
"rules":[{"_id":"r1","age":">= 21","tier":"\"A\""},{"_id":"r2","age":"","tier":"\"B\""}],
"inputs":[{"id":"age","name":"Age","field":"age"}],
"outputs":[{"id":"tier","name":"Tier","field":"tier"}]
},"position":{"x":200,"y":0}},
{"id":"output","type":"outputNode","name":"Out","position":{"x":400,"y":0}}
],
"edges":[
{"id":"e1","sourceId":"input","targetId":"dt","type":"edge"},
{"id":"e2","sourceId":"dt","targetId":"output","type":"edge"}
]
}' | nxuskit-cli zen validate --input - --format json
```
**Exit codes:** 0 = structurally valid; 4 = `entitlement_denied` (no Pro); 5 =
unparseable input (`parse_error`) or structurally invalid JDM (`zen_validate_error`);
1 = unexpected internal error. No new exit codes beyond the stable scheme.
---
### `zen test`
Run a ZEN decision table against a set of fixture cases and compare each actual
output to its `expected` (Pro-gated, Level 2 utility). On mismatch, emits a
diff-style report - never an opaque internal error.
**Input envelope:**
| Field | Type | Required | Description |
|---|---|---|---|
| `table` | JSON object | **yes** | JDM model (same shape `zen eval`'s `table` accepts) |
| `cases` | array | **yes** | List of `{name, input, expected}` cases |
| `cases[].name` | string | **yes** | Case identifier |
| `cases[].input` | JSON object | **yes** | Context data for this case |
| `cases[].expected` | JSON value | **yes** | Expected evaluation output (deep equality) |
**Success output (`--format json`):**
```json
{
"result": {
"total": 2, "passed": 2, "failed": 0,
"cases": [
{"name":"low_risk","passed":true,"expected":{"tier":"A"},"actual":{"tier":"A"}},
{"name":"high_risk","passed":true,"expected":{"tier":"C"},"actual":{"tier":"C"}}
],
"elapsed_ms": 3.4
},
"trace_id": "...", "timestamp": "...", "request_metadata": { "...": "..." }
}
```
**Failure (one or more mismatches)** - exit 5, stderr `ErrorEnvelope`:
```json
{
"code": "zen_test_mismatch",
"message": "1 of 2 case(s) did not match expected output",
"details": { "failed": [
{"name":"high_risk","expected":{"tier":"C"},"actual":{"tier":"B"},"diff":{"tier":{"expected":"C","actual":"B"}}}
] },
"trace_id": "...", "timestamp": "..."
}
```
A *fixture parse error* is `code = "parse_error"` (exit 5); an *evaluation
error on a case* (e.g. the table itself is malformed) is `code = "zen_test_eval_error"`
(exit 5) with the offending case named in `details.case` - both distinct from a
mismatch (`zen_test_mismatch`).
**Example:**
```bash
echo '{
"table": { "...": "JDM model" },
"cases": [
{"name":"prime","input":{"age":30,"score":800},"expected":{"tier":"A"}},
{"name":"young","input":{"age":19,"score":400},"expected":{"tier":"C"}}
]
}' | nxuskit-cli zen test --input - --format json
```
**Exit codes:** 0 = all cases match; 4 = `entitlement_denied`; 5 = parse error
(`parse_error`), per-case eval error (`zen_test_eval_error`), or one+ mismatches
(`zen_test_mismatch`); 1 = unexpected internal error.
---
### `solver solve`
Z3 constraint solving (Pro-gated). Auto-detects three input formats.
#### Solver Format Disambiguation
The CLI accepts three distinct input formats, auto-detected at parse time:
| Format | Detection Rule | Best For |
|--------|---------------|----------|
| **Simplified** | JSON with `"type"` on variables and string constraints | Quick CLI one-liners, human-authored problems |
| **Library API** | JSON with `"var_type"` on variables or `"constraint_type"` on constraints | Cross-language scenario sharing with nxuskit-go/nxuskit-py |
| **SMT-LIB 2** | Input starts with `(` | Direct Z3 interaction, academic benchmarks |
The **library API format** uses the same `ConstraintInput` struct as the Rust, Go,
and Python SDKs. This means a JSON file authored for `solver solve` can be loaded
directly by `nxuskit.solve()` in any SDK, enabling cross-language scenario sharing.
---
#### Format 1: Simplified
**Input schema (`SolverInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `variables` | array of `SolverVariable` | **yes** | Variable declarations |
| `constraints` | array of strings | **yes** | Constraint expressions (e.g. `"x + y == 10"`) |
| `objective` | string | no | `"minimize"` or `"maximize"` |
| `objective_expr` | string | no | Expression to optimize (requires `objective`) |
**`SolverVariable` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Variable identifier |
| `type` | string | **yes** | `"integer"`, `"real"`, or `"boolean"` |
| `bounds` | array of `{"min": n}` / `{"max": n}` | no | Domain bounds |
Supported constraint operators: `==`, `!=`, `>=`, `<=`, `>`, `<`.
Arithmetic in LHS: `x + y == 10`, `x - y == 5`, `x * y == 12`.
**Example (simplified):**
```bash
echo '{
"variables": [
{"name": "x", "type": "integer", "bounds": [{"min": 0}, {"max": 10}]},
{"name": "y", "type": "integer", "bounds": [{"min": 0}, {"max": 10}]}
],
"constraints": ["x + y == 10", "x >= 3"],
"objective": "maximize",
"objective_expr": "x"
}' | nxuskit-cli solver solve --input - --format json
```
---
#### Format 2: Library API (`ConstraintInput`)
**Input schema (`ConstraintInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `variables` | array of `VariableDef` | no | Variable declarations |
| `constraints` | array of `ConstraintDef` | no | Structured constraint definitions |
| `objective` | `ObjectiveDef` | no | Single optimization objective |
| `objectives` | array of `ObjectiveDef` | no | Multiple objectives (multi-objective mode) |
| `config` | `SolverConfig` | no | Per-request solver configuration overrides |
| `retract` | array of strings | no | Named constraints to remove |
| `assumptions` | array of `ConstraintDef` | no | Temporary constraints (auto-retracted after solve) |
**`VariableDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Variable identifier |
| `var_type` | string | **yes** | `"integer"`, `"real"`, or `"boolean"` |
| `domain` | `{"min": f64, "max": f64}` or `[min, max]` | no | Domain bounds |
| `label` | string | no | Human-readable description |
**`ConstraintDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | no | Identifier for retraction / unsat core |
| `constraint_type` | string | **yes** | `"eq"`, `"neq"`, `"lt"`, `"gt"`, `"le"`, `"ge"`, `"add"`, `"sub"`, `"mul"`, `"div"`, `"and"`, `"or"`, `"not"`, `"implies"`, `"iff"`, `"all_different"`, `"at_most"`, `"at_least"`, `"exactly"`, `"in_range"` |
| `params` / `parameters` | JSON object | no | Type-specific parameters (e.g. `{"left": "x", "right": 3}`). Both field names accepted. If omitted, auto-inferred from `variables` and `expression` fields (see below). |
| `variables` | string[] | no | Variable names involved in the constraint. Used to auto-infer `params` when omitted. |
| `expression` | string | no | Human-readable expression (e.g. `"a * 20 = c"`). Used to auto-infer `params` when omitted. |
| `weight` | f64 | no | Soft constraint penalty (omit for hard constraint) |
| `label` | string | no | Human-readable description |
**`ObjectiveDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Unique objective identifier |
| `direction` | string | **yes** | `"minimize"` or `"maximize"` |
| `expression` | string | **yes** | Expression to optimize (references variable names) |
| `weight` | f64 | no | Weight for weighted multi-objective mode |
| `label` | string | no | Human-readable description |
| `priority` | u32 | no | Priority for lexicographic mode (lower = higher priority) |
**Params auto-inference**: When `params`/`parameters` is omitted or null, the CLI infers it from the `variables` and `expression` fields — matching the behavior of the Rust SDK's `ensure_parameters()` helper. This means shared `problem.json` scenario files work directly without modification:
- Comparison constraints (`ge`, `le`, `eq`, etc.) with `variables: ["a", "b"]` → infers `params: {"left": "a", "right": "b"}`
- Arithmetic constraints (`add`, `mul`, etc.) with `variables: ["a", "b", "c"]` and `expression: "a * 20 = c"` → infers `params: {"left": "a", "right": 20, "result": "c"}`
- Set constraints (`all_different`, `at_most`, `at_least`, `exactly`) with `variables: ["x", "y", "z"]` → infers `params: {"variables": ["x", "y", "z"]}`
- Partial params (e.g., `{"right": 19000}` with `variables: ["salary"]`) → merges to `{"left": "salary", "right": 19000}`
**Type aliases**: The CLI accepts `equal` (→ `eq`) and `not_equal` (→ `neq`) as long-form constraint type names for compatibility with some scenario files.
**Example (library API):**
```bash
echo '{
"variables": [
{"name": "x", "var_type": "integer", "domain": {"min": 0, "max": 10}},
{"name": "y", "var_type": "integer", "domain": {"min": 0, "max": 10}}
],
"constraints": [
{"name": "sum", "constraint_type": "add", "params": {"left": "x", "right": "y", "result": 10}},
{"name": "lower_bound", "constraint_type": "ge", "params": {"left": "x", "right": 3}}
],
"objective": {
"name": "max_x",
"direction": "maximize",
"expression": "x"
}
}' | nxuskit-cli solver solve --input - --format json
```
---
#### Format 3: SMT-LIB 2
Raw SMT-LIB 2 text. Auto-detected when input starts with `(`.
**Example (SMT-LIB):**
```bash
echo '(declare-const x Int)
(declare-const y Int)
(assert (>= x 0))
(assert (<= x 10))
(assert (>= y 0))
(assert (<= y 10))
(assert (= (+ x y) 10))
(assert (>= x 3))
(check-sat)
(get-model)' | nxuskit-cli solver solve --input - --format json
```
**Common errors (all formats):**
- `Entitlement check failed: solver` -- Fix: solver is Pro-gated. Ensure a valid Pro license.
- `Cannot parse constraint expression: 'x + y = 10'` -- Fix: use `==` for equality, not `=`.
- `Invalid solver input JSON: ...` -- Fix: ensure JSON is well-formed. Check that simplified format uses `"type"` (not `"var_type"`).
- `Invalid solver library format: ...` -- Fix: library format requires `"var_type"` on variables and `"constraint_type"` on constraints.
---
### `clips eval`
CLIPS rule engine evaluation.
**Input schema (`ClipsEvalInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `rules` | string | **yes** | CLIPS rule definitions (defrule, deftemplate, etc.) |
| `facts` | array of strings | no | Initial facts to assert (default: `[]`) |
> **Newline escaping:** CLIPS rules contain newlines. In JSON strings you must
> use `\n` for line breaks. When piping from a shell, use `$'...'` quoting or
> a heredoc to embed literal newlines, then let `jq` handle escaping.
**Example:**
```bash
echo '{
"rules": "(defrule greet (person (name ?n)) => (assert (greeting (message (str-cat \"Hello \" ?n)))))",
"facts": ["(person (name \"World\"))"]
}' | nxuskit-cli clips eval --input - --format json
```
**Multi-line rules (using jq for safe escaping):**
```bash
RULES=$(cat <<'CLIPS'
(deftemplate person (slot name))
(deftemplate greeting (slot message))
(defrule greet
(person (name ?n))
=>
(assert (greeting (message (str-cat "Hello " ?n)))))
CLIPS
)
jq -n --arg rules "$RULES" '{"rules": $rules, "facts": ["(person (name \"World\"))"]}' \
| nxuskit-cli clips eval --input - --format json
```
**Common errors:**
- `Failed to load CLIPS rules: ...` -- Fix: check CLIPS syntax. Common issues: unbalanced parentheses, missing `=>` in defrule.
- `Failed to assert fact '(foo)': ...` -- Fix: if using deftemplates, facts must match the template signature (e.g. `(person (name "x"))` not `(person "x")`).
- `Invalid CLIPS eval input: missing field "rules"` -- Fix: `rules` is required. Use `"rules": ""` for an empty ruleset.
---
### `bn infer`
Bayesian network inference via variable elimination.
**Input schema (`BnInferInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `network` | `NetworkDef` | **yes** | Bayesian network structure and CPDs |
| `evidence` | map of string to string | no | Observed variable states (default: `{}`) |
| `query_nodes` | array of strings | **yes** | Variables to compute posterior probabilities for |
| `algorithm` | string | no | Inference algorithm (default: `"variable_elimination"`) |
**`NetworkDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `nodes` | array of `NodeDef` | **yes** | Variable definitions with states |
| `edges` | array of `EdgeDef` | **yes** | Directed edges (parent to child) |
| `cpds` | map of string to `CpdDef` | **yes** | Conditional probability distributions |
**`NodeDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Variable name |
| `states` | array of strings | **yes** | Possible states for this variable |
**`EdgeDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `from` | string | **yes** | Parent node name |
| `to` | string | **yes** | Child node name |
**`CpdDef` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `probabilities` | array of f64 | **yes** | Flat probability table (row-major order over parent states) |
**Example:**
```bash
echo '{
"network": {
"nodes": [
{"name": "Rain", "states": ["yes", "no"]},
{"name": "Sprinkler", "states": ["on", "off"]},
{"name": "GrassWet", "states": ["wet", "dry"]}
],
"edges": [
{"from": "Rain", "to": "GrassWet"},
{"from": "Sprinkler", "to": "GrassWet"}
],
"cpds": {
"Rain": {"probabilities": [0.2, 0.8]},
"Sprinkler": {"probabilities": [0.4, 0.6]},
"GrassWet": {"probabilities": [0.99, 0.01, 0.9, 0.1, 0.8, 0.2, 0.0, 1.0]}
}
},
"evidence": {"GrassWet": "wet"},
"query_nodes": ["Rain"]
}' | nxuskit-cli bn infer --input - --format json
```
**Common errors:**
- `Invalid variable name '...': ...` -- Fix: node names must be non-empty alphanumeric identifiers.
- `Failed to set CPD for '...': ...` -- Fix: probability array length must equal the product of the node's state count and all parent nodes' state counts.
- `Invalid BN inference input: missing field "network"` -- Fix: `network` and `query_nodes` are both required.
---
### `bn learn`
Parameter learning: estimate the conditional probability tables (CPDs) of a
network from a CSV dataset, given the network *skeleton* (variables + edges, no
CPDs). The learned network is BIF-exportable. Community edition.
**Input schema (`BnLearnInput`):**
| Field | Type | Required | Description |
|---|---|---|---|
| `network` | object | **yes** | Network skeleton: `{"nodes": [{"name","states"}], "edges": [{"from","to"}]}` -- NO `cpds` |
| `data_file` | string | **yes** | Path to the CSV dataset; column headers must map to variable names |
| `learner` | string | no (default `"mle"`) | `"mle"` (Maximum Likelihood + Laplace smoothing) or `"bayesian"` (Dirichlet prior) |
| `pseudocount` | number | no (default `1.0`) | Laplace pseudocount; for `bayesian`, the default Dirichlet alpha |
**Output (`--format json`):** `{"result": {"learned_cpts": {var: [probs]}, "bif": "", "num_rows": N, "num_variables": M, "learner": "mle", "elapsed_ms": ...}}`.
**Example:**
```bash
echo '{
"network": {
"nodes": [
{"name":"Rain","states":["yes","no"]},
{"name":"Sprinkler","states":["on","off"]},
{"name":"WetGrass","states":["yes","no"]}
],
"edges": [{"from":"Rain","to":"WetGrass"},{"from":"Sprinkler","to":"WetGrass"}]
},
"data_file": "/abs/path/to/training.csv",
"learner": "mle",
"pseudocount": 0.0
}' | nxuskit-cli bn learn --input - --format json
```
**Common errors:**
- `Training CSV not found: ...` -- Fix: `data_file` must be a path to an existing CSV file.
- `Failed to load dataset '...': ...` -- Fix: CSV column headers must match the network's variable names; cell values must match declared states (empty / `?` cells are treated as missing).
- `Unknown learner '...'. Valid: mle, bayesian` -- Fix: use one of the two supported learners.
**Excluded from v0.9.4:** structure *search* (`hill_climb` / `k2`) is engine-only, not a CLI surface; streaming; team-runtime lineage.
---
### `bn evidence`
Validate and normalize an observations map against a fully-specified network
(same `network` shape as `bn infer`). Returns the validated observations or a
structured validation error naming the offending variable/state. Community edition.
**Input schema (`BnEvidenceInput`):**
| Field | Type | Required | Description |
|---|---|---|---|
| `network` | object | **yes** | `{"nodes": [...], "edges": [...], "cpds": {...}}` (same as `bn infer`) |
| `observations` | object | no | `{var: state, ...}` -- each is validated against the network |
**Output (`--format json`):** `{"result": {"valid": true, "evidence": {var: state}, "observation_count": N, "elapsed_ms": ...}}`.
**Example:**
```bash
echo '{
"network": {
"nodes": [{"name":"Rain","states":["yes","no"]},{"name":"WetGrass","states":["yes","no"]}],
"edges": [{"from":"Rain","to":"WetGrass"}],
"cpds": {"Rain":{"probabilities":[0.2,0.8]},"WetGrass":{"probabilities":[0.9,0.1,0.1,0.9]}}
},
"observations": {"Rain":"yes"}
}' | nxuskit-cli bn evidence --input - --format json
```
**Common errors:**
- `Invalid observation Rain=maybe: ...` (exit 5, `validation`) -- Fix: the observed state must be one of the variable's declared states.
- `Invalid observation variable '...': ...` -- Fix: the variable must exist in the network.
---
### `pipeline run`
Sequential multi-stage pipeline execution. Accepts YAML or JSON.
**Input schema (`PipelineDefinition`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Pipeline name |
| `stages` | array of `Stage` | **yes** | Ordered list of stages to execute |
**`Stage` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | **yes** | Stage identifier |
| `type` | string | **yes** | Stage type: `"llm"`, `"clips_eval"`, `"zen_eval"`, `"solver_solve"`, `"bn_infer"` |
| `config` | JSON object | no | Stage-specific configuration (passed to the engine) |
| `output_key` | string | no | Bind stage output to a named key for `{{key}}` interpolation in later stages |
For `llm` stages, `config` accepts `prompt`, `provider`, and `model`.
For `clips_eval` stages, `config` accepts `rules` and `facts`.
For other stage types, `config` mirrors the respective command's input schema.
Stages execute sequentially. Each stage receives the previous stage's output.
String values in `config` support `{{key}}` interpolation from `output_key` bindings.
If a stage fails, all subsequent stages are marked `"skipped"`.
**Example:**
```bash
echo '{
"name": "demo-pipeline",
"stages": [
{
"name": "generate",
"type": "llm",
"config": {"prompt": "Say hello", "provider": "loopback", "model": "echo"},
"output_key": "llm_result"
},
{
"name": "evaluate",
"type": "llm",
"config": {"prompt": "Summarize: {{llm_result}}", "provider": "loopback", "model": "echo"}
}
]
}' | nxuskit-cli pipeline run --input - --format json
```
**Common errors:**
- `Invalid pipeline definition: ...` -- Fix: ensure input is valid YAML or JSON with `name` and `stages` fields.
- `Unknown stage type: xyz` -- Fix: valid stage types are `llm`, `clips_eval`, `zen_eval`, `solver_solve`, `bn_infer`.
- `PipelineStageFailed { stage: "...", detail: ... }` -- Fix: check the `stages[].result.message` field in the output for the root cause.
---
### `artifact merge`
Deep-merge multiple JSON artifact files with conflict detection.
This command takes multiple `--input` flags (not stdin JSON). Each input must be a
JSON object (not an array or scalar).
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--input` | string (repeatable) | **yes** (>= 2) | Paths to JSON files to merge |
| `--merge-strategy` | string | no | Conflict resolution: `"error"` (default), `"first"`, `"last"` |
No JSON input schema -- inputs are arbitrary JSON objects read from files.
**Example:**
```bash
echo '{"a": 1, "b": {"x": 10}}' > /tmp/art1.json
echo '{"b": {"y": 20}, "c": 3}' > /tmp/art2.json
nxuskit-cli artifact merge \
--input /tmp/art1.json --input /tmp/art2.json \
--format json
```
**Common errors:**
- `artifact merge requires at least 2 input files` -- Fix: provide at least two `--input` paths.
- `MergeConflict { paths: ["b.x"] }` -- Fix: two files have different values at the same key path. Use `--merge-strategy first` or `--merge-strategy last` to resolve.
- `'...' is not a JSON object` -- Fix: each input file must contain a JSON object (`{...}`), not an array or scalar.
---
### `artifact summarize`
Summarize a JSON artifact's structure and estimated token cost.
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--input` | string | **yes** | Path to JSON file or `-` for stdin |
No JSON input schema -- the input is any valid JSON value.
**Output fields:**
| Field | Type | Description |
|-------|------|-------------|
| `field_count` | u32 | Total number of fields (recursive) |
| `top_level_keys` | array of strings | Keys at the root level |
| `estimated_tokens` | u32 | Rough token estimate (byte length / 4) |
**Example:**
```bash
echo '{"name": "test", "data": {"x": 1, "y": 2}}' \
| nxuskit-cli artifact summarize --input - --format json
```
**Common errors:**
- `Invalid artifact JSON: ...` -- Fix: input must be valid JSON.
---
### `packet validate`
Validate a JSON document against a JSON Schema.
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--input` | string | **yes** | Packet data file (JSON) or `-` for stdin |
| `--schema` | string | **yes** | Path to a JSON Schema file |
No custom input schema -- the packet is any JSON value validated against the
provided JSON Schema.
**Example:**
```bash
echo '{"type": "string"}' > /tmp/schema.json
echo '"hello"' | nxuskit-cli packet validate --input - --schema /tmp/schema.json --format json
```
**Output fields:**
| Field | Type | Description |
|-------|------|-------------|
| `valid` | bool | `true` if the packet conforms to the schema |
| `errors` | array of `{path, message, keyword}` | Validation errors (empty when valid) |
**Common errors:**
- `SchemaNotFound { path: "..." }` -- Fix: the `--schema` path must point to an existing file.
- `Invalid JSON Schema: ...` -- Fix: ensure the schema file is a valid JSON Schema draft.
- Exits with code 1 when validation fails (output still written to stdout).
---
### `tool-loop run`
Iterative tool-augmented LLM loop. The model is called repeatedly until it
converges (stops requesting tool calls) or hits `max_iterations`.
**Input schema (`ToolLoopInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `prompt` | string | **yes** | Initial user prompt |
| `provider` | string | no | Provider name (default: `loopback` or `$NXUSKIT_PROVIDER`) |
| `model` | string | no | Model identifier. For `loopback`, use a valid loopback model such as `"echo"`; do not rely on the implicit `"default"` model in v0.9.4. |
| `max_iterations` | u32 | no | Maximum loop iterations (default: `10`) |
| `tools` | array of strings | no | Tool adapter names: `"file_reader"`, `"calculator"`, `"web_search"` |
| `tool_configs` | JSON object | no | Per-tool configuration |
| `tool_definitions` | array of JSON objects | no | Function/tool schemas passed to the LLM for function calling |
Built-in tool adapters:
- `file_reader` -- reads a file, expects `{"path": "..."}` arguments
- `calculator` -- evaluates a math expression, expects `{"expression": "..."}` arguments
- `web_search` -- searches the web, expects `{"query": "..."}` arguments (MCP-gated)
**Example:**
```bash
echo '{
"prompt": "What is 2 + 2?",
"provider": "loopback",
"model": "echo",
"tools": ["calculator"],
"max_iterations": 5
}' | nxuskit-cli tool-loop run --input - --format json
```
**Common errors:**
- `Invalid tool-loop input: missing field "prompt"` -- Fix: `prompt` is the only required field.
- `Unknown tool adapter: xyz` -- Fix: valid adapters are `file_reader`, `calculator`, `web_search`.
- `Entitlement check failed: mcp` -- Fix: the `mcp` tool adapter is Pro-gated.
---
### `judge select`
LLM-based candidate selection. Sends candidates and criteria to an LLM and
parses a structured JSON response with scores and reasoning.
**Input schema (`JudgeSelectInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `candidates` | array of `Candidate` | **yes** | Candidates to evaluate |
| `criteria` | string | no | Evaluation criteria description |
| `provider` | string | no | Provider name (default: `"loopback"`) |
| `model` | string | no | Model identifier. Use a configured LLM model; `loopback` echoes the judge prompt and can fail structured parsing. |
**`Candidate` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | string | **yes** | Unique candidate identifier |
| `content` | string | **yes** | Candidate text to evaluate |
**Example:**
```bash
echo '{
"candidates": [
{"id": "a", "content": "The answer is 42."},
{"id": "b", "content": "The answer is approximately 42.0."}
],
"criteria": "accuracy and conciseness",
"provider": "your-provider",
"model": "your-json-capable-model"
}' | nxuskit-cli judge select --input - --format json
```
**Common errors:**
- `Invalid judge select input: missing field "candidates"` -- Fix: `candidates` array is required with at least one entry.
- `Failed to parse judge response as structured JSON: ...` -- Fix: the LLM must return a JSON object with `selected_id`, `reasoning`, and `scores`. The loopback provider may not produce valid judge output; use a real LLM provider for meaningful results.
---
### `branch fork`
Fan out a single prompt to multiple models concurrently.
**Input schema (`BranchForkInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `prompt` | string | **yes** | Prompt sent to all models |
| `models` | array of strings | **yes** | Model identifiers to invoke in parallel |
| `provider` | string | no | Provider name (default: `"loopback"`) |
| `system` | string | no | System message prepended to each request |
Alternatively, models can be specified via the `--models` CLI flag as a
comma-separated list, which overrides the `models` field in the JSON input.
**Example:**
```bash
echo '{
"prompt": "Explain recursion in one sentence.",
"models": ["echo", "echo-json-native"],
"provider": "loopback"
}' | nxuskit-cli branch fork --input - --format json
```
**Using `--models` flag:**
```bash
echo '{"prompt": "Explain recursion.", "provider": "loopback"}' \
| nxuskit-cli branch fork --input - --models echo,echo-json-native --format json
```
**Common errors:**
- `Invalid fork input: missing field "prompt"` -- Fix: `prompt` is required.
- `Invalid fork input: missing field "models"` -- Fix: provide `models` in JSON or via `--models` flag.
---
### `branch compare`
Compare results from a previous `branch fork` invocation. Input is the JSON
output of `branch fork` (the `BranchForkResult` object).
**Input schema (`BranchForkResult`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `results` | array of `BranchModelResult` | **yes** | Results from `branch fork` |
**`BranchModelResult` fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `model` | string | **yes** | Model identifier |
| `content` | string | **yes** | Model's response text |
| `usage` | `{input_tokens, output_tokens, total_tokens}` | no | Token usage |
| `elapsed_ms` | f64 | **yes** | Response latency in milliseconds |
**Output includes:**
- `comparison`: per-model length and optional quality score
- `diffs`: structural differences (content_length, word_count, sentence_count, elapsed_ms, content_similarity for 2-model comparisons)
**Example (piping fork output to compare):**
```bash
echo '{
"prompt": "Explain recursion.",
"models": ["echo", "echo-json-native"],
"provider": "loopback"
}' | nxuskit-cli branch fork --input - --format json \
| jq '.result' \
| nxuskit-cli branch compare --input - --format json
```
**Common errors:**
- `Invalid fork result input: missing field "results"` -- Fix: input must be a `BranchForkResult` object (the `result` field from a fork envelope, not the full envelope).
---
### `solver what-if`
What-if scenario analysis (Pro-gated). Accepts the same three input formats as
`solver solve`. With `--compare`, solves both a base problem and an assumed
variant, then outputs a diff of the results.
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--input` | string | **yes** | Base problem file or `-` for stdin (any solver format) |
| `--compare` | string | no | Assumed variant file (same format as `--input`). Enables diff output. |
| `--format` | string | no | Output format: `json` (default), `yaml`, `text` |
**Single what-if (no comparison):**
Returns the solution to the assumed scenario, identical in shape to `solver solve` output.
```bash
echo '{
"variables": [
{"name": "budget", "type": "integer", "bounds": [{"min": 0}, {"max": 100000}]},
{"name": "headcount", "type": "integer", "bounds": [{"min": 1}, {"max": 20}]}
],
"constraints": ["budget == headcount * 5000"],
"assumptions": [{"name": "assume_headcount", "constraint_type": "eq", "params": {"left": "headcount", "right": 12}}]
}' | nxuskit-cli solver what-if --input - --format json
```
**Comparison (`--compare`):**
Solves both the base (from `--input`) and the assumed variant (from `--compare`),
then emits a `diff` block showing changed variables and the objective delta.
```bash
nxuskit-cli solver what-if --input base.json --compare assumed.json --format json
```
**Output shape (comparison):**
```json
{
"base": { "status": "sat", "values": {"budget": 60000, "headcount": 12} },
"assumed": { "status": "sat", "values": {"budget": 75000, "headcount": 15} },
"diff": {
"changed": [
{"variable": "budget", "base": 60000, "assumed": 75000, "delta": 15000},
{"variable": "headcount", "base": 12, "assumed": 15, "delta": 3}
],
"objective_delta": 15000
}
}
```
**Common errors:**
- `Entitlement check failed: solver_what_if` -- Fix: requires Pro edition.
- `Cannot parse base input` -- Fix: ensure `--input` is a valid solver format.
- `Cannot parse assumed input` -- Fix: ensure `--compare` file uses the same solver format as `--input`.
---
### `clips session`
Persistent CLIPS sessions survive across multiple eval calls. Session count is
enforced per tier — exit code 4 when the limit is reached.
#### `clips session create`
Create a new CLIPS session, optionally pre-loading rules.
**Input schema (`ClipsSessionCreateInput`):**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `rules` | string | no | CLIPS rule definitions to load into the session |
| `label` | string | no | Human-readable label for the session |
**Example:**
```bash
echo '{
"rules": "(defrule greet (person (name ?n)) => (printout t (str-cat \"Hello \" ?n) crlf))",
"label": "greet-session"
}' | nxuskit-cli clips session create --input - --format json
```
**Output:**
```json
{
"session_id": "sess_abc12345",
"label": "greet-session",
"created_at": "2026-04-13T10:00:00Z",
"rule_count": 1
}
```
**Common errors:**
- `Entitlement check failed: clips_session_limit` (exit 4) -- Fix: destroy an existing session first, or upgrade edition.
- `Failed to load CLIPS rules: ...` (exit 1) -- Fix: check CLIPS syntax.
---
#### `clips session list`
List all active CLIPS sessions.
**No input required.** Pass `--format json` for machine-readable output.
```bash
nxuskit-cli clips session list --format json
```
**Output:**
```json
{
"sessions": [
{"session_id": "sess_abc12345", "label": "greet-session", "rule_count": 1, "created_at": "..."},
{"session_id": "sess_def67890", "label": null, "rule_count": 5, "created_at": "..."}
],
"count": 2
}
```
---
#### `clips session destroy`
Destroy a session and release its resources.
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `--session-id` | string | **yes** | Session ID returned by `clips session create` |
```bash
nxuskit-cli clips session destroy --session-id sess_abc12345 --format json
```
**Output:**
```json
{"session_id": "sess_abc12345", "destroyed": true}
```
**Common errors:**
- `Unknown session ID: sess_abc12345` (exit 5) -- Fix: use `clips session list` to find valid IDs.
---
### `provider list`
List all registered providers with type, status, and capability metadata.
**No input required.**
```bash
nxuskit-cli provider list --format json
```
**Output shape:**
```json
{
"providers": [
{
"name": "openai",
"type": "llm",
"status": "available",
"capabilities": ["streaming", "vision", "tool_calling"],
"auth_required": true
},
{
"name": "loopback",
"type": "llm",
"status": "available",
"capabilities": ["streaming"],
"auth_required": false
},
{
"name": "clips",
"type": "rule_engine",
"status": "available",
"capabilities": [],
"auth_required": false
}
],
"count": 3
}
```
---
### `provider info`
Show detailed information for a single provider. Accepts fuzzy name matching —
if the name is close but not exact, suggestions are printed to stderr and the
command exits with code 5.
**CLI arguments:**
| Argument | Type | Required | Description |
|----------|------|----------|-------------|
| `` | string | **yes** | Provider name (positional argument) |
```bash
nxuskit-cli provider info openai --format json
```
**Output shape:**
```json
{
"name": "openai",
"type": "llm",
"status": "available",
"capabilities": ["streaming", "vision", "tool_calling"],
"auth_required": true,
"auth_env_var": "OPENAI_API_KEY",
"default_model": "gpt-4o",
"supported_formats": ["json", "yaml", "jsonl", "text"],
"docs_url": "https://platform.openai.com/docs"
}
```
**Common errors:**
- `Unknown provider "opnai". Did you mean: openai?` (exit 5, stderr) -- Fix: use the exact provider name from `provider list`, or let the suggestion guide you.
---
### Error responses
All non-zero exits write a JSON `ErrorEnvelope` to **stderr**. Stdout may be
empty or contain partial output.
```json
{
"code": "entitlement_denied",
"message": "This command requires the pro edition",
"details": {
"feature": "solver",
"current_tier": "oss",
"required_tier": "pro"
},
"trace_id": "a1b2c3d4",
"timestamp": "2026-04-13T10:00:00Z"
}
```
| Field | Type | Description |
|-------|------|-------------|
| `code` | string | Machine-readable error code |
| `message` | string | Human-readable description |
| `details` | object | Optional structured context (tier info, field names, session IDs, etc.) |
| `trace_id` | string | 8-character hex trace ID |
| `timestamp` | string | ISO 8601 UTC timestamp |
**Exit code -> `code` mapping (Level 1 and Level 2):**
| Exit | `code` values |
|------|--------------|
| 0 | (success - no `code`) |
| 1 | `internal_error`, `provider_error`, `engine_error`, `internal` |
| 2 | `timeout`, `idle_timeout` |
| 3 | `auth_failure`, `auth_failed`, `token_expired`, `token_missing` |
| 4 | `entitlement_denied`, `session_limit_reached` |
| 5 | `validation`, `validation_error`, `parse_error`, `unknown_provider`, `unknown_session`, `zen_validate_error`, `zen_test_mismatch`, `zen_test_eval_error` |
| 130 | `cancelled` (SIGINT) |
The exit-code set itself is frozen (FR-001 / Article IV): Level 2 commands like
`zen validate` / `zen test` introduce new `code` strings within exit 5, not new
exit codes.
---
# Cloud LLM Providers
URL: https://docs.nxus.systems/v0.9.4/nxuskit/reference/providers/cloud-llms
## OpenAI
```json
{
"provider_type": "openai",
"api_key": "sk-...",
"base_url": "https://api.openai.com/v1",
"timeout_ms": 30000
}
```
**Environment variable:** `OPENAI_API_KEY`
**Supported models:** `gpt-4o`, `gpt-4o-mini`, `o1`, `o1-mini`, `o3-mini`, `gpt-4-turbo`
**Capabilities:** System messages, streaming, vision, tools/function calling, JSON mode, JSON schema, seed, logprobs, presence/frequency penalty, response format
## xAI Grok
```json
{
"provider_type": "xai",
"api_key": "xai-...",
"base_url": "https://api.x.ai/v1",
"timeout_ms": 30000
}
```
**Environment variable:** `XAI_API_KEY`
**Supported models:** `grok-4`, `grok-4-latest`, `grok-4-fast`
**Capabilities:** System messages, streaming, vision, tools/function calling, JSON mode, JSON schema
`xai` is the canonical provider id for xAI Grok. `groq` remains Groq, Inc.; there is no `grok` provider alias.
## Anthropic Claude
```json
{
"provider_type": "claude",
"api_key": "sk-ant-...",
"base_url": "https://api.anthropic.com",
"timeout_ms": 30000
}
```
**Environment variable:** `ANTHROPIC_API_KEY`
**Supported models:** `claude-sonnet-4-20250514`, `claude-opus-4-20250514`, `claude-haiku-4-5-20251001`, `claude-3-5-sonnet-20241022`
**Capabilities:** System messages, streaming, vision, tools/function calling, JSON mode, top-k sampling. Max stop sequences: 8192.
## Groq
```json
{
"provider_type": "groq",
"api_key": "gsk_...",
"timeout_ms": 30000
}
```
**Environment variable:** `GROQ_API_KEY`
**Supported models:** `llama-3.3-70b-versatile`, `llama-3.1-8b-instant`, `mixtral-8x7b-32768`, `gemma2-9b-it`
**Capabilities:** System messages, streaming, tools/function calling, JSON mode
## Fireworks
```json
{
"provider_type": "fireworks",
"api_key": "fw_...",
"timeout_ms": 30000
}
```
**Environment variable:** `FIREWORKS_API_KEY`
**Capabilities:** System messages, streaming
## Together
```json
{
"provider_type": "together",
"api_key": "...",
"timeout_ms": 30000
}
```
**Environment variable:** `TOGETHER_API_KEY`
**Capabilities:** System messages, streaming
## OpenRouter
```json
{
"provider_type": "openrouter",
"api_key": "sk-or-...",
"timeout_ms": 30000
}
```
**Environment variable:** `OPENROUTER_API_KEY`
**Capabilities:** System messages, streaming, vision, tools/function calling
## Perplexity
```json
{
"provider_type": "perplexity",
"api_key": "pplx-...",
"timeout_ms": 30000
}
```
**Environment variable:** `PERPLEXITY_API_KEY`
**Capabilities:** System messages, streaming
## Mistral
```json
{
"provider_type": "mistral",
"api_key": "...",
"timeout_ms": 30000
}
```
**Environment variable:** `MISTRAL_API_KEY`
**Supported models:** `mistral-large-latest`, `mistral-medium-latest`, `mistral-small-latest`, `codestral-latest`
**Capabilities:** System messages, streaming, tools/function calling, JSON mode
---
# Expert System & Utility Providers
URL: https://docs.nxus.systems/v0.9.4/nxuskit/reference/providers/expert-systems
## CLIPS Rule Engine
The CLIPS provider runs rules against a CLIPS 6.4.2 expert system engine.
Unlike LLM providers, CLIPS uses deterministic rule-based reasoning.
A word about CLIPS: During its development at NASA from 1985 to 1996, the
primary CLIPS contributors were: Robert Savely, who conceived and championed
the project; Chris Culbert, who managed the project; Gary Riley and Brian
Dantes, who were the lead developers; and Frank Lopez, who developed the first
version. Since leaving NASA in 1996, Gary Riley has maintained CLIPS as public
domain software.
```json
{
"provider_type": "clips",
"model": "/path/to/rules/directory"
}
```
**Configuration:**
- `model` field is used for the rules directory path (contains `.clp` rule files or `.bin` binary images)
**Capabilities:** System messages
**Note:** No API key required. The CLIPS engine runs in-process.
For writing custom rules, see the [Rule Authoring Guide](/v0.9.4/nxuskit/guides/clips-rule-authoring/).
## MCP (Model Context Protocol)
Connects to an MCP server for tool-augmented model interactions.
```json
{
"provider_type": "mcp",
"base_url": "http://localhost:3000",
"model": "model-name"
}
```
**Configuration:**
- `base_url` — MCP server URI (required)
- `model` — Model name to use on the server
**Capabilities:** System messages, streaming
## Mock (Testing)
Returns deterministic responses for unit testing.
```json
{
"provider_type": "mock"
}
```
**Capabilities:** System messages, streaming
**Note:** No API key or configuration required. Returns fixed responses.
## Loopback (Testing)
Echoes back the user's input for integration testing.
```json
{
"provider_type": "loopback"
}
```
**Capabilities:** System messages, streaming
**Note:** Use `"model": "echo"` in the chat request to echo back the user's
message content. Other model names return an empty response.
---
# Local LLM Providers
URL: https://docs.nxus.systems/v0.9.4/nxuskit/reference/providers/local-llms
nxusKit supports two categories of local LLM providers:
- **In-Process Providers** — Load and run models directly in your application process. No external server required. Requires Cargo feature flags.
- **HTTP-Based Providers** — Connect to a locally running inference server (Ollama, LM Studio). No feature flags needed.
---
## In-Process Providers
In-process providers load GGUF model files directly into your application and run inference without any external server. This gives you the lowest possible latency, full control over model lifecycle, and zero network overhead.
### Backends
nxusKit provides two in-process inference backends:
| Backend | Feature Flag | Engine | Status |
|---------|-------------|--------|--------|
| llama.cpp | `provider-local-llama` | [llama-cpp-2](https://github.com/utilityai/llama-cpp-rs) (safe Rust bindings to llama.cpp) | Production-ready |
| mistral.rs | `provider-local-mistralrs` | [mistral.rs](https://github.com/EricLBuehler/mistral.rs) (pure-Rust inference on Candle) | Experimental |
Both backends load the same **GGUF** model format. If both features are enabled, you can select a backend explicitly or let nxusKit auto-select the first available one.
### Supported Model Format
**GGUF** (GPT-Generated Unified Format) is the only supported format. GGUF files are self-contained — they bundle weights, tokenizer, and metadata in a single file. Both backends read the same `.gguf` files.
You can obtain GGUF models from:
- [Hugging Face](https://huggingface.co/models?library=gguf) — Search for "GGUF" in model filters
- [Ollama](https://ollama.com/library) — Models pulled by Ollama are stored as GGUF blobs (nxusKit can discover these)
- [TheBloke on Hugging Face](https://huggingface.co/TheBloke) — Prolific quantizer of popular models
### Compatible Model Families
Any model published in GGUF format that is compatible with llama.cpp should work. The following model families are known to work:
| Model Family | Parameters | Example GGUF | Notes |
|---|---|---|---|
| **Llama 3.2** | 1B, 3B | `Llama-3.2-1B-Instruct-Q4_K_M.gguf` | Meta's latest small models. Great for CPU. |
| **Llama 3.1** | 8B, 70B, 405B | `Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf` | Excellent general-purpose. 8B runs well on 16GB RAM. |
| **Llama 3** | 8B, 70B | `Meta-Llama-3-8B-Instruct-Q4_K_M.gguf` | Predecessor to 3.1, widely available. |
| **Llama 2** | 7B, 13B, 70B | `llama-2-7b-chat.Q4_K_M.gguf` | Older but battle-tested. |
| **Mistral** | 7B | `mistral-7b-instruct-v0.3.Q4_K_M.gguf` | Strong performance relative to size. |
| **Mixtral** | 8x7B, 8x22B | `mixtral-8x7b-instruct-v0.1.Q4_K_M.gguf` | Mixture-of-experts. Needs more RAM. |
| **Phi-3 / Phi-3.5** | 3.8B, 14B | `Phi-3.5-mini-instruct-Q4_K_M.gguf` | Microsoft. Strong reasoning for size. |
| **Gemma 2** | 2B, 9B, 27B | `gemma-2-9b-it-Q4_K_M.gguf` | Google. Good coding and instruction following. |
| **Qwen 2.5** | 0.5B–72B | `Qwen2.5-7B-Instruct-Q4_K_M.gguf` | Alibaba. Multilingual, strong at math/code. |
| **DeepSeek-R1** | 1.5B–70B (distilled) | `DeepSeek-R1-Distill-Llama-8B-Q4_K_M.gguf` | Reasoning-focused distilled models. |
| **CodeLlama** | 7B, 13B, 34B | `codellama-7b-instruct.Q4_K_M.gguf` | Code-specialized Llama variant. |
| **TinyLlama** | 1.1B | `tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf` | Tiny. Useful for testing and CI. |
| **StableLM** | 1.6B, 3B | `stablelm-2-1_6b-chat.Q4_K_M.gguf` | Stability AI. Small and fast. |
| **Yi** | 6B, 9B, 34B | `Yi-1.5-9B-Chat-Q4_K_M.gguf` | 01.AI. Strong multilingual. |
| **Command R** | 35B, 104B | `c4ai-command-r-v01-Q4_K_M.gguf` | Cohere. RAG-optimized. |
| **Falcon** | 7B, 40B, 180B | `falcon-7b-instruct-Q4_K_M.gguf` | TII. |
> **Tip:** For testing and development, start with **TinyLlama 1.1B** (fast, tiny, runs anywhere) or **Llama 3.2 1B** (modern, instruction-tuned, still small enough for CPU).
### Quantization Levels
GGUF models come in different quantization levels that trade quality for size/speed. nxusKit auto-detects the quantization from the filename:
| Quantization | Bits/Weight | Relative Quality | Relative Size | Recommended For |
|---|---|---|---|---|
| `F32` | 32 | Best (reference) | Largest | Accuracy testing only |
| `F16` | 16 | Excellent | ~50% of F32 | GPU with sufficient VRAM |
| `Q8_0` | 8.5 | Near-lossless | ~50% of F16 | Quality-sensitive tasks |
| `Q6_K` | 6.6 | Very good | ~38% of F16 | Good quality/size balance |
| `Q5_K_M` | 5.7 | Good | ~33% of F16 | Balanced |
| `Q5_K_S` | 5.5 | Good | ~32% of F16 | Slightly smaller than K_M |
| `Q4_K_M` | 4.8 | Acceptable | ~27% of F16 | **Most popular**. Best quality/size tradeoff. |
| `Q4_K_S` | 4.5 | Acceptable | ~26% of F16 | Slightly smaller than K_M |
| `Q3_K_M` | 3.9 | Degraded | ~22% of F16 | Memory-constrained environments |
| `Q2_K` | 3.4 | Poor | ~18% of F16 | Extreme memory constraints only |
> **Recommendation:** Use **Q4_K_M** for most deployments. It provides the best balance of quality, speed, and memory usage.
### Memory Requirements
Approximate RAM needed to load a model (varies by quantization):
| Model Size | Q4_K_M | Q8_0 | F16 |
|---|---|---|---|
| 1B params | ~0.8 GB | ~1.2 GB | ~2 GB |
| 3B params | ~2 GB | ~3.5 GB | ~6 GB |
| 7-8B params | ~4.5 GB | ~8 GB | ~15 GB |
| 13B params | ~8 GB | ~14 GB | ~26 GB |
| 34B params | ~20 GB | ~36 GB | ~68 GB |
| 70B params | ~40 GB | ~72 GB | ~140 GB |
These are approximate. Actual usage depends on context window size, batch size, and KV cache.
### GPU Acceleration
GPU offloading is automatic when available:
| Platform | Acceleration | How to Enable |
|---|---|---|
| macOS (Apple Silicon) | Metal | Automatic — llama.cpp detects Metal at build time |
| Linux (NVIDIA) | CUDA | Install CUDA toolkit; llama-cpp-2 detects at build time |
| Linux (AMD) | ROCm/Vulkan | Vulkan support via llama.cpp build flags |
| Windows (NVIDIA) | CUDA | Install CUDA toolkit |
| All platforms | CPU (AVX2/NEON) | Always available as fallback |
Control GPU offloading with `n_gpu_layers`:
- `-1` — offload all layers to GPU (maximum acceleration)
- `0` — CPU only (default)
- `N` — offload first N layers (partial offloading for limited VRAM)
### Configuration
```json
{
"provider_type": "local",
"model": "/path/to/model.gguf",
"options": {
"backend": "llama-cpp",
"n_gpu_layers": -1,
"context_size": 4096,
"batch_size": 512,
"threads": 8
}
}
```
**Configuration options:**
| Option | Type | Default | Description |
|---|---|---|---|
| `backend` | string | auto-detect | `"llama-cpp"` or `"mistralrs"`. Auto-selects first available if omitted. |
| `n_gpu_layers` | integer | `0` | GPU layer offloading. `-1` = all, `0` = CPU only, `N` = first N layers. |
| `context_size` | integer | model default | Context window size in tokens. |
| `batch_size` | integer | backend default | Prompt processing batch size. Higher = faster prompt processing, more memory. |
| `threads` | integer | auto-detect | CPU thread count. Leave unset for optimal auto-detection. |
### Rust API
```rust
use nxuskit-engine::{LocalRuntimeProvider, ChatRequest, Message};
let provider = LocalRuntimeProvider::builder()
.model_path("/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf")
.n_gpu_layers(-1) // Use GPU
.context_size(4096)
.build()?;
let request = ChatRequest::new("Llama-3.2-1B-Instruct-Q4_K_M.gguf")
.with_message(Message::user("Explain quantum computing in one paragraph."))
.with_temperature(0.7)
.with_max_tokens(256);
let response = provider.chat(&request).await?;
println!("{}", response.content);
```
### Model Discovery
The provider can discover available models from multiple sources:
```rust
let models = provider.list_models().await?;
for model in &models {
println!("{}: {} ({})",
model.id,
model.name,
model.metadata.get("quantization").unwrap_or(&"unknown".into()));
}
```
**Discovery sources** (in priority order):
1. **Explicit path** — The model path in your configuration
2. **Search paths** — Directories you configure (scans for `.gguf` files)
3. **Ollama store** (opt-in) — Discovers models already pulled by Ollama
**Ollama store locations** (auto-detected):
- macOS: `~/.ollama/models`
- Linux: `/usr/share/ollama/.ollama/models` or `~/.ollama/models`
- Windows: `%USERPROFILE%\.ollama\models`
**Environment variables:**
- `NXUSKIT_MODELS` — Custom model search directory
- `OLLAMA_MODELS` — Override Ollama store location
### Model Cache Management
Models stay loaded in memory after first use. You can manage the cache explicitly:
```rust
// Pre-load a model (async, happens in background)
provider.preload_model("/models/llama-3.2-1b.Q4_K_M.gguf").await?;
// Check what's loaded
for info in provider.cached_models() {
println!("{}: {} bytes", info.path, info.memory_bytes.unwrap_or(0));
}
// Free memory
provider.unload_model("/models/llama-3.2-1b.Q4_K_M.gguf");
```
### Capabilities
| Capability | Supported |
|---|---|
| System messages | Yes |
| Streaming | Yes (token-by-token) |
| Vision/images | No |
| JSON mode | No (llama-cpp) / Yes (mistral.rs) |
| Seed (deterministic) | Yes |
| Stop sequences | Yes (up to 4) |
| Temperature | Yes |
| Top-p | Yes |
| Max tokens | Yes |
| Presence penalty | No |
| Frequency penalty | No |
| Tool calling | No |
### Backend Comparison
| Feature | llama.cpp (`provider-local-llama`) | mistral.rs (`provider-local-mistralrs`) |
|---|---|---|
| Maturity | Production-ready | Experimental |
| Language | C++ with Rust bindings | Pure Rust (Candle) |
| Build time | Fast (~30s) | Slow (~3-5 min, pulls Candle) |
| GPU support | Metal, CUDA, Vulkan | Metal, CUDA (via Candle) |
| JSON mode | No | Yes (ISQ support) |
| Chat templates | Manual | Auto-detected from GGUF metadata |
| PagedAttention | No | Yes (CUDA, Apple Silicon) |
| In-situ quantization | No | Yes (load unquantized, quantize at runtime) |
| Binary size impact | Small (~2 MB) | Large (~20 MB, Candle framework) |
---
## HTTP-Based Providers
HTTP-based local providers connect to a separately running inference server. No Cargo feature flags are needed — they use the standard HTTP transport.
### Ollama
Run models locally via [Ollama](https://ollama.com/).
```json
{
"provider_type": "ollama",
"base_url": "http://localhost:11434",
"timeout_ms": 120000
}
```
**Environment variable:** `OLLAMA_HOST` (optional, defaults to `http://localhost:11434`)
**Supported models:** Any model pulled via `ollama pull`, e.g., `llama3.1`, `codellama`, `mistral`, `phi3`
**Capabilities:** System messages, streaming
**Note:** No API key required. The provider connects to a locally running Ollama server. The default timeout is 120 seconds (longer than cloud providers) to accommodate model loading.
### LM Studio
Run models locally via [LM Studio](https://lmstudio.ai/).
```json
{
"provider_type": "lmstudio",
"base_url": "http://localhost:1234/v1",
"timeout_ms": 120000
}
```
**Environment variable:** `LMSTUDIO_HOST` (optional, defaults to `http://localhost:1234/v1`)
**Capabilities:** System messages, streaming
**Note:** No API key required. Start the LM Studio local server before using this provider.
---
## Choosing Between Local Providers
| Consideration | In-Process (local) | Ollama | LM Studio |
|---|---|---|---|
| Setup complexity | Download a GGUF file | Install Ollama + pull model | Install LM Studio + download model |
| External server | None required | Must be running | Must be running |
| Latency | Lowest (no HTTP overhead) | Low (localhost HTTP) | Low (localhost HTTP) |
| Model lifecycle control | Full (preload/unload API) | Managed by Ollama | Managed by LM Studio |
| Memory management | Direct (cache API) | Managed by Ollama | Managed by LM Studio |
| Feature flags needed | Yes (`provider-local-llama`) | No | No |
| Build dependencies | C++ compiler (llama.cpp) | None | None |
| Best for | Embedded/library use, max control | Quick experimentation | GUI-based development |
---
# Z3 Constraint Satisfaction Provider
URL: https://docs.nxus.systems/v0.9.4/nxuskit/reference/providers/z3-solver
The Z3 provider integrates [Microsoft Z3](https://github.com/Z3Prover/z3), an industry-grade SMT (Satisfiability Modulo Theories) solver, into the nxusKit provider interface. It enables constraint satisfaction, optimization, and formal verification problems to be expressed and solved using the same `chat()` / `chat_stream()` API as LLM providers.
Unlike LLM providers, Z3 is deterministic — the same input always produces the same output.
## Configuration
```json
{
"provider_type": "z3",
"timeout_ms": 30000,
"random_seed": 42,
"produce_unsat_core": true,
"logic": "QF_LIA"
}
```
**Configuration options:**
| Option | Type | Default | Description |
|---|---|---|---|
| `timeout_ms` | integer | 30000 | Solver timeout in milliseconds |
| `random_seed` | integer | none | Seed for search heuristics (for reproducibility) |
| `produce_unsat_core` | boolean | false | Extract conflicting constraints when problem is unsatisfiable |
| `logic` | string | auto | SMT logic preset (e.g., `"QF_LIA"`, `"QF_LRA"`, `"QF_BV"`) |
| `max_conflicts` | integer | none | Maximum conflict (branch) limit for search |
| `model_paths` | string[] | none | Directories to scan for `.smt2` and `.z3` model files |
**Capabilities:** System messages, streaming, JSON mode, seed
## Input Format
The Z3 provider accepts structured JSON as the user message content. The JSON describes variables, constraints, and optionally an optimization objective.
### Variables
```json
{
"variables": [
{"name": "x", "var_type": "integer"},
{"name": "y", "var_type": "integer", "domain": {"min": 1, "max": 100}},
{"name": "flag", "var_type": "boolean"},
{"name": "ratio", "var_type": "real", "domain": {"min": 0.0, "max": 1.0}}
]
}
```
**Variable types:** `integer`, `real`, `boolean`
**Domain constraints** (optional): `min`, `max` for numeric types.
### Constraints
```json
{
"constraints": [
{"constraint_type": "eq", "params": {"left": "x", "right": 42}},
{"constraint_type": "gt", "params": {"left": "y", "right": "x"}},
{"constraint_type": "all_different", "params": {"variables": ["x", "y", "z"]}},
{"constraint_type": "in_range", "params": {"variable": "x", "min": 1, "max": 10}}
]
}
```
**Supported constraint types:**
| Type | Description | Parameters |
|---|---|---|
| `eq` | Equal | `left`, `right` |
| `neq` | Not equal | `left`, `right` |
| `lt` | Less than | `left`, `right` |
| `gt` | Greater than | `left`, `right` |
| `le` | Less than or equal | `left`, `right` |
| `ge` | Greater than or equal | `left`, `right` |
| `add` | Addition expression | `left`, `right` (or `operands` list) |
| `sub` | Subtraction expression | `left`, `right` |
| `mul` | Multiplication expression | `left`, `right` |
| `div` | Division expression | `left`, `right` |
| `and` | Logical AND | `operands` list |
| `or` | Logical OR | `operands` list |
| `not` | Logical NOT | `operand` |
| `implies` | Logical implication | `left`, `right` |
| `iff` | If and only if | `left`, `right` |
| `all_different` | All variables must differ | `variables` list |
| `at_most` | At most N true | `variables`, `n` |
| `at_least` | At least N true | `variables`, `n` |
| `exactly` | Exactly N true | `variables`, `n` |
| `in_range` | Value within range | `variable`, `min`, `max` |
Parameters can reference variable names (strings), literal values (numbers, booleans), or nested expressions.
### Optimization
Add an `objective` field to minimize or maximize a variable:
```json
{
"variables": [...],
"constraints": [...],
"objective": {
"direction": "minimize",
"expression": "cost"
}
}
```
**Directions:** `"minimize"` or `"maximize"`
### Named Constraints
Constraints can be named for unsat core extraction:
```json
{
"constraints": [
{"name": "budget_limit", "constraint_type": "le", "params": {"left": "cost", "right": 1000}},
{"name": "quality_req", "constraint_type": "ge", "params": {"left": "quality", "right": 8}}
]
}
```
When the problem is unsatisfiable and `produce_unsat_core` is enabled, the response includes the names of conflicting constraints.
## Output Format
The response `content` field contains JSON:
### Satisfiable (SAT)
```json
{
"status": "sat",
"assignments": {
"x": 42,
"y": 58,
"flag": true
},
"stats": {
"solve_time_ms": 2,
"num_conflicts": 0,
"num_decisions": 5
}
}
```
### Unsatisfiable (UNSAT)
```json
{
"status": "unsat",
"unsat_core": ["budget_limit", "quality_req"],
"stats": {
"solve_time_ms": 1,
"num_conflicts": 3
}
}
```
### Optimal (Optimization)
```json
{
"status": "optimal",
"assignments": {
"cost": 150,
"quality": 8
},
"objective_value": 150.0,
"stats": {
"solve_time_ms": 15,
"num_solutions_found": 4
}
}
```
## Streaming
- **Satisfaction problems**: Single result chunk (solve is typically < 1ms).
- **Optimization problems**: Progressive improvement — each improving solution is emitted as a `StreamChunk`, with the final chunk containing `finish_reason` and complete stats.
## Examples
### Basic Satisfaction
```rust
use nxuskit-engine::{Z3Provider, ChatRequest, Message};
let provider = Z3Provider::builder()
.timeout_ms(5_000)
.build()?;
let problem = r#"{
"variables": [
{"name": "x", "var_type": "integer", "domain": {"min": 1, "max": 9}},
{"name": "y", "var_type": "integer", "domain": {"min": 1, "max": 9}},
{"name": "z", "var_type": "integer", "domain": {"min": 1, "max": 9}}
],
"constraints": [
{"constraint_type": "all_different", "params": {"variables": ["x", "y", "z"]}},
{"constraint_type": "eq", "params": {"left": {"add": ["x", "y", "z"]}, "right": 15}}
]
}"#;
let request = ChatRequest::new("z3-solver")
.with_message(Message::user(problem));
let response = provider.chat(&request).await?;
let output: serde_json::Value = serde_json::from_str(&response.content)?;
assert_eq!(output["status"], "sat");
```
### Via C ABI (Go)
```go
provider, err := nxuskit-go.NewZ3FFIProvider(
nxuskit-go.WithZ3Timeout(5000),
nxuskit-go.WithZ3UnsatCore(true),
)
response, err := provider.Chat(ctx, &nxuskit-go.ChatRequest{
Model: "z3-solver",
Messages: []nxuskit-go.Message{
{Role: "user", Content: problemJSON},
},
})
```
### Via C ABI (Python)
```python
from nxuskit-py._ffi_provider import create_ffi_provider
provider = create_ffi_provider({
"provider_type": "z3",
"timeout_ms": 5000,
"produce_unsat_core": True,
})
response = provider.chat(model="z3-solver", messages=[
{"role": "user", "content": problem_json}
])
```
## Model Discovery
The Z3 provider can discover pre-defined constraint model files:
```rust
let models = provider.list_models().await?;
// Returns built-in models ("z3-solver", "z3-optimizer") plus
// any .smt2 and .z3 files found in configured model_paths
```
## Use Cases
- **Scheduling**: Resource allocation, timetabling, shift planning
- **Configuration**: Product configuration with constraints, compatibility checking
- **Puzzles**: Sudoku, N-Queens, logic puzzles
- **Verification**: Property checking, invariant validation
- **Optimization**: Cost minimization, resource optimization with constraints
- **Planning**: Task sequencing with dependency and resource constraints
---
# nxus.SYSTEMS Documentation
URL: https://docs.nxus.systems/v1.0.0
import { CardGrid, LinkCard } from '@astrojs/starlight/components';
## Current Entry Points
---
# GitHub Repositories
URL: https://docs.nxus.systems/v1.0.0/github
The public nxus.SYSTEMS GitHub organization is
[github.com/nxus-SYSTEMS](https://github.com/nxus-SYSTEMS).
## Public Repositories
| Repository | What to use it for |
| --- | --- |
| [nxusKit SDK](https://github.com/nxus-SYSTEMS/nxusKit) | Source for the multi-language SDK covering LLM providers, rule engines, constraint solving, Bayesian networks, decision tables, the C ABI, and CLI/Bash workflows. |
| [nxusKit Examples](https://github.com/nxus-SYSTEMS/nxusKit-examples) | Runnable Rust, Go, Python, and CLI/Bash examples for common nxusKit integration patterns. |
| [nxus Codex Plugins](https://github.com/nxus-SYSTEMS/nxus-codex-plugins) | Codex Plugin packages from nxus.SYSTEMS, including nxusKit Celerat. |
| [nxus Docs](https://github.com/nxus-SYSTEMS/nxus-docs) | Source for this public documentation site, hosted at [docs.nxus.systems](https://docs.nxus.systems/). |
## Related Links
- [nxusKit documentation](/v1.0.0/nxuskit/)
- [nxusKit examples documentation](/v1.0.0/nxuskit/examples/)
- [Codex Plugins documentation](/codex-plugins/)
- [Commercial website](https://nxus.systems)
- [Plans](https://nxus.systems/pricing)
---
# nxusKit SDK
URL: https://docs.nxus.systems/v1.0.0/nxuskit
nxusKit is a unified, type-safe SDK for calling LLM providers (Claude, OpenAI, Ollama, and more),
CLIPS rule engines, Z3 constraint solvers, Bayesian networks, and ZEN decision tables — from Rust, Go, Python, and the C ABI.
## Start Here
Install the SDK, configure credentials, and run your first request:
- [Installation](/v1.0.0/nxuskit/getting-started/installation/)
- [First Call](/v1.0.0/nxuskit/getting-started/first-call/)
- [Authentication](/v1.0.0/nxuskit/getting-started/authentication/)
## Browse by Task
- **Build an integration** — Start with [installation](/v1.0.0/nxuskit/getting-started/installation/), then use the [provider model](/v1.0.0/nxuskit/concepts/provider-model/) to choose the right backend.
- **Explore working code** — Browse [examples](/v1.0.0/nxuskit/examples/) for reusable patterns, local model setup, solver workflows, and complete applications.
- **Author rules** — Use the [CLIPS rule authoring guide](/v1.0.0/nxuskit/guides/clips-rule-authoring/) and the [CLIPS session API](/v1.0.0/nxuskit/reference/api-reference/#clips-session-api).
- **Look up contracts** — Use the [API reference](/v1.0.0/nxuskit/reference/api/), [C ABI reference](/v1.0.0/nxuskit/reference/api-reference/), [CLI reference](/v1.0.0/nxuskit/reference/cli-reference/), and [provider references](/v1.0.0/nxuskit/reference/providers/cloud-llms/).
- **Manage editions** — Review [feature tiers](/v1.0.0/nxuskit/concepts/tier-system/) and [license activation](/v1.0.0/nxuskit/concepts/licensing/).
- **Use Codex workflows** — Install [nxusKit Celerat](/codex-plugins/nxuskit/) and browse [task recipes](/codex-plugins/nxuskit/task-recipes/) for Codex-ready implementation prompts.
---
# Architecture
URL: https://docs.nxus.systems/v1.0.0/nxuskit/concepts/architecture
## Overview
nxusKit is organized around a shared provider model with language-specific
wrappers for Rust, Go, and Python, plus a stable C ABI. Each wrapper exposes
native types while keeping the same core concepts: provider configuration, chat
requests, chat responses, streaming chunks, and structured error handling.
The architecture has four practical layers:
1. **Language wrappers** — Idiomatic SDK surfaces for application code.
2. **Provider abstraction** — A common contract for chat, streaming, capability
discovery, and provider metadata.
3. **Provider implementations** — Cloud LLMs, local LLMs, CLIPS, Z3, Mock,
Loopback, and MCP adapters.
4. **Native boundary** — C ABI functions and ownership rules for embedding and
cross-language integration.
## Component Map
| Component | Role |
|-----------|------|
| Rust SDK | Reference implementation, async provider interface, CLI, and native engine integrations. |
| Go SDK | Go-native provider interface with context cancellation and channel-based streaming. |
| Python SDK | Python-friendly provider creation, chat calls, and FFI access. |
| C ABI | Stable native boundary for providers, responses, streams, errors, and CLIPS sessions. |
| CLI | Shell interface for chat, provider checks, structured JSON workflows, and Pro features. |
| Examples | Runnable patterns and applications that demonstrate cross-language usage. |
## Provider Families
nxusKit providers fall into four broad groups:
| Family | Examples | Behavior |
|--------|----------|----------|
| Cloud LLMs | OpenAI, Anthropic, Groq, Mistral, Fireworks, Together, OpenRouter, Perplexity | Hosted model APIs with provider-specific capabilities. |
| Local LLMs | Ollama, LM Studio, in-process GGUF backends | Local inference for development, privacy, or low-latency use cases. |
| Deterministic engines | CLIPS, Z3 | Repeatable rule evaluation, inference, constraint solving, and optimization. |
| Utility providers | Mock, Loopback, MCP | Testing, integration checks, and tool-oriented workflows. |
See the [Provider Model](/v1.0.0/nxuskit/concepts/provider-model/) for the shared
configuration and request flow.
## Cross-Language Design
The SDK keeps concepts aligned across languages:
| Concept | Rust | Go | C ABI |
|---------|------|----|-------|
| Provider configuration | `ProviderConfig` | `ProviderConfig` | provider config JSON |
| Chat request | `ChatRequest` | `ChatRequest` | request JSON |
| Chat response | `ChatResponse` | `ChatResponse` | response handle + JSON |
| Streaming | async stream | channel stream | callback stream |
| Errors | typed errors | typed errors | `nxuskit_last_error()` |
This lets teams choose a language per service without redesigning provider
selection, request structure, credentials, or feature-gating behavior.
## Native Boundary
The C ABI is the stable integration point for native consumers and higher-level
FFI wrappers. It uses opaque handles for providers, responses, and streams. Any
memory returned across the boundary has a matching free function.
Read the [C ABI Reference](/v1.0.0/nxuskit/reference/api-reference/) before embedding
nxusKit in C, C++, Go FFI, Python FFI, or another native runtime.
## Operational Flow
```text
Application code
-> language wrapper or C ABI
-> provider configuration
-> chat or streaming request
-> provider implementation
-> response, chunks, metadata, or typed error
```
For Pro features, the same call path also checks license state before executing
the feature. Community-tier features continue to run without a license token.
## What to Read Next
- [Installation](/v1.0.0/nxuskit/getting-started/installation/)
- [Provider Model](/v1.0.0/nxuskit/concepts/provider-model/)
- [Streaming](/v1.0.0/nxuskit/guides/streaming/)
- [C ABI Reference](/v1.0.0/nxuskit/reference/api-reference/)
- [CLI Input Format Reference](/v1.0.0/nxuskit/reference/cli-reference/)
- [Examples](/v1.0.0/nxuskit/examples/)
---
# Licensing
URL: https://docs.nxus.systems/v1.0.0/nxuskit/concepts/licensing
## Overview
nxusKit Pro features require a valid license token. This guide covers the
full lifecycle: authentication, activation, deployment, renewal, and
deactivation.
## Quick Start
```bash
# 1. Authenticate with your nxus.systems account
nxuskit-cli license login
# 2. Activate with your Purchase ID / Activation Key from My Products
nxuskit-cli license activate --key --accept-eula
# 3. Accept the End User License Agreement (required once per machine)
nxuskit-cli --accept-eula
# Or pre-accept for CI/CD (see EULA Acceptance below)
# 4. Verify activation
nxuskit-cli license status
# 5. Use Pro features — they just work
```
## EULA Acceptance
nxusKit requires acceptance of the End User License Agreement (EULA) before
use. Acceptance is recorded once per machine and persists across sessions.
### Interactive (TTY)
When running in an interactive terminal, the CLI prompts you to accept the EULA
on first use:
```
nxusKit End User License Agreement
...
Do you accept the EULA? [y/N]:
```
Type `y` and press Enter to accept. Acceptance is stored at
`~/.config/nxuskit/eula_accepted` (mode `0600`).
### Non-interactive (CI/CD)
In non-TTY environments (CI runners, Docker, scripts), the interactive prompt is
suppressed and the CLI exits with an error if the EULA has not been pre-accepted.
**Option 1 — `--accept-eula` flag** (recommended for CI):
```bash
nxuskit-cli --accept-eula license status
```
The flag is accepted on any subcommand. In GitHub Actions:
```yaml
- name: Verify license
run: nxuskit-cli --accept-eula license status
env:
NXUSKIT_LICENSE_TOKEN: ${{ secrets.NXUSKIT_LICENSE_TOKEN }}
```
**Option 2 — Pre-write the acceptance file**:
Create the file before invoking the CLI (useful in container image builds):
```bash
mkdir -p ~/.config/nxuskit
echo "accepted" > ~/.config/nxuskit/eula_accepted
chmod 0600 ~/.config/nxuskit/eula_accepted
```
### Acceptance File
| Path | `~/.config/nxuskit/eula_accepted` |
|------|-----------------------------------|
| Permissions | `0600` (owner read/write only) |
| Content | `accepted` (literal string) |
| Created by | Interactive prompt or `--accept-eula` flag |
---
## Licensing Environments
Release builds default to the production licensing API:
```
https://nxus.systems/licensing-api/v1
```
The production ES256 public key is embedded in release builds. Standard users do not configure the key or endpoint.
Development and test lanes may opt into a non-production endpoint with
`NXUSKIT_LICENSE_SERVER` and may label that lane with
`NXUSKIT_LICENSE_ENVIRONMENT`. These overrides are visible in
`nxuskit-cli license status --json` under `licensing.endpoint`,
`licensing.environment`, and `licensing.signing_key`; they are not silent
fallbacks.
## Offline-First Entitlements
After activation, Pro-gated entitlement checks validate the cached token
locally: signature, expiry, machine binding, product id, edition, and
entitlement claims are checked without contacting the licensing API. The
licensing API is contacted for activation, explicit refresh/sync, or recovery
from a local validation failure.
---
## Token Types
The SDK manages five token shapes:
| Token | Storage | Purpose | Expiry | Machine-bound? |
|-------|---------|---------|--------|----------------|
| **Auth** | `~/.config/nxuskit/auth.json` | Authenticates you with the licensing service | 30 days | No |
| **Developer** | `~/.nxuskit/license.token` | Authorizes purchased Pro SDK features for local developer workstations after storefront checkout | Subscription period | Yes (up to 3 machines) |
| **Deployment** | `NXUSKIT_LICENSE_TOKEN` env var | Authorizes customer shipping/runtime use of products that embed or depend on nxusKit | Never expires | No (org-scoped) |
| **Real Purchase** | `~/.nxuskit/license.token` | Backward-compatible SDK fixture/claim shape; production storefront activations currently issue Developer tokens | Subscription period | Yes |
| **Leased** | `~/.nxuskit/license.token` or `NXUSKIT_LICENSE_TOKEN` | CI/automation license that can be revoked server-side | Short lease, default 72 hours | Yes |
For CI automations that need a working Pro license but also need routine
revocation control, prefer a leased activation key over a long-lived deployment
token. Re-run `nxuskit-cli license activate --key
--accept-eula` on the runner before the 72-hour lease
expires. If the lease is blocked server-side, reactivation fails and any
already-issued token lapses at its normal `exp`.
## Step-by-Step Activation
### 1. Authenticate
Before activating a license, you must authenticate with your nxus.systems
account:
```bash
nxuskit-cli license login
```
This opens your browser to the nxus.systems login page. After logging in,
enter the code shown in your terminal. The auth token is stored at
`~/.config/nxuskit/auth.json` and used automatically for subsequent commands.
Check auth status:
```bash
nxuskit-cli license status
```
### 2. Activate
With authentication complete, activate your license. First-time activations
must accept the EULA:
```bash
nxuskit-cli license activate --key --accept-eula --json
```
The `--accept-eula` flag is recorded in
`~/.config/nxuskit/eula_accepted` (mode `0600`); subsequent activations on
the same machine do not need to repeat it. The `--json` flag is recommended
for scripting — see the JSON output schema in §3.
On success you will see (text mode):
```
Activated. 1/3 machines used.
Token stored: ~/.nxuskit/license.token
```
The license token is stored locally and validated on each SDK
initialization. **Activation uses an extended 30s client timeout
(`EXTENDED_TIMEOUT_SECS = 30`)** to absorb production cold-starts; the
matching proxy timeout extension is in
`nxus_device_auth/services/proxy_client.py::EXTENDED_TIMEOUT_PATHS`.
#### Real-purchase activation (production)
After purchasing a license at `https://nxus.systems/shop`, your purchase
IDs appear at `https://nxus.systems/my/products`. Each card shows the
exact CLI to run:
```bash
nxuskit-cli license activate --key nxus_purchase_ --accept-eula --json
```
Production storefront purchases currently issue `developer` license tokens:
machine-bound, seat-indexed, and valid through the commercial subscription
period. The SDK also accepts the legacy/fixture `real_purchase` claim shape for
compatibility, but it is not the production storefront issuer contract.
Customer shipping/runtime use belongs to the separate `deployment` token flow.
`leased` tokens are designed for CI/automation where revocation control matters — re-activate before the default 72-hour expiry;
blocking the lease server-side prevents future activations and existing tokens
lapse at `exp`.
### 3. Verify
Check your license status at any time:
```bash
nxuskit-cli license status
```
Output includes token type, edition, expiry date, machine count, licensing
environment, endpoint, and signing-key metadata.
For JSON output (useful in scripts):
```bash
nxuskit-cli license status --json
```
### 4. Use Pro Features
Once activated, Pro features work transparently:
```python
# Python — ZEN decision tables (Pro)
from nxuskit import zen_evaluate
result = zen_evaluate(table_path, input_data)
# Python — Solver (Pro)
from nxuskit import SolverConfig
```
```rust
// Rust — ZEN evaluation (Pro)
let result = nxuskit::zen_evaluate(&table, &input)?;
```
```go
// Go — Solver (Pro)
session, err := nxuskit.NewSolverSession(config)
```
## Trial Activation
To start a 30-day Pro trial, first register for an account and authenticate:
```bash
nxuskit-cli license login
nxuskit-cli license activate --trial
```
The trial provides full Pro-tier access for 30 days.
## Deployment Tokens
Deployment tokens are designed for production, CI/CD, and containerized
environments. They have no expiry and no machine binding.
### Setup
Set the deployment token as an environment variable:
```bash
export NXUSKIT_LICENSE_TOKEN=""
```
This works for:
- CI/CD pipelines (GitHub Actions, GitLab CI, Jenkins)
- Docker containers
- Kubernetes pods
- Production servers
- Serverless functions
### Version Ceiling
Deployment tokens include a **version ceiling** (e.g., `1.0`). The token
is valid for any SDK version at or below that ceiling:
- Token ceiling `1.0` → works with v1.0.0 and patch releases such as v1.0.5
- Token ceiling `1.0` → does NOT work with v1.1.0+
When you upgrade the SDK past the ceiling, you will see:
```
Deployment token covers up to v1.0.x. Update your deployment token for v1.1+ support.
```
Organizations with active support subscriptions receive updated deployment
tokens when new major.minor versions are released.
## Token Resolution Chain
The SDK resolves tokens from multiple sources in this precedence order:
| Priority | Source | Use Case |
|----------|--------|----------|
| 1 (highest) | `NXUSKIT_LICENSE_TOKEN` env var | CI/CD, containers |
| 2 | `~/.nxuskit/license.token` file | Local development |
| 3 (lowest) | API parameter | Embedded / programmatic |
The first valid token found is used. This order is the same for static and
dynamic linking modes.
## Multiple Machines
Each developer license supports up to 3 machine activations:
```bash
# Activate on machine 1
nxuskit-cli license activate --key
# → Activated. 1/3 machines used.
# Activate on machine 2
nxuskit-cli license activate --key
# → Activated. 2/3 machines used.
# If all 3 slots are used, deactivate one first:
nxuskit-cli deactivate
# → Deactivated. 2/3 machines used.
```
## Renewal
When your subscription approaches expiry (7 days out), the SDK logs a
once-per-session reminder:
```
Pro license expires in 7 days. Renew at your account dashboard.
```
After expiry, Pro features return:
```
License installation required.
```
Community features continue working without interruption.
## Deactivation
To free a machine activation slot:
```bash
nxuskit-cli deactivate
```
The local token file is removed and the activation count is decremented.
To revoke your auth session:
```bash
nxuskit-cli license logout
```
## Troubleshooting
| Symptom | Cause | Fix |
|---------|-------|-----|
| `License installation required.` | No valid license token found | Run `nxuskit-cli license login`, then `nxuskit-cli license activate --key ` |
| `LicenseExpired` | Subscription lapsed | Renew at your account dashboard |
| `EditionInsufficient` | Community binary | Download Pro binary |
| `VersionCeilingExceeded` | SDK upgraded past token ceiling | Request updated deployment token |
| `FeatureUnavailable` | Multiple possible causes | Run `nxuskit-cli license status` for details |
| Auth token expired | 30-day auth session ended | Run `nxuskit-cli license login` again |
---
# Provider Model
URL: https://docs.nxus.systems/v1.0.0/nxuskit/concepts/provider-model
## Overview
nxusKit presents LLMs, local inference servers, rule engines, solvers, and test
adapters through one provider interface. Your application chooses a
`provider_type`, sends a `ChatRequest`, and receives a structured response. The
same request/response pattern works whether the backend is OpenAI, Anthropic,
Ollama, CLIPS, Z3, Mock, or Loopback.
The goal is portability: application code can switch providers without changing
its surrounding orchestration, logging, retry, or licensing logic.
## Provider Types
| Category | Provider types | Use when |
|----------|----------------|----------|
| Cloud LLMs | `openai`, `claude`, `groq`, `mistral`, `fireworks`, `together`, `openrouter`, `perplexity` | You need hosted models, managed scaling, or provider-specific model quality. |
| Local LLMs | `ollama`, `lmstudio`, `local` | You need local inference, data locality, lower latency, or offline development. |
| Reasoning engines | `clips`, `z3` | You need deterministic rule evaluation, constraint solving, or explainable decisions. |
| Utility providers | `mock`, `loopback`, `mcp` | You need tests, integration checks, or model-context tooling. |
## Configuration Shape
All providers use the same high-level configuration fields:
```json
{
"provider_type": "openai",
"model": "gpt-4o",
"api_key": "sk-...",
"base_url": "https://api.openai.com/v1",
"timeout_ms": 30000,
"options": {}
}
```
Only `provider_type` is always required. API keys can come from explicit
configuration, environment variables, or the credential store. See
[Authentication](/v1.0.0/nxuskit/getting-started/authentication/) for the precedence
rules.
## Request Flow
1. Create a provider from configuration.
2. Build a chat request with a model name and messages.
3. Call `chat()` for a complete response or `chat_stream()` for incremental chunks.
4. Read response content and provider metadata.
```rust
use nxuskit::{ChatRequest, Message, NxuskitProvider, ProviderConfig};
let provider = NxuskitProvider::new(ProviderConfig {
provider_type: "openai".into(),
..Default::default()
})?;
let request = ChatRequest::new("gpt-4o")
.with_message(Message::user("Summarize the provider model."));
let response = provider.chat(request)?;
println!("{}", response.content);
```
## Capabilities
Providers advertise capabilities such as streaming, vision, JSON mode, tool
calling, deterministic seeds, and local model discovery. Use the capability
metadata to choose a provider at runtime instead of hard-coding assumptions.
For provider-specific details, see:
- [Cloud LLM Providers](/v1.0.0/nxuskit/reference/providers/cloud-llms/)
- [Local LLM Providers](/v1.0.0/nxuskit/reference/providers/local-llms/)
- [Expert System & Utility Providers](/v1.0.0/nxuskit/reference/providers/expert-systems/)
- [Z3 Constraint Satisfaction Provider](/v1.0.0/nxuskit/reference/providers/z3-solver/)
## Choosing a Provider
| Need | Start with |
|------|------------|
| General hosted chat, tools, and JSON output | Cloud LLM provider |
| Local development without external API calls | Ollama or LM Studio |
| Embedded local inference with direct model lifecycle control | In-process local provider |
| Deterministic business rules | CLIPS |
| Constraint solving and optimization | Z3 |
| Unit tests with predictable responses | Mock or Loopback |
---
# Tier System
URL: https://docs.nxus.systems/v1.0.0/nxuskit/concepts/tier-system
## Overview
nxusKit SDK uses a dual-edition model for the public SDK surface.
The public `nxusKit` repository contains nxusKit SDK Community Edition, which is free and open source. CE is not a trial, teaser, or time-limited evaluation; it is intended to remain useful on its own. We do not move released CE features behind the Pro paywall, and code released as CE remains available under its open-source license.
Community Edition is useful on its own without Pro. The public `nxusKit-examples` repository labels examples by edition, so developers can see which workflows run with CE alone and which require Pro.
nxusKit SDK Pro adds proprietary commercial capabilities for teams that need solver-backed workflows, ZEN decision tables, plugin loading, and trust-policy features. Pro is distributed under a paid, trial, or evaluation entitlement. **Enterprise** adds delegated trust and custom plugin configuration for large organizations.
## Feature Matrix
| Feature Domain | Community | Pro | Enterprise |
|----------------|:---------:|:---:|:----------:|
| LLM Cloud Providers (OpenAI, Claude, xAI Grok, Groq, Mistral, Fireworks, Together, OpenRouter, Perplexity) | Yes | Yes | Yes |
| LLM Local Providers (Ollama, LM Studio) | Yes | Yes | Yes |
| CLIPS Rule Engine (ClipsSession API) | Yes | Yes | Yes |
| Bayesian Network Inference | Yes | Yes | Yes |
| Auth Helper (API-key management, credential store) | Yes | Yes | Yes |
| Tool Calling / Function Calling | Yes | Yes | Yes |
| Streaming & Token Usage | Yes | Yes | Yes |
| Retry & Adaptive Rate Limiting | Yes | Yes | Yes |
| Vision / Image Support | Yes | Yes | Yes |
| OAuth Authentication Infrastructure | Yes | Yes | Yes |
| Cross-language Parity (Rust, Go, Python) | Yes | Yes | Yes |
| Static + Dynamic Linking | Yes | Yes | Yes |
| **ZEN Decision Tables** | — | Yes | Yes |
| **Constraint Solver (Z3-backed)** | — | Yes | Yes |
| **Plugin Loading & Trust Policy** | — | Yes | Yes |
| **MCP (Model Context Protocol)** | — | Yes | Yes |
| **CLIPS Advanced (programmatic rules, session persistence)** | — | Yes | Yes |
| **Custom Plugin Configuration Paths** | — | — | Yes |
| **Delegated Trust Roots** | — | — | Yes |
| **Priority Support** | — | — | Yes |
## Numerical Limits
| Limit | Community | Pro | Enterprise |
|-------|:---------:|:---:|:----------:|
| Max concurrent CLIPS sessions | 16 | 64 | 256 |
| Max cached rulebases | 8 | 32 | 128 |
| Max rules per session | 500 | 5,000 | 50,000 |
| Max facts per session | 10,000 | 100,000 | 1,000,000 |
| Max Bayesian network nodes | 50 | 500 | 5,000 |
| Max solver constraints | — | 10,000 | 100,000 |
| Machine activations (developer tokens) | — | 3 | Unlimited |
## SDK Wrapper Availability
All editions provide wrappers for all three languages:
| Language | Package | Install |
|----------|---------|---------|
| Rust | `nxuskit` | `cargo add nxuskit` |
| Go | `nxuskit` | `go get github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go` |
| Python | `nxuskit-py` | `pip install nxuskit-py` |
## Example Tier Assignments
| Example | Tier | Reason |
|---------|------|--------|
| LLM basics, streaming, tool calling | Community | Uses cloud/local LLM providers |
| CLIPS basics, CLIPS-LLM hybrid | Community | CLIPS engine is Community-tier |
| Bayesian network inference | Community | BN inference is Community-tier |
| Gamer (game AI solver) | **Pro** | Uses Z3 constraint solver |
| Racer (optimization) | **Pro** | Uses Z3 constraint solver |
| Ruler (rule evaluation) | **Pro** | Uses ZEN decision tables |
| Solver (generic CSP) | **Pro** | Uses Z3 constraint solver |
| Riffer (music generation) | **Pro** | Uses solver + CLIPS pipeline |
| Sweeper (minesweeper AI) | **Pro** | Uses Z3 constraint solver |
## Licensing
| Aspect | Community | Pro | Enterprise |
|--------|-----------|-----|------------|
| License type | Open-source | Commercial subscription | Commercial subscription |
| Token required | No | Yes (developer or deployment) | Yes |
| Machine activations | N/A | Up to 3 per license | Unlimited |
| Deployment tokens | N/A | Unlimited instances, no per-seat fees | Unlimited |
| Version ceiling | N/A | Locked to major.minor at purchase time | Locked to major.minor |
| Trial | N/A | 30-day trial (registration required) | Contact sales |
## Getting Started with Pro
1. Create an account and register for a trial or purchase a license
2. Authenticate: `nxuskit-cli license login`
3. Activate on your machine: `nxuskit-cli license activate --key `
4. For CI/CD: set `NXUSKIT_LICENSE_TOKEN` with your deployment token
See the [License Activation Guide](/v1.0.0/nxuskit/concepts/licensing/) for the full workflow.
---
# nxusKit Examples
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples
[](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE)



**[Examples Docs](https://docs.nxus.systems/nxuskit/examples/)** · **[SDK Docs](https://docs.nxus.systems/nxuskit/)** · **[nxusKit SDK](https://github.com/nxus-SYSTEMS/nxusKit)** · **[Examples Portfolio](https://nxus.systems/examples)** · **[Website](https://nxus.systems)**
34 production-quality examples for the nxusKit SDK in Rust, Go, and Python, plus selected CLI/Bash implementations for shell-first orchestration — covering LLM patterns, CLIPS rule engines, Z3 constraint solvers, Bayesian networks, and ZEN decision tables.
## A Word About CLIPS
During its development at NASA from 1985 to 1996, the primary CLIPS
contributors were: Robert Savely, who conceived and championed the project;
Chris Culbert, who managed the project; Gary Riley and Brian Dantes, who were
the lead developers; and Frank Lopez, who developed the first version. Since
leaving NASA in 1996, Gary Riley has maintained CLIPS as public domain
software.
## Quick Start
```bash
# 1. Install the SDK (see https://docs.nxus.systems/nxuskit/getting-started/installation/)
# 2. Set up this project
source ~/.nxuskit/sdk/current/scripts/setup-sdk.sh # Go, env vars, library paths
./scripts/setup-sdk-symlink.sh # Rust Cargo paths override
# 3. Run an example
cargo run --manifest-path examples/patterns/basic-chat/rust/Cargo.toml # Rust
go run -tags nxuskit ./examples/patterns/basic-chat/go # Go
python examples/patterns/basic-chat/python/main.py # Python
```
## Examples
### Patterns — Reusable SDK integration patterns
| Example | Edition | Description | Languages |
|---------|---------|-------------|-----------|
| [basic-chat](/v1.0.0/nxuskit/examples/patterns/basic-chat/) | Community | Basic chat completion with a simple prompt | Rust, Go, Python |
| [streaming](/v1.0.0/nxuskit/examples/patterns/streaming/) | Community | Streaming chat completion with real-time output | Rust, Go, Python |
| [multi-provider](/v1.0.0/nxuskit/examples/patterns/multi-provider/) | Community | Using multiple providers in one application | Rust, Go, Python, CLI/Bash |
| [convenience-api](/v1.0.0/nxuskit/examples/patterns/convenience-api/) | Community | LiteLLM-style convenience API usage | Rust, Go |
| [blocking-api](/v1.0.0/nxuskit/examples/patterns/blocking-api/) | Community | Synchronous blocking API for simpler use cases | Rust, Go |
| [capability-detection](/v1.0.0/nxuskit/examples/patterns/capability-detection/) | Community | Detecting provider capabilities at runtime | Rust, Go, CLI/Bash |
| [cost-routing](/v1.0.0/nxuskit/examples/patterns/cost-routing/) | Community | Cost-aware provider routing and selection | Rust, Go, Python, CLI/Bash |
| [polymorphic](/v1.0.0/nxuskit/examples/patterns/polymorphic/) | Community | Polymorphic provider patterns with trait objects | Rust, Go |
| [retry-fallback](/v1.0.0/nxuskit/examples/patterns/retry-fallback/) | Community | Retry and fallback strategies across providers | Rust, Go, Python, CLI/Bash |
| [structured-output](/v1.0.0/nxuskit/examples/patterns/structured-output/) | Community | JSON mode and structured output generation | Rust, Go, Python, CLI/Bash |
| [timeout-config](/v1.0.0/nxuskit/examples/patterns/timeout-config/) | Community | Timeout configuration and connection management | Rust, Go, Python |
| [token-budget](/v1.0.0/nxuskit/examples/patterns/token-budget/) | Community | Token budget management and cost estimation | Rust, Go, Python, CLI/Bash |
| [vision](/v1.0.0/nxuskit/examples/patterns/vision/) | Community | Vision and multimodal capabilities with images | Rust, Go, Python, CLI/Bash |
| [auth-helper](/v1.0.0/nxuskit/examples/patterns/auth-helper/) | Community | OAuth login flow and credential management helper | Rust, Go |
| ↳ `status` | | List provider authentication status and stored credentials | |
| ↳ `set` | | Store an API key for a specific provider | |
| ↳ `remove` | | Remove a stored API key for a provider | |
| ↳ `dashboard` | | Open provider credential dashboard in browser | |
| [solver](/v1.0.0/nxuskit/examples/patterns/solver/) | Pro | Z3 constraint solver integration via nxusKit SDK | Rust, Go, Python, CLI/Bash |
| ↳ `theme-park` | | Budget and space planning for a theme park with rides, food courts, and entertainment zones | |
| ↳ `space-colony` | | Resource allocation for a space colony dealing with solar storm what-if scenarios | |
| ↳ `fantasy-draft` | | Fantasy sports draft optimization under salary cap with injury what-if analysis | |
| ↳ real-world: **Theme Park Planning** | | Facility layout, capital budgeting, resource allocation | |
| ↳ real-world: **Space Colony Planning** | | Infrastructure sizing, capacity planning, disaster recovery modeling | |
| ↳ real-world: **Fantasy Sports Draft** | | Portfolio optimization, team composition, auction bidding strategies | |
| [bayesian-inference](/v1.0.0/nxuskit/examples/patterns/bayesian-inference/) | Community | Bayesian network inference via nxusKit SDK | Rust, Go, Python, CLI/Bash |
| ↳ `haunted-house` | | Investigate a haunted house — is it a ghost or a raccoon? | |
| ↳ `coffee-shop` | | Diagnose bad espresso from grind size, temperature, and bean age | |
| ↳ `plant-doctor` | | Diagnose a sick plant from overwatering, nutrient, and disease evidence | |
| ↳ real-world: **Haunted House** | | Fault diagnosis, anomaly detection, sensor fusion from multiple noisy sensors pointing to hidden causes | |
| ↳ real-world: **Coffee Shop** | | Manufacturing quality control, process parameter tuning, root cause analysis in production | |
| ↳ real-world: **Plant Doctor** | | Medical diagnosis, agricultural advisory systems, multi-symptom differential diagnosis | |
| [solver-what-if](/v1.0.0/nxuskit/examples/patterns/solver-what-if/) | Pro | What-if scenario analysis with solver scoping | Rust, Go, Python, CLI/Bash |
| ↳ `wedding` | | Wedding budget planning with $25k constraint and vendor what-if scenarios | |
| ↳ `mars` | | Mars colony resource allocation with dust storm what-if disruptions | |
| ↳ `recipe` | | Recipe scaling with vegan substitution — may be UNSAT | |
| ↳ real-world: **Wedding Budget Planning** | | Event planning, capital budgeting, portfolio allocation | |
| ↳ real-world: **Mars Colony Planning** | | Infrastructure sizing, supply chain planning, disaster preparedness | |
| ↳ real-world: **Recipe Scaling** | | Manufacturing scaling, formulation optimization, process engineering | |
### Integrations — Combining SDK features
| Example | Edition | Description | Languages |
|---------|---------|-------------|-----------|
| [ollama](/v1.0.0/nxuskit/examples/integrations/ollama/) | Community | Using Ollama for local inference | Rust, Go, Python |
| [lmstudio](/v1.0.0/nxuskit/examples/integrations/lmstudio/) | Community | Using LM Studio for local inference | Rust, Go |
| [alert-triage](/v1.0.0/nxuskit/examples/integrations/alert-triage/) | Community | Alert triage with LLM-powered analysis | Rust, Go, CLI/Bash |
| [cli-assistant](/v1.0.0/nxuskit/examples/integrations/cli-assistant/) | Community | Interactive CLI assistant with LLM backend | Rust, Go |
| [clips-basics](/v1.0.0/nxuskit/examples/integrations/clips-basics/) | Community | CLIPS rule engine basics via nxusKit SDK | Rust, Go, CLI/Bash |
| [clips-llm-hybrid](/v1.0.0/nxuskit/examples/integrations/clips-llm-hybrid/) | Community | Hybrid CLIPS rules + LLM reasoning | Rust, Go, Python, CLI/Bash |
| [common-sense-guardrails](/v1.0.0/nxuskit/examples/integrations/common-sense-guardrails/) | Community Runs in Community Edition. Pro adds optional Solver and ZEN proof stages. | Progressive LLM guardrails with Community CLIPS validation and optional Pro proof stages | Python, CLI/Bash |
| ↳ `car-wash` | | Catch the classic car-wash walk-vs-drive failure with object-presence rules and optional solver proof | |
| ↳ `coupon-stack` | | Reject promotion stacking that violates eligibility and margin policy, with optional ZEN validation | |
| ↳ `pallet-door` | | Block unsafe warehouse advice that ignores dimensional clearance, with optional solver what-if | |
| ↳ `cold-chain` | | Prevent cheaper logistics recommendations that violate handling requirements, with optional ZEN validation | |
| ↳ real-world: **LLM answer validation** | | Catch plausible recommendations that fail physical, operational, or policy preconditions before they reach users | |
| ↳ real-world: **Policy enforcement** | | Turn free-form answers into facts, apply deterministic rules, and produce auditable repair context | |
| ↳ real-world: **Operational decision support** | | Preserve fast LLM drafting while requiring concrete feasibility evidence for workflow-critical recommendations | |
| [model-research-harness](/v1.0.0/nxuskit/examples/integrations/model-research-harness/) | Community Runs in Community Edition. Future Pro profiles may add Solver portfolio optimization and ZEN decision tables. | Python-first harness for provider-neutral model research, Promptfoo import, CLIPS policy, Bayesian scoring, and dry-run lifecycle recommendations | Python, CLI/Bash |
| ↳ `basic-ticket-routing` | | Run a credentials-free support ticket classification research smoke | |
| ↳ `promptfoo-import` | | Import a Promptfoo config and run the converted nxusKit harness matrix | |
| ↳ `software-dev` | | Evaluate code analysis, bug finding, patching, generation, refactoring, and review outputs | |
| ↳ real-world: **Model evaluation** | | Score model candidates against task-specific outputs and report confidence instead of relying on ad hoc impressions | |
| ↳ real-world: **Provider comparison** | | Compare local and cloud providers through one provider-neutral workflow while keeping capability claims honest | |
| ↳ real-world: **Lifecycle policy** | | Generate dry-run pull, pin, keep, or retest recommendations bounded by deterministic policy | |
| ↳ real-world: **Software development workflow research** | | Exercise code analysis, bug finding, bugfixing, generation, refactoring, and review scenarios with public-safe fixtures | |
| [bn-solver-clips-pipeline](/v1.0.0/nxuskit/examples/integrations/bn-solver-clips-pipeline/) | Pro | Three-stage BN prediction → Solver optimization → CLIPS safety pipeline | Rust, Go, CLI/Bash |
| ↳ `festival` | | Music festival staging — crowd predictions drive band scheduling and safety | |
| ↳ `rescue` | | Search and rescue — survivor probability drives team assignment and safety checks | |
| ↳ `bakery` | | Bakery scheduling — demand forecasts drive oven allocation and allergen separation | |
| ↳ real-world: **Event planning** | | Predict attendance, optimize resource allocation, enforce safety codes | |
| ↳ real-world: **Emergency response** | | Estimate survival windows, deploy rescue assets, enforce operational protocols | |
| ↳ real-world: **Manufacturing** | | Forecast demand, schedule production, enforce quality and safety standards | |
| ↳ real-world: **Logistics** | | Predict delivery volumes, optimize fleet routing, enforce regulatory compliance | |
| ↳ real-world: **Healthcare** | | Predict patient load, optimize staff scheduling, enforce clinical safety protocols | |
| [llm-solver-hybrid](/v1.0.0/nxuskit/examples/integrations/llm-solver-hybrid/) | Pro | Hybrid LLM + Z3 solver problem solving | Rust, Go, Python, CLI/Bash |
| ↳ `seating` | | Wedding dinner seating — 12 guests across 3 tables with constraints | |
| ↳ `dungeon` | | Dungeon layout — 5 rooms with boss and treasure placement rules | |
| ↳ `road-trip` | | Road trip planning — 14 days across 5 national parks with preferences | |
| [bn-structure-learning](/v1.0.0/nxuskit/examples/integrations/bn-structure-learning/) | Community | Bayesian network structure learning from data | Rust, Go, Python |
| ↳ `golf` | | Golf course conditions — weather, soil, and maintenance factor learning | |
| ↳ `bmx` | | BMX performance — skill level, technique, and jump factor learning | |
| ↳ `sourdough` | | Sourdough baking — feeding schedule, flour type, and temperature factor learning | |
| ↳ real-world: **Epidemiology** | | Discover disease risk factor relationships from patient records | |
| ↳ real-world: **Manufacturing** | | Identify root causes of defects from production data | |
| ↳ real-world: **Finance** | | Map causal relationships between economic indicators | |
| ↳ real-world: **Genomics** | | Learn gene regulatory networks from expression data | |
| ↳ real-world: **Quality control** | | Find which process parameters affect product quality | |
| [zen-decisions](/v1.0.0/nxuskit/examples/integrations/zen-decisions/) | Pro | ZEN decision table evaluation via nxusKit SDK | Rust, Go, Python, CLI/Bash |
| ↳ `maze-rat` | | First Hit Policy — route a maze runner through personality-driven decisions | |
| ↳ `potion` | | Collect Hit Policy — match ingredient lists against brewing recipes | |
| ↳ `food-truck` | | Expression Nodes — compute dynamic pricing with conditional logic | |
### Apps — Complete applications
| Example | Edition | Description | Languages |
|---------|---------|-------------|-----------|
| [puzzler](/v1.0.0/nxuskit/examples/apps/puzzler/) | Pro | Multi-approach puzzle solver comparing CLIPS, LLM, and hybrid strategies | Rust, Go |
| ↳ `sudoku` | | Solve Sudoku puzzles using CLIPS constraint propagation | |
| ↳ `set-game` | | Find valid SET card combinations using CLIPS pattern matching | |
| ↳ `compare` | | Side-by-side comparison of CLIPS, LLM, and hybrid solvers | |
| [racer](/v1.0.0/nxuskit/examples/apps/racer/) | Pro | CLIPS vs LLM head-to-head benchmarking tool | Rust, Go |
| ↳ `race` | | Head-to-head CLIPS vs LLM race on a single problem | |
| ↳ `benchmark` | | Statistical benchmarking with multiple runs and timing | |
| ↳ `list` | | List all available problems with difficulty ratings | |
| ↳ `describe` | | Show detailed description of a specific problem | |
| [riffer](/v1.0.0/nxuskit/examples/apps/riffer/) | Pro | Music sequence analysis and transformation tool (still learning to shred) | Rust, Go |
| ↳ `analyze` | | Analyze a music sequence for key, intervals, and rhythm patterns | |
| ↳ `score` | | Score a sequence on six musical dimensions | |
| ↳ `transform` | | Transform a sequence — transpose, invert, or retrograde | |
| ↳ `convert` | | Convert between MIDI and MusicXML formats | |
| [ruler](/v1.0.0/nxuskit/examples/apps/ruler/) | Pro | LLM-powered CLIPS rule generator with automatic validation | Rust, Go, CLI/Bash |
| ↳ `generate` | | Generate CLIPS rules from natural language descriptions | |
| ↳ `validate` | | Validate CLIPS rule syntax and semantic correctness | |
| ↳ `save` | | Save generated rules to a file for later use | |
| ↳ `load` | | Load previously saved rules from a file | |
| ↳ `examples` | | Run progressive complexity examples demonstrating rule generation | |
| [arbiter](/v1.0.0/nxuskit/examples/apps/arbiter/) | Pro | CLIPS-validated LLM retry app with rule-based answer verification | Rust, Go, CLI/Bash |
| ↳ `classification` | | Categorize input text into specified categories | |
| ↳ `extraction` | | Extract structured information from unstructured text | |
| ↳ `reasoning` | | Perform logical inference and multi-step reasoning | |
## SDK Editions
| Badge | Meaning |
|-------|---------|
| **Community** | Runs with the free OSS SDK |
| **Pro** | Requires a Pro license ([activation guide](https://github.com/nxus-SYSTEMS/nxusKit)) |
Edition labels describe the minimum runnable edition for the default path. A Community example can still list optional Pro enhancements; those stages are disabled by default and require a Pro entitlement only when you run them.
See `conformance/example-tiers.json` for the full tier map.
## Project Structure
```
examples/
├── patterns/ Community-tier reusable patterns
├── integrations/ SDK feature combinations
├── apps/ Complete applications (mostly Pro tier)
└── shared/ Shared libraries and helpers (Rust, Go, Python, CLI/Bash)
conformance/ Example manifest and tier definitions
scripts/ Build and test helpers
```
## Building
All examples require the nxusKit SDK. Run these once after cloning:
```bash
# Set up Go workspace, env vars, and native library paths
source ~/.nxuskit/sdk/current/scripts/setup-sdk.sh
# Set up Rust Cargo paths override (generates .cargo/config.toml)
./scripts/setup-sdk-symlink.sh
```
The first script creates Go workspace files and exports environment variables. The second generates a `.cargo/config.toml` that tells Cargo where to find the installed Rust SDK (the generated file is `.gitignore`d — each developer runs this once).
### Rust
```bash
cargo run --manifest-path examples///rust/Cargo.toml
```
### Go
```bash
go run -tags nxuskit ./examples///go/cmd
```
### Python
```bash
python examples///python/main.py
```
### CLI/Bash
```bash
cd examples///bash
make run
```
---
Built with gratitude for the open-source projects that make nxusKit possible.
See [ACKNOWLEDGEMENTS.md](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/ACKNOWLEDGEMENTS.md) for a curated list of key projects.
---
## License
nxusKit Examples is dual-licensed under MIT or Apache 2.0, at your option. See [LICENSE](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE), [LICENSE-MIT](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE-MIT), and [LICENSE-APACHE](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/LICENSE-APACHE).
Copyright 2025-2026 nxus.SYSTEMS LLC.
---
# Arbiter - Auto-Retry LLM with CLIPS Validation
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/apps/arbiter
A command-line tool demonstrating the Solver pattern: using CLIPS rules to evaluate LLM output quality and automatically retry with adjusted parameters when validation fails.
> Stop accepting unreliable LLM output — validate every response against CLIPS rules and retry automatically until your standards are met.
**Scenarios**: `classification` · `extraction` · `reasoning`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** CLIPS-validated LLM retry app with rule-based answer verification
- **Scenario:** Submit questions to an LLM and validate answers against CLIPS rules, retrying on validation failure
- **`tech_tags` in manifest:** `CLIPS, LLM` — example id **`arbiter`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Real-World Application
Operations research tool, constraint modeling workbench.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
Solver
## CLIPS integration path (validation)
Go CLIPS validation uses **provider chat** with local `go/clips_wire.go` types mirroring `ClipsInput` / `ClipsOutput`. For **Session API** access, use `nxuskit.ClipsSession`. Reference: `conformance/clips-json-contract.json`; nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/arbiter`:
cd rust && cargo build
cd go && make build
```
## Features
- **LLM Output Validation** - Use CLIPS rules to evaluate response quality
- **Automatic Retry** - Retry with adjusted parameters on validation failure
- **Configurable Strategies** - Define retry strategies for different failure modes
- **Multiple Conclusion Types** - Classification, extraction, and reasoning tasks
- **Scoring System** - Score attempts based on validation results
## Installation
### Rust
```bash
cd examples/apps/arbiter/rust
cargo build --release
```
### Go
```bash
cd examples/apps/arbiter/go
make build
```
## Run
### Rust
```bash
cd examples/apps/arbiter/rust
# Show help
cargo run -- --help
# Run classification task
cargo run -- -t classification -i "This product is amazing!" --categories "positive,negative,neutral"
# Run with custom config
cargo run -- -c config.yaml -i "Analyze this text"
# Run extraction task
cargo run -- -t extraction -i "John works at Acme Corp in New York"
# Verbose mode
cargo run -- -v -t reasoning -i "If A implies B and B implies C, what can we conclude about A and C?"
```
### Go
```bash
cd examples/apps/arbiter/go
# Show help
./bin/arbiter --help
# Run classification
./bin/arbiter -t classification -i "Great service!" --categories "positive,negative,neutral"
```
## Command Line Options
```
USAGE:
arbiter [OPTIONS] -i
OPTIONS:
-c, --config Configuration file path
-i, --input Input text to process
-t, --type Conclusion type: classification, extraction, reasoning
--categories Comma-separated categories for classification
--max-retries Maximum retry attempts (default: 3)
-v, --verbose Show detailed progress
-h, --help Show help message
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/arbiter --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/arbiter --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Conclusion Types
### Classification
Categorize input into predefined categories.
```bash
arbiter -t classification -i "I love this!" --categories "positive,negative,neutral"
```
### Extraction
Extract structured information from text.
```bash
arbiter -t extraction -i "Contact John at john@example.com or 555-1234"
```
### Reasoning
Perform logical reasoning and inference.
```bash
arbiter -t reasoning -i "All cats are mammals. Whiskers is a cat. What is Whiskers?"
```
## Configuration
Create a YAML configuration file for custom settings:
```yaml
# arbiter-config.yaml
max_retries: 5
strategies:
- failure_type: invalid_category
adjustments:
temperature: -0.2
prompt_suffix: "Choose only from the given categories."
- failure_type: incomplete_extraction
adjustments:
temperature: 0
prompt_suffix: "Extract all mentioned entities."
- failure_type: invalid_reasoning
adjustments:
temperature: -0.1
prompt_suffix: "Show your reasoning step by step."
```
## Example Output
### Classification Result
```
=== Solver: Classification Task ===
Input: "This product exceeded my expectations!"
Categories: positive, negative, neutral
Attempt 1:
LLM Response: "positive"
Validation: PASSED
Score: 100
Result: positive (1 attempt, 45ms)
```
### With Retry
```
=== Solver: Classification Task ===
Input: "It's okay I guess"
Categories: positive, negative, neutral
Attempt 1:
LLM Response: "somewhat positive"
Validation: FAILED (invalid category)
Strategy: Reduce temperature, clarify categories
Attempt 2:
LLM Response: "neutral"
Validation: PASSED
Score: 95
Result: neutral (2 attempts, 1.2s)
```
## Retry Strategies
The arbiter includes default strategies for common failure modes:
| Failure Type | Adjustment |
|--------------|------------|
| Invalid category | Lower temperature, clarify options |
| Incomplete extraction | Reset temperature, request all entities |
| Invalid reasoning | Lower temperature, request step-by-step |
| Confidence too low | Increase temperature slightly |
| Format error | Add format examples to prompt |
## Architecture
```
arbiter/
├── rust/
│ ├── src/main.rs # CLI entry point
│ └── Cargo.toml
├── go/
│ ├── cmd/main.go # CLI entry point
│ ├── solver.go # Core solver logic
│ ├── strategies.go # Retry strategies
│ ├── validator.go # CLIPS validation
│ └── go.mod
└── shared/
├── rules/ # CLIPS validation rules
└── configs/ # Example configurations
```
## How It Works
1. **Initial Request**: Send input to LLM with configured prompt
2. **Validation**: Pass LLM response through CLIPS validation rules
3. **Evaluation**: Score the response based on validation results
4. **Retry Decision**: If validation fails, find matching retry strategy
5. **Adjustment**: Apply strategy adjustments (temperature, prompt, etc.)
6. **Repeat**: Retry up to max_retries times
7. **Result**: Return best successful attempt or highest-scoring failure
## Notes
- CLIPS validation rules are in `shared/rules/classification-eval.clp`
- Build Go with `-tags=clips` for real ClipsProvider integration
- LLM approach requires API key (ANTHROPIC_API_KEY or OPENAI_API_KEY)
## Testing
```bash
# Rust
cd examples/apps/arbiter/rust
cargo test
# Go
cd examples/apps/arbiter/go
go test -v ./...
```
## License
Part of the nxusKit project.
---
# Puzzler - Puzzle Solver Comparison
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/apps/puzzler
A command-line tool for comparing three approaches to solving logic puzzles: CLIPS-only, LLM-only, and Hybrid.
> Compare CLIPS rule-based constraint solving against LLM reasoning side by side, then combine both in a hybrid approach for real puzzle problems.
**Scenarios**: `sudoku` · `set-game` · `compare`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS · Solver
- **Summary:** Multi-approach puzzle solver comparing CLIPS, LLM, and hybrid strategies
- **Scenario:** Compare CLIPS rule-based, LLM reasoning, and hybrid approaches for solving logic puzzles
- **`tech_tags` in manifest:** `CLIPS, LLM, Solver` — example id **`puzzler`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Real-World Application
Educational puzzle solver, constraint programming tutorial.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
Solver
## CLIPS integration path (CLIPS-only / hybrid modes)
The Go CLIPS solver path uses **provider chat** (`go/clips_wire.go` mirrors `ClipsInput` / `ClipsOutput` JSON). It is not the **Session API** (`nxuskit.ClipsSession`). See `conformance/clips-json-contract.json` and nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/puzzler`:
cd rust && cargo build
cd go && make build
```
## Features
- **Sudoku Puzzles** - Solve Sudoku puzzles of varying difficulty
- **Set Game** - Find valid sets in Set card game hands
- **Three Approaches**:
- **CLIPS-only**: Pure rule-based constraint propagation
- **LLM-only**: Pure LLM reasoning
- **Hybrid**: CLIPS primary with LLM fallback for stuck states
- **Comparison Mode** - Run all approaches and compare results
## Installation
### Rust
```bash
cd examples/apps/puzzler/rust
cargo build --release
```
### Go
```bash
cd examples/apps/puzzler/go
make build
```
## Run
### Rust
```bash
cd examples/apps/puzzler/rust
# Show help
cargo run -- --help
# Solve a Sudoku puzzle
cargo run -- sudoku -p easy
# Compare all approaches on Sudoku
cargo run -- sudoku --compare
# Play Set game
cargo run -- set -p random
# Compare approaches on Set game
cargo run -- set --compare
```
### Go
```bash
cd examples/apps/puzzler/go
# Show help
./bin/puzzler --help
# Solve a Sudoku puzzle
./bin/puzzler sudoku -p easy
# Compare all approaches
./bin/puzzler sudoku --compare
```
## Command Line Options
```
USAGE:
puzzler [OPTIONS]
GAMES:
sudoku Solve Sudoku puzzles
set Find sets in Set game cards
OPTIONS:
-p, --puzzle Puzzle identifier (easy, medium, hard, expert, or custom)
-a, --approach Solver approach: clips, llm, hybrid (default: hybrid)
-c, --compare Compare all three approaches
-v, --verbose Show detailed solving steps
-h, --help Show help message
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/puzzler --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/puzzler --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Puzzle Types
### Sudoku
Difficulty levels:
- **easy** - Many given numbers, straightforward solving
- **medium** - Moderate difficulty
- **hard** - Requires advanced techniques
- **expert** - Very few givens, requires backtracking
### Set Game
Find valid sets where each attribute (color, shape, shading, number) is either all the same or all different across three cards.
## Example Output
### Sudoku Comparison
```
=== Sudoku Puzzle: easy ===
Approach | Time | Solved | Moves
--------------|---------|--------|-------
CLIPS-only | 12ms | Yes | 47
LLM-only | 2.3s | Yes | 52
Hybrid | 15ms | Yes | 47
Winner: CLIPS-only (fastest)
```
### Set Game
```
=== Set Game: 12 cards ===
Found 3 valid sets:
Set 1: Red-Oval-Solid-1, Red-Oval-Striped-2, Red-Oval-Empty-3
Set 2: Green-Diamond-Solid-1, Purple-Diamond-Striped-1, Red-Diamond-Empty-1
Set 3: ...
```
## Architecture
```
puzzler/
├── rust/
│ ├── src/main.rs # CLI entry point
│ └── Cargo.toml
├── go/
│ ├── cmd/main.go # CLI entry point
│ ├── sudoku.go # Sudoku solver logic
│ ├── setgame.go # Set game solver logic
│ └── go.mod
└── shared/
└── puzzles/ # Puzzle definitions
```
## Notes
- CLIPS validation rules are in `shared/puzzles/`
- LLM solving uses Ollama by default (no API key required)
- Optional: Set ANTHROPIC_API_KEY or OPENAI_API_KEY for cloud providers
## Testing
```bash
# Rust
cd examples/apps/puzzler/rust
cargo test
# Go
cd examples/apps/puzzler/go
go test -v ./...
```
## License
Part of the nxusKit project.
---
# Racer - CLIPS vs LLM Head-to-Head Competition
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/apps/racer
A benchmarking tool for running concurrent races between CLIPS rule-based solving and LLM reasoning on logic problems.
> Race CLIPS rule engines against LLMs on logic puzzles and let the data choose your AI strategy.
**Scenarios**: `race` · `benchmark` · `list` · `describe`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## Real-World Application
Motorsport strategy advisor, real-time decision engine.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
CLIPS
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** CLIPS rule-based racing strategy engine
- **Scenario:** Simulate racing pit-stop strategy using CLIPS rules
- **`tech_tags` in manifest:** `CLIPS` — example id **`racer`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## CLIPS integration path
The Go CLIPS runner uses **provider chat** (`go/clips_wire.go`). For **Session API** usage, use CLIPS session bindings in the SDK. Reference: `conformance/clips-json-contract.json`; nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/racer`:
cd rust && cargo build
cd go && make build
```
## Features
- **Head-to-Head Racing** - Run CLIPS and LLM approaches simultaneously
- **Benchmarking** - Statistical analysis over multiple runs
- **Problem Library** - Built-in collection of logic problems
- **Scoring Modes** - Speed, accuracy, or composite scoring
- **JSON Output** - Machine-readable results for analysis
## Installation
### Rust
```bash
cd examples/apps/racer/rust
cargo build --release
```
### Go
```bash
cd examples/apps/racer/go
make build
```
## Run
### Rust
```bash
cd examples/apps/racer/rust
# Show help
cargo run -- --help
# Run a single race
cargo run -- race einstein-riddle
# Run with accuracy scoring
cargo run -- race -s accuracy family-relations
# Benchmark with 20 runs
cargo run -- benchmark -n 20 einstein-riddle -o results.json
# List available problems
cargo run -- list
# Describe a specific problem
cargo run -- describe einstein-riddle
```
### Go
```bash
cd examples/apps/racer/go
# Show help
./bin/racer --help
# Run a single race
./bin/racer race einstein-riddle
# Benchmark mode
./bin/racer benchmark -n 10 logic-grid
```
## Commands
### race
Run a single head-to-head race between CLIPS and LLM.
```bash
racer race [OPTIONS]
OPTIONS:
-s, --scoring Scoring: speed, accuracy, composite (default: speed)
-t, --timeout Timeout per approach (default: 60)
-m, --model LLM model to use
--clips-only Run only CLIPS approach
--llm-only Run only LLM approach
-j, --json Output in JSON format
-v, --verbose Show detailed progress
```
### benchmark
Run multiple races for statistical analysis.
```bash
racer benchmark [OPTIONS]
OPTIONS:
-n, --runs Number of benchmark runs (default: 10)
-o, --output Write results to file
-j, --json Output in JSON format
```
### list
List available problems with optional filtering.
```bash
racer list [OPTIONS]
OPTIONS:
-t, --type Filter by problem type
-d, --difficulty Filter by difficulty
```
### describe
Show detailed information about a problem.
```bash
racer describe
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/racer --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/racer --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Problem Types
- **einstein-riddle** - The classic Einstein's Riddle (Zebra Puzzle)
- **family-relations** - Family relationship deduction
- **logic-grid** - Logic grid puzzles
- **scheduling** - Resource scheduling problems
- **classification** - Multi-attribute classification
## Scoring Modes
- **speed** - Fastest correct answer wins
- **accuracy** - Most accurate/complete answer wins
- **composite** - Weighted combination of speed and accuracy
## Example Output
### Race Results
```
=== Race: einstein-riddle ===
Contender | Time | Correct | Score
-------------|---------|---------|-------
CLIPS | 45ms | Yes | 100
LLM (Claude) | 3.2s | Yes | 98
Winner: CLIPS (faster with equal accuracy)
```
### Benchmark Results
```
=== Benchmark: einstein-riddle (20 runs) ===
Contender | Avg Time | Win Rate | Avg Score
-------------|----------|----------|----------
CLIPS | 47ms | 85% | 99.5
LLM (Claude) | 3.4s | 15% | 97.2
Statistical Winner: CLIPS (p < 0.001)
```
## Architecture
```
racer/
├── rust/
│ ├── src/main.rs # CLI entry point
│ └── Cargo.toml
├── go/
│ ├── cmd/main.go # CLI entry point
│ ├── runner.go # Race runner logic
│ ├── problems.go # Problem definitions
│ └── go.mod
└── shared/
└── problems/ # Problem definitions
```
## Notes
- CLIPS functionality uses ClipsProvider for rule execution
- LLM approach requires API key (ANTHROPIC_API_KEY or OPENAI_API_KEY)
- Benchmarks may vary based on LLM response times
## Testing
```bash
# Rust
cd examples/apps/racer/rust
cargo test
# Go
cd examples/apps/racer/go
go test -v ./...
```
## License
Part of the nxusKit project.
---
# Riffer - Music Sequence Analysis and Transformation (Rust)
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/apps/riffer
A command-line tool for analyzing and transforming music sequences, implemented in Rust.
> Analyze, score, and transform MIDI and MusicXML sequences using CLIPS rule-based music theory and LLM-powered narrative and transformation.
**Scenarios**: `analyze` · `score` · `transform` · `convert`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** CLIPS rule-based music composition engine
- **Scenario:** Generate musical riffs using CLIPS composition rules
- **`tech_tags` in manifest:** `CLIPS` — example id **`riffer`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## Real-World Application
Algorithmic music generation, creative AI assistant.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
CLIPS
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/riffer`:
cd rust && cargo build
cd go && make build
```
## Features
- **Analyze** - Detect key signature, analyze intervals, contour, rhythm, and dynamics
- **Score** - 6-dimension musicality scoring with improvement suggestions
- **Transform** - Transpose, invert, retrograde, augment, diminish, change key/tempo
- **Convert** - Convert between MIDI and MusicXML formats
## Installation
```bash
cd examples/apps/riffer/rust
cargo build --release
```
Find and set the binary path:
```bash
# Find where cargo built the binary
RIFFER=$(cargo metadata --format-version 1 | sed -n 's/.*"target_directory":"\([^"]*\)".*/\1/p')/release/riffer
# Verify it exists
ls -la "$RIFFER"
```
## Run
From the `examples/apps/riffer/rust` directory:
### Analyze a sequence
```bash
# JSON output (default)
"$RIFFER" analyze -i ../shared/testdata/e_minor_riff.mid
# Markdown output
"$RIFFER" analyze -i ../shared/testdata/e_minor_riff.mid -f markdown
```
### Score musicality
```bash
# Get a 6-dimension score with suggestions
"$RIFFER" score -i ../shared/testdata/e_minor_riff.mid -f markdown
```
Output includes:
- Overall score (0-100)
- Dimension scores: Harmonic Coherence, Melodic Interest, Rhythmic Variety, Resolution Quality, Dynamics Expression, Structural Balance
- Improvement suggestions
### Transform a sequence
```bash
# Transpose up 5 semitones
$RIFFER transform -i input.mid -o output.mid --transpose 5
# Invert around middle C (MIDI note 60)
$RIFFER transform -i input.mid -o output.mid --invert 60
# Reverse notes (retrograde)
$RIFFER transform -i input.mid -o output.mid --retrograde
# Rhythmic augmentation - double note durations (not to be confused with augmented chords)
$RIFFER transform -i input.mid -o output.mid --augment 2.0
# Rhythmic diminution - halve note durations (not to be confused with diminished chords)
$RIFFER transform -i input.mid -o output.mid --diminish 2.0
# Change key to G major
$RIFFER transform -i input.mid -o output.mid --key G
# Change tempo to 140 BPM
$RIFFER transform -i input.mid -o output.mid --tempo 140
# Combine multiple transformations
$RIFFER transform -i input.mid -o output.mid --transpose 5 --tempo 140
```
### Convert between formats
```bash
# MIDI to MusicXML
$RIFFER convert -i input.mid -o output.xml
# MusicXML to MIDI
$RIFFER convert -i input.xml -o output.mid
```
## Supported Formats
- **MIDI** (.mid, .midi) - Standard MIDI File format
- **MusicXML** (.xml, .musicxml) - MusicXML partwise format
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/riffer --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/riffer --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Example Output
### Analysis (Markdown)
```markdown
# Music Analysis: c_major_scale
## Summary
- **Notes**: 8
- **Duration**: 3840 ticks
## Key Detection
- **Detected Key**: C Major
- **Confidence**: 96.7%
## Scale Analysis
- **In Scale**: 8 notes
- **Out of Scale**: 0 notes
- **Harmonic Coherence**: 100.0%
```
### Score (Markdown)
```markdown
# Music Score: c_major_scale
## Overall Score: 59.3/100 (fair)
## Dimension Scores
| Dimension | Score | Rating |
|-----------|-------|--------|
| Harmonic Coherence | 100.0 | excellent |
| Melodic Interest | 39.0 | poor |
| Rhythmic Variety | 20.0 | poor |
## Suggestions for Improvement
- Add more interval variety for melodic interest
- Add rhythmic variety with different note durations
```
## Architecture
```
riffer/
├── main.rs # CLI entry point
├── types.rs # Core data types (Note, Sequence, etc.)
├── errors.rs # Error handling
├── formats/
│ ├── midi.rs # MIDI read/write
│ └── musicxml.rs # MusicXML read/write
├── theory/
│ ├── intervals.rs # Interval classification
│ ├── keys.rs # Key detection (Krumhansl-Schmuckler)
│ └── scales.rs # Scale definitions
└── engine/
├── analyzer.rs # Sequence analysis
├── scorer.rs # 6-dimension scoring
├── transformer.rs # Transformations
└── clips_bridge.rs # CLIPS rule engine (ClipsProvider)
```
## Testing
```bash
cd examples/apps/riffer/rust
cargo test
```
## License
Part of the nxusKit project.
---
# Ruler - Natural Language to CLIPS Rule Generation
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/apps/ruler
A command-line tool for generating CLIPS rules from natural language descriptions using LLM, with validation and automatic retry logic.
> Turn plain English into validated CLIPS rules — describe your business logic, get production-ready expert system code with automatic error correction.
**Scenarios**: `generate` · `validate` · `save` · `load` · `examples`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** CLIPS rule authoring and execution app
- **Scenario:** Author, load, and execute CLIPS rules interactively
- **`tech_tags` in manifest:** `CLIPS` — example id **`ruler`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## Real-World Application
Business rules workbench, rule management console.
## Requirements
**Edition**: nxusKit Pro
This example requires the Pro edition of nxusKit. [Purchase Pro](https://nxus.systems/pricing) or start a free 30-day trial (automatic on first Pro feature call).
## Technologies
CLIPS
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/apps/ruler`:
cd rust && cargo build
cd go && make build
```
## Features
- **Natural Language Input** - Describe rules in plain English
- **CLIPS Code Generation** - Produces valid CLIPS deftemplates and defrules
- **Automatic Validation** - Validates generated code against CLIPS syntax
- **Retry with Feedback** - Automatically retries with error feedback on failures
- **Progressive Examples** - Built-in examples from basic to advanced complexity
- **Multiple Output Formats** - Save as .clp, .json, or binary
## Installation
### Rust
```bash
cd examples/apps/ruler/rust
cargo build --release
```
### Go
```bash
cd examples/apps/ruler/go
make build
```
## Run
### Rust
```bash
cd examples/apps/ruler/rust
# Show help
cargo run -- --help
# Generate rules from natural language
cargo run -- generate "Create a rule that classifies adults if age >= 18"
# Generate with advanced complexity
cargo run -- generate -c advanced "Medical triage expert system" -o triage.clp
# Run progressive examples
cargo run -- examples -c basic
# Validate existing CLIPS code
cargo run -- validate my-rules.clp
# Load and display rules
cargo run -- load my-rules.clp
```
### Go
```bash
cd examples/apps/ruler/go
# Show help
./bin/ruler --help
# Generate rules
./bin/ruler generate "Classify customers as gold if purchases > 5000"
# Generate with output file
./bin/ruler generate -o customer.clp "Customer loyalty program rules"
```
## Commands
### generate
Generate CLIPS rules from a natural language description.
```bash
ruler generate [OPTIONS]
OPTIONS:
-c, --complexity Target complexity: basic, intermediate, advanced
-m, --model LLM model to use (default: claude-haiku-4-5-20251001)
-r, --retries Max retry attempts (default: 5)
-o, --output Write output to file
-j, --json Output in JSON format
-v, --verbose Show detailed progress
```
### validate
Validate CLIPS code syntax and structure.
```bash
ruler validate [OPTIONS]
OPTIONS:
-v, --verbose Show detailed validation results
```
### examples
Run built-in progressive complexity examples.
```bash
ruler examples [OPTIONS]
OPTIONS:
-c, --complexity Filter by complexity level
-l, --list List examples without running
```
### save / load
Save or load rule sets.
```bash
ruler save # Save current rules
ruler load # Load rules from file
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
./bin/ruler --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
./bin/ruler --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Complexity Levels
### Basic
- Simple single-rule definitions
- Basic deftemplates with few slots
- Straightforward conditions
Example: "Classify people as adults if age >= 18"
### Intermediate
- Multiple related rules
- Fact chaining and dependencies
- Moderate slot complexity
Example: "Customer loyalty program with bronze, silver, gold tiers"
### Advanced
- Complex multi-rule systems
- Salience and conflict resolution
- Advanced pattern matching
Example: "Medical triage system with symptom analysis"
## Example Output
### Generated CLIPS Code
```clp
; Generated by Ruler from: "Classify adults if age >= 18"
(deftemplate person
(slot name (type STRING))
(slot age (type INTEGER)))
(deftemplate classification
(slot person-name (type STRING))
(slot category (type SYMBOL)))
(defrule classify-adult
"Classify a person as an adult if age >= 18"
(person (name ?name) (age ?age&:(>= ?age 18)))
=>
(assert (classification (person-name ?name) (category adult))))
```
### Validation Result
```
Validation: PASSED
Templates: 2
Rules: 1
Warnings: 0
```
## Architecture
```
ruler/
├── rust/
│ ├── src/main.rs # CLI entry point
│ └── Cargo.toml
├── go/
│ ├── cmd/main.go # CLI entry point
│ ├── generator.go # Rule generation logic
│ ├── validator.go # CLIPS validation
│ └── go.mod
└── shared/
└── examples/ # Built-in examples
```
## Retry Logic
When generated code fails validation:
1. Parse the validation error
2. Include error context in retry prompt
3. Adjust complexity hints if needed
4. Retry up to N times (default: 5)
5. Return best attempt if all retries fail
## Notes
- CLIPS functionality uses ClipsProvider for validation
- LLM approach requires API key (ANTHROPIC_API_KEY or OPENAI_API_KEY)
- Generated code quality depends on description clarity
## Testing
```bash
# Rust
cd examples/apps/ruler/rust
cargo test
# Go
cd examples/apps/ruler/go
go test -v ./...
```
## License
Part of the nxusKit project.
---
# Alert Triage Integration
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/integrations/alert-triage
LLM-powered alert triage for observability systems, with batch processing and structured output.
> Turn alert noise into prioritized action by letting an LLM classify severity, surface root causes, and recommend remediation steps automatically.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## Overview
This example demonstrates using LLMs to triage monitoring alerts, providing priority assessment, likely causes, and suggested remediation actions. It's designed to work with Alertmanager-format alerts.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Alert triage with LLM-powered analysis
- **Scenario:** Classify and prioritize alerts using LLM reasoning
- **`tech_tags` in manifest:** `LLM` — example id **`alert-triage`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
SOC alert triage, IT incident management.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/alert-triage`:
cd rust && cargo build
cd go && make build
```
## Features
- Batch alert processing for efficiency
- Structured JSON output with priority, cause, and actions
- Compatible with Alertmanager webhook format
- Prioritization based on severity and context
## Alert Format
Input alerts follow the Alertmanager format:
```json
{
"alertname": "HighMemoryUsage",
"severity": "warning",
"instance": "web-server-01",
"description": "Memory usage above 85% for 5 minutes"
}
```
## Triage Output
Each alert receives a triage result:
```json
{
"alertname": "HighMemoryUsage",
"priority": 3,
"summary": "Memory pressure on web server",
"likely_cause": "Memory leak or increased traffic",
"suggested_actions": [
"Check for memory leaks in application logs",
"Review recent deployments",
"Consider horizontal scaling"
]
}
```
## Priority Scale
| Priority | Meaning | Response |
|----------|---------|----------|
| 1 | Critical | Immediate action required |
| 2 | High | Respond within 1 hour |
| 3 | Medium | Respond within 4 hours |
| 4 | Low | Respond within 24 hours |
| 5 | Informational | No action required |
## Library usage
### Rust
```rust
use alert_triage::{triage_alerts, Alert};
let alerts = vec![
Alert { alertname: "...", severity: "critical", ... },
];
let results = triage_alerts(&provider, "llama3", &alerts).await?;
for result in results {
println!("{}: Priority {} - {}", result.alertname, result.priority, result.summary);
}
```
### Go
```go
alerts := []Alert{{AlertName: "...", Severity: "critical", ...}}
results, err := TriageAlerts(ctx, provider, "llama3", alerts)
for _, result := range results {
fmt.Printf("%s: Priority %d - %s\n", result.AlertName, result.Priority, result.Summary)
}
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Sample Data
A `sample_alerts.json` file is provided with example alerts for testing.
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Integration Ideas
1. **Alertmanager webhook**: Receive alerts via HTTP webhook
2. **PagerDuty integration**: Update incident priority based on triage
3. **Slack notifications**: Send enriched alerts to Slack channels
4. **Runbook linking**: Match alerts to relevant runbooks
5. **Historical learning**: Improve triage based on past incident resolutions
---
# Multi-Provider Pipeline -- BN -> Solver -> CLIPS
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/integrations/bn-solver-clips-pipeline
Demonstrates the flagship nxusKit integration pattern: chaining Bayesian Network prediction, constraint solver optimization, and CLIPS rule-based safety enforcement in a 3-stage pipeline. Each stage feeds its output into the next, showing how probabilistic, combinatorial, and symbolic reasoning compose through a unified SDK.
> Chain probabilistic prediction, constraint optimization, and rule-based safety enforcement into a single production-ready pipeline using one unified SDK.
**Scenarios**: `festival` · `rescue` · `bakery`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## CLIPS integration path (stage 3)
Stage 3 is **CLIPS**: the **Go** path uses **provider chat** (`go/clips_wire.go`, `ClipsInput` / `ClipsOutput` JSON in the chat API). The **Rust** path uses the **Session API** (`nxuskit::clips::ClipsSession` — load rules, `fact_assert_structured`, `run`). Use the path that matches your integration style; both enforce the same rule files.
Schema: `conformance/clips-json-contract.json`. Docs: nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · CLIPS · Solver · BN
- **Summary:** Three-stage BN prediction → Solver optimization → CLIPS safety pipeline
- **Scenario:** Chain Bayesian Network prediction into Solver optimization with CLIPS safety enforcement
- **`tech_tags` in manifest:** `BN, Solver, CLIPS` — example id **`bn-solver-clips-pipeline`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go |
|---------|-------------|------|-----|
| **BnNetwork** | Load and query Bayesian Network from BIF file | `BnNetwork::from_bif()` | `LoadBnNetwork()` |
| **BnEvidence** | Set observed evidence for inference | `evidence.set_discrete()` | `ev.SetDiscrete()` |
| **Variable Elimination** | Exact posterior inference algorithm | `net.infer(&ev, "ve")` | `net.Infer(ev, "ve")` |
| **SolverSession** | Create and configure Z3 constraint solver | `SolverSession::new()` | `NewSolverSession()` |
| **Constraint Optimization** | Single-objective optimization with constraints | `session.solve()` | `session.Solve()` |
| **CLIPS (stage 3)** | Rule engine for safety | **`ClipsSession`**: `load_file`, `fact_assert_structured`, `run` | **Provider chat**: `NewClipsProvider()`, JSON in `ChatRequest` |
| **Fact assertion** | Solver → CLIPS | Structured slots → `fact_assert_structured` | JSON facts in user message |
| **Alert / conclusion readout** | Derived template facts | `facts_by_template` + `fact_slot_values` | Parse `ClipsOutput.conclusions` |
| **Pipeline Composition** | 3-stage data flow across provider types | Stage 1 -> 2 -> 3 | Stage 1 -> 2 -> 3 |
## Technologies
Solver, BN
## Pipeline Architecture
```
┌─────────────┐ Posteriors ┌──────────────┐ Assignments ┌───────────────┐
│ BN Network │ ──────────────> │ Solver │ ──────────────> │ CLIPS Rules │
│ (Prediction) │ │ (Optimization)│ │ (Safety) │
└─────────────┘ └──────────────┘ └───────────────┘
model.bif problem.json rules.clp
evidence.json
```
**Stage 1 -- BN Prediction**: Loads a Bayesian Network from a BIF file, sets observed evidence, and runs Variable Elimination to compute posterior distributions over a target variable (crowd size, survivor probability, or demand level).
**Stage 2 -- Solver Optimization**: Uses the BN prediction to inform a Z3 constraint optimization problem. Variables, constraints, and objectives are loaded from `problem.json`. The solver finds optimal assignments (band-to-stage, team-to-zone, or item-to-oven mappings).
**Stage 3 -- CLIPS Safety Enforcement**: Converts solver assignments into CLIPS facts and asserts them into a rule engine loaded with domain-specific safety rules. The engine fires rules to detect violations and generates typed alerts (critical, warning, info).
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/bn-solver-clips-pipeline`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario festival
cargo run -- --scenario rescue --verbose
cargo run -- --scenario bakery --step
```
### Go
```bash
cd go
make build
./bin/bn-solver-clips-pipeline --scenario festival
./bin/bn-solver-clips-pipeline --scenario rescue --verbose
./bin/bn-solver-clips-pipeline --scenario bakery --step
```
Or directly:
```bash
cd go
go run . --scenario festival
```
## Scenarios
### Festival (Music Festival Stage Planning)
A music festival needs to assign bands to stages while maximizing audience enjoyment. The BN predicts crowd size from weather, headliner popularity, and time of day. The solver optimizes band-to-stage assignments. CLIPS rules enforce noise limits and pyrotechnic safety regulations.
- **BN predicts**: `crowd_size` given weather, headliner popularity, time of day
- **Solver optimizes**: band-to-stage assignments maximizing `total_enjoyment`
- **CLIPS enforces**: noise proximity limits, pyrotechnic material restrictions
### Rescue (Search and Rescue Operation)
A disaster response team must deploy rescue units across zones. The BN estimates survivor probability from building damage, time since event, and weather conditions. The solver assigns teams to zones to maximize rescues. CLIPS rules enforce operational safety protocols.
- **BN predicts**: `survivor_probability` given building damage, hours since event, weather
- **Solver optimizes**: team-to-zone assignments maximizing `total_survivors_rescued`
- **CLIPS enforces**: helicopter wind limits, team deployment protocols
### Bakery (Production Scheduling)
A bakery plans its daily production across multiple ovens. The BN forecasts demand level from day of week, season, and local events. The solver schedules items across ovens to minimize waste. CLIPS rules enforce allergen isolation and food safety regulations.
- **BN predicts**: `demand_level` given day of week, season, local events
- **Solver optimizes**: item-to-oven assignments minimizing `total_waste`
- **CLIPS enforces**: allergen cross-contamination, gluten-free isolation, scheduling conflicts
## Interactive Modes
All examples support debugging flags for inspecting pipeline internals:
```bash
# Verbose mode - show intermediate data, network variables, fact assertions, rule traces
cargo run -- --scenario festival --verbose # Rust
go run . --scenario festival --verbose # Go
# Step mode - pause at each pipeline stage with explanations
cargo run -- --scenario rescue --step # Rust
go run . --scenario rescue --step # Go
# Combined mode
cargo run -- --scenario bakery --verbose --step
go run . --scenario bakery --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Scenario Data Format
Each scenario directory contains four files:
| File | Purpose | Consumed By |
|------|---------|-------------|
| `model.bif` | Bayesian Network definition in BIF format (variables, parents, CPTs) | Stage 1: BnNetwork |
| `evidence.json` | Observed variable values as `{"variable": "state"}` pairs | Stage 1: BnEvidence |
| `problem.json` | Solver problem with variables, constraints, and objectives | Stage 2: SolverSession |
| `rules.clp` | CLIPS rule definitions for domain-specific safety checks | Stage 3: ClipsProvider |
| `expected-output.json` | Golden output describing expected pipeline results | Testing/validation |
### Adding a New Scenario
1. Create a new directory under `scenarios/`
2. Define the BN model in `model.bif` with evidence and prediction variables
3. Create `evidence.json` with the observed evidence
4. Define the optimization problem in `problem.json`
5. Write CLIPS safety rules in `rules.clp` with appropriate templates
6. Add the scenario's CLIPS template mapping to `knownScenarios` in the source code
7. Create `expected-output.json` with the expected pipeline results
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Event planning | Predict attendance, optimize resource allocation, enforce safety codes |
| Emergency response | Estimate survival windows, deploy rescue assets, enforce operational protocols |
| Manufacturing | Forecast demand, schedule production, enforce quality and safety standards |
| Logistics | Predict delivery volumes, optimize fleet routing, enforce regulatory compliance |
| Healthcare | Predict patient load, optimize staff scheduling, enforce clinical safety protocols |
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
Each scenario includes an `expected-output.json` that describes the expected structure of the pipeline results, useful for regression testing and validation.
---
# BN Structure Learning -- Causal Discovery from Data
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/integrations/bn-structure-learning
Demonstrates Bayesian Network structure learning: discovering causal relationships directly from observational CSV data, learning parameters, evaluating model fit, and running inference on the learned model. Two structure learning algorithms (Hill-Climb and K2) are compared to identify high-confidence causal links.
> Discover causal structure hidden in your data — learn Bayesian network topology and parameters directly from CSV observations using Hill-Climb and K2 search algorithms.
**Scenarios**: `golf` · `bmx` · `sourdough`
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · BN
- **Summary:** Bayesian network structure learning from data
- **Scenario:** Learn Bayesian network structure from observational data
- **`tech_tags` in manifest:** `BN` — example id **`bn-structure-learning`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go |
|---------|-------------|------|-----|
| **BnNetwork (empty)** | Create an empty network for structure learning | `nxuskit_bn_net_create()` | `NewBnNetwork()` |
| **Hill-Climb Search** | Greedy structure search with edge add/remove/reverse | `nxuskit_bn_search_structure(..., "hill_climb", ...)` | `net.SearchStructure(..., "hill_climb")` |
| **K2 Search** | Order-based structure search with variable ordering | `nxuskit_bn_search_structure(..., "k2", ...)` | `net.SearchStructure(..., "k2")` |
| **BIC Scoring** | Bayesian Information Criterion (penalizes complexity) | `scoring = "bic"` | `Scoring: "bic"` |
| **BDeu Scoring** | Bayesian Dirichlet equivalent uniform scoring | `scoring = "bdeu"` | `Scoring: "bdeu"` |
| **MLE Learning** | Maximum Likelihood Estimation for CPT parameters | `nxuskit_bn_learn_mle()` | `net.LearnMLE()` |
| **Log-Likelihood** | Evaluate model fit against training data | `nxuskit_bn_log_likelihood()` | `net.LogLikelihood()` |
| **VE Inference** | Variable Elimination on the learned model | `nxuskit_bn_infer(..., "ve", ...)` | `net.Infer(ev, "ve")` |
## Technologies
BN
## Pipeline Architecture
```
┌───────────┐ Column names ┌──────────────┐ Learned edges ┌───────────────┐
│ CSV Data │ ───────────────> │ Structure │ ─────────────────> │ Parameter │
│ (200 rows) │ │ Learning │ │ Learning │
└───────────┘ │ (HC / K2) │ │ (MLE) │
└──────────────┘ └───────┬───────┘
│
┌──────────────┐ Fit score ┌──────┴───────┐
│ Algorithm │ <───────────── │ Log- │
│ Comparison │ │ Likelihood │
└──────────────┘ └──────┬───────┘
│
┌──────┴───────┐
│ Inference │
│ (VE) │
└──────────────┘
```
**Step 1 -- Load CSV Data**: Reads the scenario CSV file, discovers column names (which become BN variables) and row count.
**Step 2 -- Hill-Climb + BIC**: Runs greedy structure search starting from an empty graph. At each step, the algorithm tries adding, removing, or reversing an edge, accepting the change that most improves the BIC score. BIC balances fit against model complexity via a log(N) penalty term.
**Step 3 -- K2 + BDeu**: Runs order-based structure search using the CSV column ordering. K2 processes variables in order, greedily adding parent edges that improve the BDeu score. BDeu uses an equivalent sample size (ESS) hyperparameter that controls the strength of the prior.
**Step 4 -- MLE Parameter Learning**: Fits conditional probability tables (CPTs) to the Hill-Climb structure using Maximum Likelihood Estimation with Laplace smoothing (pseudocount=1.0) to avoid zero probabilities.
**Step 5 -- Log-Likelihood Evaluation**: Computes how well the learned model explains the training data. Per-sample log-likelihood allows comparison across different dataset sizes.
**Step 6 -- Inference**: Runs Variable Elimination on the learned model with sample evidence to demonstrate that the learned network supports standard BN queries.
**Step 7 -- Algorithm Comparison**: Compares edges discovered by both algorithms. Shared edges represent high-confidence causal relationships found independently by two different search strategies.
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/bn-structure-learning`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario golf
cargo run -- --scenario bmx --verbose
cargo run -- --scenario sourdough --step
```
### Go
```bash
cd go
make build
./bin/bn-structure-learning --scenario golf
./bin/bn-structure-learning --scenario bmx --verbose
./bin/bn-structure-learning --scenario sourdough --step
```
Or directly:
```bash
cd go
go run . --scenario golf
```
## Scenarios
### Golf (Course Conditions)
Models how weather, soil conditions, maintenance practices, and fertilizer affect golf course playing conditions. The data encodes realistic correlations: rainy weather increases soil moisture, which softens fairways; heavy fertilizer increases green speed; longer mowing increases rough thickness.
- **Variables**: weather, soil_moisture, mowing, foot_traffic, fertilizer, green_speed, fairway_firmness, rough_thickness
- **Expected causal links**: weather -> soil_moisture -> fairway_firmness, fertilizer -> green_speed, mowing -> rough_thickness
- **Inference demo**: P(green_speed | weather=rainy, fertilizer=heavy)
### BMX (Rider Performance)
Models how rider skill, technique, and jump characteristics affect BMX race outcomes. High skill correlates with perfect pump timing and fast speed; extreme jumps with low skill dramatically increase crash risk.
- **Variables**: jump_height, berm_angle, pump_timing, speed, skill, lap_time, crash_risk, style_score
- **Expected causal links**: skill -> pump_timing, skill -> jump_height, speed -> lap_time, jump_height + skill -> crash_risk
- **Inference demo**: P(lap_time | skill=pro, pump_timing=perfect)
### Sourdough (Baking)
Models how feeding schedule, flour choice, temperature, and starter maturity affect sourdough bread characteristics. Warm temperatures with mature starters produce fast rises and dense bubbles; rye flour and infrequent feeding lead to sour flavors.
- **Variables**: feeding_schedule, flour_type, ambient_temp, hydration, starter_age, rise_time, bubble_density, flavor_profile
- **Expected causal links**: ambient_temp + starter_age -> rise_time -> bubble_density, flour_type -> flavor_profile, feeding_schedule -> starter_age
- **Inference demo**: P(flavor_profile | flour_type=rye, ambient_temp=warm)
## Interactive Modes
```bash
# Verbose mode -- show raw JSON results and intermediate data
cargo run -- --scenario golf --verbose # Rust
go run . --scenario golf --verbose # Go
# Step mode -- pause at each step with explanations
cargo run -- --scenario bmx --step # Rust
go run . --scenario bmx --step # Go
# Combined mode
cargo run -- --scenario sourdough --verbose --step
go run . --scenario sourdough --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Structure Learning Concepts
### Hill-Climb vs K2
| Property | Hill-Climb | K2 |
|----------|-----------|-----|
| Search strategy | Greedy local search | Order-based forward search |
| Starting point | Empty graph | Empty graph + variable ordering |
| Operations | Add, remove, reverse edges | Add parent edges only |
| Ordering required | No | Yes (results depend on ordering) |
| Score function | BIC (default) | BDeu (default) |
| Complexity | O(n^2 * max_steps) | O(n^2 * max_parents) |
| Strengths | Flexible, no ordering needed | Fast, principled Bayesian scoring |
| Weaknesses | Can get stuck in local optima | Sensitive to variable ordering |
### Scoring Functions
**BIC (Bayesian Information Criterion)**: `BIC = LL - (k/2) * ln(N)` where LL is log-likelihood, k is the number of free parameters, and N is the sample size. Penalizes complexity more strongly with larger datasets.
**BDeu (Bayesian Dirichlet equivalent uniform)**: A Bayesian score that uses a Dirichlet prior. The equivalent sample size (ESS) parameter controls prior strength: small ESS values prefer simpler structures, large ESS values are more permissive.
### Parameter Learning (MLE)
Maximum Likelihood Estimation counts co-occurrences in the data to estimate conditional probability tables. Laplace smoothing (pseudocount > 0) adds a small count to every cell, preventing zero probabilities that would make log-likelihood undefined.
### Fit Evaluation (Log-Likelihood)
Log-likelihood measures how well the model's CPTs explain the observed data: `LL = sum_i sum_j log P(x_ij | parents(x_j))`. Higher (less negative) values indicate better fit. Per-sample log-likelihood (LL / N) normalizes for dataset size.
## CSV Format Requirements
- **Header row**: First row contains column names (become BN variable names)
- **Encoding**: UTF-8 with LF line endings
- **Delimiter**: Comma-separated values
- **Values**: Categorical (discrete) values only for structure learning
- **Missing values**: Rows with empty cells are skipped with a warning
- **Sorting**: Primary sort by first column, secondary by second column
### Adding a New Scenario
1. Create a new directory under `scenarios/`
2. Add a `data.csv` file with header row and at least 50 data rows
3. Ensure correlations in the data reflect the causal structure you expect to discover
4. Add the scenario configuration to `scenario_config()` (Rust) or `knownScenarios` (Go)
5. Create `expected-output.json` with expected edge ranges and inference results
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Epidemiology | Discover disease risk factor relationships from patient records |
| Manufacturing | Identify root causes of defects from production data |
| Finance | Map causal relationships between economic indicators |
| Genomics | Learn gene regulatory networks from expression data |
| Quality control | Find which process parameters affect product quality |
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
Each scenario includes an `expected-output.json` that describes expected edge count ranges, inference results, and fit evaluation bounds for regression testing.
---
# CLI Assistant Integration
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/integrations/cli-assistant
Converts natural language queries into shell commands using LLM with streaming output.
> Turn plain English into shell commands instantly — build a streaming CLI assistant that speaks your language and runs in your terminal.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## Overview
This example demonstrates a practical CLI tool that translates human-readable requests into executable shell commands. It showcases streaming for real-time output as the command is generated.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Interactive CLI assistant with LLM backend
- **Scenario:** Build an interactive terminal assistant powered by an LLM
- **`tech_tags` in manifest:** `LLM` — example id **`cli-assistant`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Developer productivity tool, command-line copilot.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Features
- Natural language to shell command translation
- Streaming output shows command as it's generated
- Safety comments for dangerous operations
- Works with common Unix commands
## Example Queries
| Query | Generated Command |
|-------|------------------|
| "find all rust files modified in the last week" | `find . -name "*.rs" -mtime -7` |
| "show disk usage sorted by size" | `du -sh * \| sort -h` |
| "list all running docker containers" | `docker ps` |
## Build
```bash
cd rust && cargo build
cd ../go && make build
```
## Library usage
### Rust
```rust
use nxuskit::prelude::*;
let provider = OllamaProvider::builder().model("llama3").build()?;
let command = generate_command(&provider, query).await?;
println!("Generated: {}", command);
```
### Go
```go
command, err := GenerateCommand(ctx, provider, query)
fmt.Println("Generated:", command)
```
## Run
### Rust
```bash
cd rust
cargo run
# Interactive mode
cargo run -- "your query here"
```
### Go
```bash
cd go
go run .
# Interactive mode
go run . "your query here"
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Safety Considerations
The LLM is instructed to:
- Add warning comments for dangerous operations (rm -rf, etc.)
- Use common, well-known Unix commands
- Provide clarifying comments for ambiguous requests
**Important**: Always review generated commands before executing them.
## Extending the Example
Ideas for enhancement:
1. Add command execution with confirmation prompt
2. Implement command history
3. Add support for platform-specific commands (Windows, macOS, Linux)
4. Include command explanation mode
5. Add syntax highlighting for output
---
# CLIPS Basics
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/integrations/clips-basics
Load rules, assert facts, and run the CLIPS inference engine
> Bring deterministic rule-based logic to your applications by driving the CLIPS inference engine directly through the nxusKit SDK.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · CLIPS
- **Summary:** CLIPS rule engine basics via nxusKit SDK
- **Scenario:** Load rules, assert facts, and run the CLIPS inference engine
- **`tech_tags` in manifest:** `CLIPS` — example id **`clips-basics`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## CLIPS integration path
This example uses **provider chat**: JSON shaped like `ClipsInput` is sent as the user message body to the CLIPS `LLMProvider`, and the engine returns `ClipsOutput` JSON in `response.content`. Local wire types mirror that contract and are **not** SDK exports: Go `go/clips_wire.go`, Rust via shared crate `examples/shared/clips-wire-rust` (`nxuskit-examples-clips-wire`), Python reference `examples/shared/python/clips_wire.py`.
For **Session API** access (load rules, assert facts, run, inspect via handles), use `nxuskit::ClipsSession`, `nxuskit.ClipsSession`, or the C ABI in the SDK bundle.
Schema reference: `conformance/clips-json-contract.json` in this repository. Full field documentation: nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (heading anchor `#clipsinput-json-reference`; in the extracted bundle, see `docs/rule-authoring.md`).
## Real-World Application
Business rules engine, compliance checking
## Technologies
CLIPS
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `examples/shared/python/clips_wire.py` | Wire types only (use with nxuskit-py provider chat) |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/clips-basics`:
cd rust && cargo build
cd go && make build
```
Cross-language parity: the **animal classification** demos use the same `ClipsInput`-shaped JSON (`facts` → `template` / `values`) in Go (`main.go` example 1 dog; example 2 Frog/Penguin/Spider batch) and Rust (`animal_classification.rs` via `ClipsInputWire`).
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/clips-basics
```
---
# CLIPS+LLM Hybrid Integration
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/integrations/clips-llm-hybrid
Demonstrates combining CLIPS expert system with LLM for deterministic business rules plus natural language understanding.
> Combine deterministic CLIPS rules with LLM reasoning to build AI pipelines that are both fluent and auditable.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## CLIPS integration path
The CLIPS stage uses **provider chat** (JSON `ClipsInput` in the user message, `ClipsOutput` in `content`). See `go/clips_wire.go` and Rust crate `examples/shared/clips-wire-rust`. For **Session API** usage, use the CLIPS session bindings in your language SDK instead.
Schema: `conformance/clips-json-contract.json`. Documentation: nxusKit SDK `sdk-packaging/docs/rule-authoring.md` — **ClipsInput JSON Reference** (`#clipsinput-json-reference`; bundle: `docs/rule-authoring.md`).
## What this demonstrates
**Difficulty: Intermediate** 🟦 · LLM · CLIPS
- **Summary:** Hybrid CLIPS rules + LLM reasoning
- **Scenario:** Combine deterministic CLIPS rules with LLM-based reasoning
- **`tech_tags` in manifest:** `CLIPS, LLM` — example id **`clips-llm-hybrid`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
- **CLIPS:** Use an SDK build with CLIPS support (native `libnxuskit`); rule files and JSON contracts are referenced from this repo’s `conformance/` docs.
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go |
|---------|-------------|------|-----|
| **ClipsProvider** | Rule-based expert system as LLMProvider | ✅ `ClipsProvider::builder()` | ✅ `NewClipsProvider()` |
| **JSON Fact Assertion** | Convert structured data to CLIPS facts | ✅ `ChatRequest` with JSON | ✅ `ChatRequest` with JSON |
| **Conclusion Extraction** | Parse CLIPS output for derived facts | ✅ `ClipsOutput::conclusions` | ✅ `ClipsOutput.Conclusions` |
| **Provider Abstraction** | Same interface for LLM and CLIPS | ✅ `LLMProvider` trait | ✅ `LLMProvider` interface |
| **ResponseFormat** | Structured JSON output from LLM | ✅ `ResponseFormat::Json` | ✅ `JSONMode: true` |
| **Hybrid Pipeline** | LLM → CLIPS → LLM workflow | ✅ `analyze_ticket()` | ✅ `AnalyzeTicket()` |
## Real-World Application
Explainable AI decisions, regulated industry automation.
## Technologies
CLIPS, LLM
## Overview
This example shows the "hybrid AI" pattern: using LLM for natural language understanding and CLIPS for deterministic business decisions. Both Rust and Go implementations use the **real ClipsProvider** to execute CLIPS rules.
## Why Hybrid?
| Approach | Strengths | Weaknesses |
|----------|-----------|------------|
| **LLM only** | Natural language understanding, flexibility | Inconsistent policy application, no audit trail |
| **CLIPS only** | Deterministic, auditable, policy-compliant | Can't understand unstructured text |
| **Hybrid** | Both! Understanding AND compliance | More complex architecture |
## Three-Step Flow
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Step 1 │ │ Step 2 │ │ Step 3 │
│ LLM │ ──► │ CLIPS │ ──► │ LLM │
│ (classify) │ │ (routing) │ │ (response) │
└─────────────┘ └─────────────┘ └─────────────┘
Extract Apply rules Generate
category, deterministic empathetic
priority, team routing, customer
sentiment SLA, escalation response
```
1. **LLM Classification**: Extract category, priority, sentiment, entities from ticket text
2. **CLIPS Routing**: Apply deterministic rules for team assignment, SLA, escalation
3. **LLM Response**: Generate appropriate customer response
## Routing Rules
The CLIPS rules in `ticket-routing.clp` apply:
| Category | Priority | Team | SLA | Escalation |
|----------|----------|------|-----|------------|
| Security | Any | Security | 4h | Level 2 |
| Infrastructure | Critical | SRE | 2h | Level 1 |
| Infrastructure | High | SRE | 4h | Level 1 |
| Application | Critical | Development | 4h | Level 1 |
| Application | High | Development | 8h | None |
| General | Any | General Support | 24h | None |
## Library usage
### Rust (with ClipsProvider)
```rust
use clips_llm_hybrid::analyze_ticket;
use std::path::Path;
// nxusKit: Hybrid analysis using LLM + ClipsProvider
let rules_path = Path::new("ticket-routing.clp");
let result = analyze_ticket(&provider, "llama3", ticket_text, rules_path).await?;
// Deterministic routing from CLIPS (auditable, explainable)
println!("Team: {}", result.team);
println!("SLA: {} hours", result.sla_hours);
// LLM-derived insights (natural language understanding)
println!("Sentiment: {}", result.sentiment);
println!("Response: {}", result.suggested_response);
```
### Go (with ClipsProvider)
```go
// nxusKit: Hybrid analysis using LLM + ClipsProvider
rulesPath := "ticket-routing.clp"
result, err := AnalyzeTicket(ctx, provider, "llama3", ticketText, rulesPath)
// Deterministic routing from CLIPS (auditable, explainable)
fmt.Println("Team:", result.Team)
fmt.Println("SLA:", result.SLAHours, "hours")
// LLM-derived insights (natural language understanding)
fmt.Println("Sentiment:", result.Sentiment)
```
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/clips-llm-hybrid`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## CLIPS Rules File
See `ticket-routing.clp` for the actual CLIPS rules used in the Rust implementation.
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Production Considerations
1. **Rule versioning**: Track changes to CLIPS rules with version control
2. **Audit logging**: Log all routing decisions with rule traces
3. **Fallback handling**: Define default routing for edge cases
4. **Rule testing**: Unit test CLIPS rules independently of LLM
5. **Performance**: Cache common routing patterns
---
# Common-Sense Guardrails
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/integrations/common-sense-guardrails
> Catch plausible but impossible LLM recommendations by turning answers into facts, firing rules, and repairing failures with auditable prompts.
**Scenarios**: `car-wash` · `coupon-stack` · `pallet-door` · `cold-chain`
## Edition
**Community** - runs the full guardrail workflow: raw answer, structured facts, CLIPS validation, deterministic repair packet, and corrected answer.
**Edition note:** Runs in Community Edition. Pro adds optional Solver and ZEN proof stages.
## Pro Enhancement Path
Pro adds optional proof stages only when requested with `--stage pro` or `--stage all`.
- `solver-proof`: uses Solver artifacts for object-presence and dimensional feasibility scenarios.
- `zen-policy`: uses ZEN decision artifacts for promotion policy and cold-chain handling scenarios.
Mock Pro evidence is fixture-backed and does not require entitlement. In live mode this example checks for the normal nxusKit Pro entitlement signal before labeling a Pro proof stage as live-entitled; without entitlement it skips the Pro stage with a clear message and leaves Community stages runnable. The first-release Python and Bash implementations do not execute Solver or ZEN engines directly; they show the handoff shape through checked-in proof artifacts.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS
- **Summary:** Progressive LLM guardrails with Community CLIPS validation and optional Pro proof stages.
- **Scenario:** Refine LLM recommendations with structured extraction, rules, retry repair, and optional Pro proof.
- **`tech_tags` in manifest:** `LLM`, `CLIPS` - example id **`common-sense-guardrails`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Mock mode uses only Python 3, Bash, and `jq`. Live mode uses an installed nxusKit SDK or `nxuskit-cli`.
- **Languages in this example:** python, bash.
- **Models:** Live and auto mode can use `NXUSKIT_PROVIDER` with `NXUSKIT_MODEL`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, reachable `OLLAMA_HOST`, or reachable `LMSTUDIO_BASE_URL`.
- **CLIPS:** Community validation is represented by scenario-local CLIPS rule files and normalized findings.
## Scenario Purposes
| Scenario | Failure class | Guardrail |
|----------|---------------|-----------|
| `car-wash` | Implicit object-presence precondition | Washing the car requires the car to be at the wash location, not just the person. |
| `coupon-stack` | Promotion policy and margin violation | Discounts, free shipping, and loyalty credits must satisfy stacking and margin rules. |
| `pallet-door` | Dimensional feasibility and unsafe geometry | A pallet cannot be pushed through a door that is narrower than the loaded pallet. |
| `cold-chain` | Handling and auditability violation | Frozen medical material must use certified refrigerated service with temperature traceability. |
## Run
Canonical Community smoke commands:
```bash
cd examples/integrations/common-sense-guardrails/python
python3 main.py --scenario car-wash --mode mock --stage ce
cd ../bash
bash main.sh --scenario car-wash --mode mock --stage ce
```
Machine-readable parity checks:
```bash
cd examples/integrations/common-sense-guardrails/python
python3 main.py --scenario car-wash --mode mock --stage all --json
cd ../bash
bash main.sh --scenario car-wash --mode mock --stage all --json
```
All launch scenarios:
```bash
for scenario in car-wash coupon-stack pallet-door cold-chain; do
python3 main.py --scenario "$scenario" --mode mock --stage ce --json
done
```
## Mode Behavior
- `--mode mock`: uses checked-in fixtures for every Community stage and optional Pro evidence. It performs no provider, network, or entitlement preflight.
- `--mode live`: requires a configured live provider and fails before scenario content is sent if preflight is unavailable.
- `--mode auto`: uses live execution when provider preflight succeeds; otherwise it labels the run as fixture-backed mock mode.
Live structured fact extraction prefers pure JSON. If the model wraps a valid JSON object in prose, the runners extract it and mark the structured-facts stage as `warn`; if no valid JSON object is recoverable after retry, the structured-facts stage is marked `fail` and the run falls back to checked-in fact fixtures so later guardrail stages can still show their behavior.
Provider preflight order is explicit nxusKit provider/model environment, phase-specific model environment, nxusKit-recognized cloud credentials, reachable Ollama, then reachable LM Studio. Do not commit provider credentials or license tokens.
For local Ollama live runs, the Python runner honors `OLLAMA_HOST` and uses a short 5 second connect timeout with a 120 second read timeout because local model responses can be slower than cloud providers. The Python runner requests JSON response format for fact extraction when the installed SDK exposes it, but v1.0.0 does not expose provider-level `thinking_mode` in Python. Use the Bash/CLI runner for the strict local proof path because it can pass both `thinking_mode` and `response_format` through `nxuskit-cli call`.
Live runs can use one provider/model for every phase or override phases independently:
```bash
export NXUSKIT_PROVIDER=ollama
export NXUSKIT_MODEL=qwen3.5:4b
export OLLAMA_HOST=http://127.0.0.1:11434
```
Phase-specific provider overrides are also supported with `NXUSKIT_COMMON_SENSE_BASELINE_PROVIDER`, `NXUSKIT_COMMON_SENSE_FACTS_PROVIDER`, and `NXUSKIT_COMMON_SENSE_REPAIR_PROVIDER`. See [OLLAMA_MODELS.md](/v1.0.0/nxuskit/examples/integrations/common-sense-guardrails/ollama-models/) for local Ollama model notes from the repository walkthrough.
Strict live smoke is gated separately so mock fallback output is not mistaken for live provider output:
```bash
cd examples/integrations/common-sense-guardrails/bash
RUN_LIVE_SMOKE=1 ./strict_live_smoke.sh
```
## Local Model Starting Points
These are dated smoke-test starting points from the DevOps Ollama model-testing notes, not model rankings or product guarantees.
| Model | Why try it |
|-------|------------|
| `qwen3.5:4b` | 2026-05-11/12 local smokes show the desired guardrail-demo shape: naive car-wash answer fails as `walk`, constrained output is parseable, and enhanced object-presence prompting recovers to `drive`; it also has local structured/document evidence. |
| `qwen3.5:2b` | 2026-05-12 local smoke shows the same fail/recover car-wash shape at a smaller 2.7 GB footprint; use it when low-resource local testing matters more than tool-intent strength. |
| `gemma3:1b` or `erukude/omni-json:1b` | 2026-05-09/12 small-model smokes found both useful for very small guardrail demos because they reproduce the naive failure and recover under the enhanced prompt. |
| `nemotron-3-nano:4b` | 2026-05-12 smokes show the car-wash fail/recover target plus a native strict tool-call pass, making it a useful local comparison point. |
Avoid using passing or unparsed baseline behavior as a demo failure source. For example, the same DevOps notes show `phi4-mini-reasoning:3.8b` answering `drive` on the naive prompt and `granite4:350m-h` failing to recover under the enhanced prompt, so neither is a good default for this specific guardrail walkthrough.
## Scenario Data Contract
Each scenario directory contains these required Community files:
```text
problem.json
expected-output.json
rules.clp
mock-baseline.json
mock-facts.json
mock-repair.json
mock-corrected.json
```
Pro-enabled scenarios add one of:
```text
solver-problem.json
decision-model.json
```
Structured fact fixtures must include:
- `goal`
- `candidate_actions`
- `objects_required`
- `objects_moved`
- `resources`
- `constraints`
- `policy_context`
- `confidence`
CLIPS findings normalize to `status`, `rule_id`, `severity`, `message`, and `evidence`. Expected-output fixtures list required stage ids, expected finding rule ids, correction text fragments, and optional Pro stage metadata.
## Adding a Scenario
1. Create `scenarios//`.
2. Add every required Community file listed above.
3. Include a stable `id`, non-empty prompts, and a `repair_template` containing `{findings}` in `problem.json`.
4. Add scenario-local `rules.clp` findings with stable kebab-case rule ids.
5. Add `solver-problem.json` or `decision-model.json` only when the optional Pro stage is meaningful.
6. Run validation and both contract test suites before updating manifest scenarios.
Authoring validation:
```bash
cd examples/integrations/common-sense-guardrails/python
python3 main.py --validate-scenarios
python3 test_contract.py
cd ../bash
bash main.sh --validate-scenarios
bash test.sh
```
## Public Inspiration
Shout-out to [Haris Rahi](https://harisrahi.ai) and [Tamara Storm](https://www.linkedin.com/in/tamarastorm) for their LinkedIn discussions on the car-wash scenario from Opper.ai, Focus AI, and the HOB benchmark line.
## Scope Exclusions
This is not a medical, legal, financial, or safety certification system. Do not add PHI, regulated personal data, certification claims, or model-ranking claims to scenarios. The examples demonstrate an engineering pattern for auditable guardrails, not a complete common-sense benchmark.
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| LLM answer validation | Catch plausible recommendations that fail physical, operational, or policy preconditions before they reach users |
| Policy enforcement | Turn free-form answers into facts, apply deterministic rules, and produce auditable repair context |
| Operational decision support | Preserve fast LLM drafting while requiring concrete feasibility evidence for workflow-critical recommendations |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`: extracted bundle or installer layout) for live SDK checks. Mock acceptance commands do not need the SDK.
```bash
# From `/examples/integrations/common-sense-guardrails`:
cd python && python3 main.py --help
cd ../bash && make test
```
---
# Curated Ollama Models
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/integrations/common-sense-guardrails/ollama-models
This note records local model passes used for the common-sense guardrails walkthrough. The first pass on 2026-05-07 combined `ollama-cache list` SSD residency with `ollama list` installed sizes and filtered to models under 8 GB. Follow-up passes on 2026-05-11 and 2026-05-12 added the car-wash fail/recover smoke shape and structured-output checks.
These are dated smoke-test starting points, not model rankings or product guarantees.
## Source Notes
- Live structured fact extraction prefers pure JSON. If the model wraps a valid JSON object in prose, the Python and Bash runners extract it and mark the structured-facts stage as `warn`. If no valid JSON object is recoverable after retry, the stage is marked `fail` and the run falls back to checked-in fact fixtures so later guardrail stages can still demonstrate their behavior.
- Ollama structured outputs are most reliable when the API `format` field carries JSON or a JSON schema, and Ollama recommends grounding the prompt with the schema and using low temperature. Provider-native structured-output controls are still the robust path for future hardening, but this walkthrough no longer treats structured-facts failure as the expected result.
- Local car-wash smokes found `qwen3.5:4b` to be the best primary walkthrough candidate: small enough for local proof, stronger than the 2B option, and tested against the desired naive `walk` failure plus enhanced `drive` recovery.
- Local car-wash smokes found `qwen3.5:2b` useful as the low-resource option with the same fail/recover shape.
- Small-model smokes also found `gemma3:1b` and `erukude/omni-json:1b` useful for very small demos. `nemotron-3-nano:4b` is useful as a comparison point because separate tool-intent smokes showed native strict behavior.
- `llama3.2` remains a historical target candidate from earlier sweeps, but it is no longer the default recommendation for this walkthrough.
References:
-
-
-
- DevOps Ollama model-testing notes from 2026-05-09 through 2026-05-12
## Recommended Walkthrough Models
Use these first because they are small local smoke-test candidates that match the guardrail demo shape:
| Role | Model | Installed size | Why it is on the list | Walkthrough note |
|------|-------|----------------|------------------------|------------------|
| Primary live walkthrough | `qwen3.5:4b` | 3.4 GB | Stronger small Qwen 3.5 option from the 2026-05-11/12 local smokes. | Desired car-wash shape: naive answer fails as `walk`, constrained output is parseable, and enhanced object-presence prompting recovers to `drive`. Use this first when available. |
| Low-resource walkthrough | `qwen3.5:2b` | 2.7 GB | Smaller Qwen 3.5 option from the 2026-05-12 local smoke. | Same fail/recover car-wash shape at a smaller footprint. Use when local resource constraints matter more than maximum tool-intent strength. |
| Very small demo candidates | `gemma3:1b` or `erukude/omni-json:1b` | 815 MB / 1.4 GB | Very small models that reproduced the demo failure and recovery shape in local smokes. | Useful for constrained machines, but keep the primary docs and walkthrough centered on `qwen3.5:4b`. |
| Comparison candidate | `nemotron-3-nano:4b` | 2.8 GB | Car-wash fail/recover target plus separate native strict tool-call smoke evidence. | Interesting for comparison, but adding it to the main walkthrough can dilute the guardrails story. |
Other observed models:
| Model | Installed size | Use | Walkthrough note |
|-------|----------------|-----|------------------|
| `llama3.2` | 2.0 GB | Historical target candidate. | Earlier local sweeps showed a valid fail/recover shape, but newer release-surface guidance prefers `qwen3.5:4b` primary and `qwen3.5:2b` low-resource. |
| `phi4-mini-reasoning:3.8b` | 3.2 GB | Avoid as default for this scenario. | Answered `drive` on the naive prompt, which removes the intended baseline failure. |
| `granite4:350m-h` | 366 MB | Avoid as default for this scenario. | Failed to recover under the enhanced prompt in local smokes. |
| `qwen3:4b` | 2.5 GB | Historical extraction experiment. | Direct JSON probes were useful, but newer Qwen 3.5 smokes are the better starting point for the full walkthrough. |
## Current Walkthrough Default
Prefer `qwen3.5:4b` for the interactive walkthrough when it is available. It is the primary v1.0.0 local proof candidate, remains small enough for a developer laptop, and has current local smoke evidence for the car-wash fail/recover shape.
```bash
export NXUSKIT_PROVIDER=ollama
export NXUSKIT_MODEL=qwen3.5:4b
export OLLAMA_HOST=http://127.0.0.1:11434
```
For a lower-resource run, use the 2B Qwen 3.5 variant:
```bash
export NXUSKIT_PROVIDER=ollama
export NXUSKIT_MODEL=qwen3.5:2b
export OLLAMA_HOST=http://127.0.0.1:11434
```
For phase-specific experiments, keep the stronger model on extraction and repair while trying a smaller baseline:
```bash
export NXUSKIT_PROVIDER=ollama
export NXUSKIT_MODEL=qwen3.5:2b
export NXUSKIT_COMMON_SENSE_FACTS_MODEL=qwen3.5:4b
export NXUSKIT_COMMON_SENSE_REPAIR_MODEL=qwen3.5:4b
export OLLAMA_HOST=http://127.0.0.1:11434
```
## Structured Facts Posture
Provider-native structured-output controls remain the preferred hardening path, especially Ollama JSON/schema formatting and thinking-mode controls when exposed through the installed SDK/CLI surface. In v1.0.0, the Bash/CLI runner disables thinking for short guardrail calls and requests JSON schema output for fact extraction. The example itself should be described more narrowly: live structured facts can pass with pure JSON, warn when valid JSON is recovered from prose, or fail after retry and fall back to fixtures. Failure is a fallback state, not the expected walkthrough result.
---
# LLM-Solver Hybrid -- Natural Language to Optimized Solutions
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/integrations/llm-solver-hybrid
Demonstrates using an LLM to translate natural language constraints into structured solver variables and constraints, then feeding them to the Z3-based constraint solver for optimization. Supports mock mode (no API key needed) and live mode with configurable LLM providers.
> Bridge natural language and constraint solvers — let an LLM parse human intent, let Z3 find the optimal answer.
**Scenarios**: `seating` · `dungeon` · `road-trip`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · LLM · Solver
- **Summary:** Hybrid LLM + Z3 solver problem solving
- **Scenario:** Use an LLM to formulate constraints and Z3 to solve them
- **`tech_tags` in manifest:** `LLM, Solver` — example id **`llm-solver-hybrid`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust, python (paths under this directory).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go | Python |
|---------|-------------|------|-----|--------|
| **LLM Chat API** | Send structured prompts to LLM providers | `nxuskit::chat()` | `provider.Chat()` | `provider.chat(..., response_format=ResponseFormat.JSON)` |
| **Constraint Solver** | Z3-based solver session with variables, constraints, objectives | `nxuskit::solver::SolverSession` | `NewSolverSession()` | `nxuskit.solver.SolverSession` |
| **JSON Parsing/Validation** | Parse LLM output into typed variable and constraint definitions | `serde_json` | `encoding/json` | `json` + validation stage |
| **Retry Logic** | Re-prompt LLM on parse failure with error feedback (max 3 attempts) | `call_llm_with_retry()` | Retry loop in Stage 2 | Retry loop in `extract_variables_live()` |
| **Mock Mode** | Deterministic offline testing with pre-computed LLM responses | `--mock` flag | `--mock` (default) | `--mock` / `--no-mock` |
| **Provider Abstraction** | Same pipeline works with Ollama, LM Studio, OpenAI, Claude, Groq, and xAI Grok | `--provider` flag | `--provider` flag | `--provider` flag |
## Real-World Application
Natural language optimization, conversational planning.
## Technologies
LLM, Solver
## Architecture
```
┌──────────────┐ JSON ┌───────────┐ Structured ┌──────────┐
│ Natural Lang │ ──────────> │ LLM │ ──────────────> │ Solver │
│ Constraints │ prompt │ (or Mock) │ variables + │ (Z3) │
└──────────────┘ └───────────┘ constraints └──────────┘
problem.json │
Optimal Solution
```
**Stage 1 -- Load Problem**: Reads the scenario's `problem.json` containing natural language constraints, system prompt, objective definition, solver configuration, and a pre-computed mock LLM response.
**Stage 2 -- Get Structured Constraints**: In mock mode, uses the pre-defined `mock_llm_response` from `problem.json`. In live mode, sends the system prompt and natural language constraints to an LLM provider, parses the JSON response into variables and constraints arrays, and retries up to 3 times on parse failure.
**Stage 3 -- Validate**: Checks that each variable has a name, type, and domain. Verifies that all constraint variable references point to existing variable names. Filters out invalid constraints and reports warnings.
**Stage 4 -- Solve**: Creates a Z3 solver session, adds variables and constraints, sets the optimization objective, and solves. Falls back to satisfiability check if the objective cannot be applied.
**Stage 5 -- Interpret Results**: Renders solver assignments in scenario-specific human-readable format (table assignments, dungeon map, trip itinerary).
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/llm-solver-hybrid`:
cd rust && cargo build
cd go && make build
```
## Run
### Go
```bash
cd go
make build
./bin/llm-solver-hybrid --scenario seating
./bin/llm-solver-hybrid --scenario dungeon --verbose
./bin/llm-solver-hybrid --scenario road-trip --step
```
Or directly:
```bash
cd go
go run . --scenario seating
```
### Rust
```bash
cd rust
cargo run -- --scenario seating
cargo run -- --scenario dungeon --verbose
cargo run -- --scenario road-trip --step
```
### Python
```bash
cd python
python3 main.py --scenario seating
python3 main.py --scenario dungeon --verbose
python3 main.py --scenario road-trip --step
```
## Mock vs Live Mode
### Mock Mode (default)
Mock mode uses the pre-computed `mock_llm_response` from each scenario's `problem.json`. No API key or running LLM server is needed. This is the default for Rust, Go, and Python.
```bash
# Go (mock is the default)
go run . --scenario seating
# Rust (mock is the default)
cargo run -- --scenario seating
# Python (mock is the default)
python3 main.py --scenario seating
```
### Live Mode
Live mode calls a real LLM provider to extract structured constraints from natural language. The LLM response is parsed as JSON and validated before being sent to the solver.
```bash
# Go: disable mock with --no-mock
go run . --scenario seating --no-mock --provider ollama --model llama3.2
# Rust: disable mock with --no-mock
cargo run -- --scenario seating --no-mock --provider ollama --model llama3.2
# Python: disable mock with --no-mock
python3 main.py --scenario seating --no-mock --provider ollama --model llama3.2
```
**Supported providers**: `ollama`, `lmstudio`, `openai`, `claude`, `groq`, `xai`
Use `groq` for Groq (`GROQ_API_KEY`) and `xai` for xAI Grok (`XAI_API_KEY`). The provider id `grok` is intentionally not an alias.
**API key setup** (for cloud providers):
```bash
export OPENAI_API_KEY=sk-...
export ANTHROPIC_API_KEY=sk-ant-...
export GROQ_API_KEY=gsk_...
export XAI_API_KEY=xai-...
```
Local providers (Ollama, LM Studio) require the server to be running but no API key.
## Scenarios
### Seating -- Wedding Dinner Arrangement
Assign 12 wedding guests to 3 tables while respecting social constraints: feuding relatives at different tables, couples together, ex-partners separated, language requirements, and table capacity limits. The solver maximizes a happiness score based on social preferences.
- **Variables**: 12 integer variables (one per guest, domain 1--3)
- **Constraints**: 4 (not-equal, equal, linear capacity)
- **Objective**: maximize happiness
### Dungeon -- Game Level Layout
Generate a 5-room dungeon with boss placement, treasure rooms, and progressive difficulty. The boss must be in the last room, treasure rooms cannot overlap with the boss, and difficulty increases as the player goes deeper.
- **Variables**: 9 integer variables (room assignments, difficulty levels)
- **Constraints**: 5 (equality, not-equal, linear progression)
- **Objective**: maximize total challenge
### Road Trip -- National Park Itinerary
Plan a 14-day road trip visiting 5 national parks (Yosemite, Yellowstone, Zion, Glacier, Grand Canyon). Constraints include minimum days at large parks, geographic ordering (visit nearby parks consecutively), and the total day budget.
- **Variables**: 10 integer variables (days-at and visit-order per park)
- **Constraints**: 4 (linear budget, minimum days, ordering)
- **Objective**: maximize total experience
## Interactive Modes
All examples support debugging flags for inspecting pipeline internals:
```bash
# Verbose mode - show raw LLM responses, parsed JSON, solver details
cargo run -- --scenario seating --verbose # Rust
go run . --scenario seating --verbose # Go
# Step mode - pause at each pipeline stage with explanations
cargo run -- --scenario dungeon --step # Rust
go run . --scenario dungeon --step # Go
# Combined mode
cargo run -- --scenario road-trip --verbose --step
go run . --scenario road-trip --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Retry Logic
When running in live mode, the LLM extraction step uses a retry loop (max 3 attempts):
1. **Attempt 1**: Send the system prompt and natural language constraints to the LLM, requesting JSON output with `variables` and `constraints` arrays.
2. **Parse and validate**: Check that the response is valid JSON, contains non-empty `variables` and `constraints` arrays, and that variables have required fields.
3. **On failure**: Append the failed response and an error-feedback message to the conversation, then re-prompt the LLM. The feedback describes the specific parse error (invalid JSON, empty arrays, missing fields).
4. **After 3 failures**: Fall back to the mock response from `problem.json` and continue the pipeline.
This retry-with-feedback pattern is effective because the LLM sees its own previous attempt and the specific error, allowing it to self-correct.
## Scenario Data Format
Each scenario is defined by a single `problem.json` file in `scenarios//`:
| Field | Type | Purpose |
|-------|------|---------|
| `description` | string | Human-readable scenario description |
| `natural_language_constraints` | string[] | Plain English constraints sent to the LLM |
| `system_prompt` | string | System message instructing the LLM how to respond |
| `objective` | object | Optimization objective (`name`, `direction`, `expression`, `label`) |
| `solver_config` | object | Solver configuration (e.g., `timeout_ms`) |
| `mock_llm_response` | object | Pre-computed LLM output with `variables` and `constraints` arrays |
Each variable in `mock_llm_response.variables` has:
```json
{
"name": "guest_anna_table",
"var_type": "integer",
"label": "Table assignment for Anna",
"domain": { "min": 1, "max": 3 }
}
```
Each constraint in `mock_llm_response.constraints` has:
```json
{
"name": "martha_bob_apart",
"constraint_type": "not_equal",
"label": "Aunt Martha and Uncle Bob at different tables",
"variables": ["guest_martha_table", "guest_bob_table"],
"parameters": {}
}
```
An `expected-output.json` file alongside each `problem.json` describes the expected pipeline results in mock mode, useful for regression testing.
### Adding a New Scenario
1. Create a new directory under `scenarios/`
2. Write a `problem.json` with natural language constraints and a mock LLM response
3. Add the scenario's result interpretation logic to `interpretResults` (Go) or `interpret_result` (Rust)
4. Create an `expected-output.json` with the expected mock-mode results
## Prompt Engineering Notes
The quality of LLM-extracted constraints depends heavily on the system prompt. Tips for writing effective prompts:
1. **Specify the output format explicitly**: Tell the LLM to return JSON with `variables` and `constraints` arrays. Mention the exact field names expected (`name`, `var_type`, `domain`, `constraint_type`, `parameters`).
2. **Define variable types and domains**: Instruct the LLM what variable types are available (`integer`, `boolean`) and how to express domains (`min`/`max` for integers).
3. **List supported constraint types**: Enumerate the solver's supported constraint types (`equal`, `not_equal`, `linear`) so the LLM does not invent unsupported types.
4. **Use concrete examples**: Include a short example variable and constraint in the system prompt to anchor the LLM's output format.
5. **Keep it focused**: One system prompt per domain. A seating-specific prompt outperforms a generic "convert any constraints" prompt.
6. **Request JSON-only output**: Explicitly state "Respond with JSON only" to prevent the LLM from wrapping the response in explanatory text or markdown code fences.
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
Each scenario includes an `expected-output.json` that describes the expected structure of the pipeline results in mock mode, useful for regression testing and validation.
---
# LM Studio
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/integrations/lmstudio
Connect to a local LM Studio server for desktop LLM inference
> Run LLM inference on your own machine — connect nxusKit to LM Studio and prototype without cloud dependencies or API keys.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Using LM Studio for local inference
- **Scenario:** Connect to a local LM Studio server for desktop LLM inference
- **`tech_tags` in manifest:** `LLM` — example id **`lmstudio`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Developer local testing, offline prototyping
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/lmstudio`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/lmstudio
```
---
# Model Research Harness
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/integrations/model-research-harness
Research, test, score, rank, and report on model/provider fitness with a provider-neutral nxusKit workflow.
> Research model fitness with provider-neutral runs, Promptfoo import, deterministic policy checks, Bayesian confidence, and dry-run lifecycle recommendations.
**Scenarios**: `basic-ticket-routing` · `promptfoo-import` · `software-dev`
## Edition
**Community** - the default path uses provider-neutral LLM calls, mock/local fixtures, CLIPS-style deterministic policy checks, Bayesian confidence scoring, Promptfoo import, external-runner adapters, and dry-run lifecycle recommendations. Optional configs can use nxusKit CLIPS and Bayesian engines when native SDK dependencies are installed, with fixture-safe fallbacks for the public quickstart.
**Edition note:** Runs in Community Edition. Future Pro profiles may add Solver portfolio optimization and ZEN decision tables.
**Optional Pro profile** - future solver-backed portfolio selection and ZEN decision-table policies require a Pro or trial entitlement. The public quickstart below does not execute Pro code.
## What this demonstrates
**Difficulty: Advanced** ♦🏁 · LLM · CLIPS · BN
- **Summary:** Python-first model research and compatibility harness.
- **Scenario:** Import or define evaluation configs, run provider/model test matrices, score outputs, apply policy, aggregate confidence, and write reports.
- **`tech_tags` in manifest:** `LLM, CLIPS, BN` - example id **`model-research-harness`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only - see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** Python is authoritative. CLI/Bash is a thin wrapper around the Python runner.
- **Python:** standard library only for the public mock quickstart. The bundled `.yaml` configs use a strict JSON-compatible YAML subset; PyYAML is optional for broader user-authored YAML.
- **Native CLIPS/BN:** use a Python interpreter with `cffi` installed and an SDK with `python/src` plus `lib/libnxuskit.dylib`. The harness automatically adds `$NXUSKIT_SDK_DIR/python/src` when `NXUSKIT_SDK_DIR` is set; on macOS, avoid Apple/Xcode Python for native-engine runs unless `cffi` is installed there. Set `NXUSKIT_PYTHON=/path/to/python3` for the Bash wrapper when needed.
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Model evaluation | Score model candidates against task-specific outputs and report confidence instead of relying on ad hoc impressions |
| Provider comparison | Compare local and cloud providers through one provider-neutral workflow while keeping capability claims honest |
| Lifecycle policy | Generate dry-run pull, pin, keep, or retest recommendations bounded by deterministic policy |
| Software development workflow research | Exercise code analysis, bug finding, bugfixing, generation, refactoring, and review scenarios with public-safe fixtures |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/model-research-harness`:
cd python && python3 main.py --help
cd bash && bash main.sh --help
```
## Run
Mock mode uses checked-in fixtures. It does not require cloud credentials, Promptfoo, Ollama, or a Pro entitlement.
```bash
cd python
python3 main.py --config ../configs/nxuskit-harness-basic.yaml --mode mock --json
python3 main.py --config ../configs/nxuskit-harness-software-dev.yaml --mode mock --output-dir ../.tmp/software-dev
```
Thin CLI/Bash wrapper:
```bash
cd bash
bash main.sh --config ../configs/nxuskit-harness-basic.yaml --mode mock --json
```
Promptfoo import:
```bash
cd python
python3 main.py --import-promptfoo ../configs/promptfoo-basic.yaml --mode import-promptfoo --json
python3 main.py \
--import-promptfoo ../configs/promptfoo-requires-code.yaml \
--compatibility-report ../.tmp/promptfoo-requires-code-report.json \
--json
```
The second command is intentionally fail-closed: it writes a compatibility report that requires `--allow-code` or `--promptfoo-native-reference`.
## Configs
| Config | Purpose |
|--------|---------|
| `nxuskit-harness-basic.yaml` | Minimal mock quickstart for ticket classification |
| `nxuskit-harness-clips-policy.yaml` | Deterministic CLIPS-style required-field and forbidden-value checks |
| `nxuskit-harness-clips-engine.yaml` | Real nxusKit `ClipsSession` policy execution with Python fallback when native CLIPS is unavailable |
| `nxuskit-harness-bayesian-confidence.yaml` | Posterior confidence from sparse weighted evidence |
| `nxuskit-harness-bn-engine.yaml` | Real nxusKit BN inference over model-fitness evidence with beta fallback when native BN is unavailable |
| `nxuskit-harness-local-vs-cloud.yaml` | Local fixture versus cloud-reference fixture comparison |
| `nxuskit-harness-structured-output.yaml` | Native JSON-mode claims versus harness-side schema validation |
| `nxuskit-harness-lifecycle-policy.yaml` | Dry-run cache and lifecycle recommendations |
| `nxuskit-harness-lifecycle-mutation-fixture.yaml` | Public-safe mutation gate fixture requiring both external and lifecycle approval flags |
| `nxuskit-harness-matrix-template.yaml` | Compact prompt/parameter matrix expansion syntax |
| `nxuskit-harness-native-ollama-template.yaml` | Native Ollama schema, image, thinking, and tool-call knobs behind harness scoring |
| `nxuskit-harness-software-dev.yaml` | Code analysis, bug finding, bugfixing, code generation, refactoring, and review scenarios |
| `nxuskit-harness-external-command-fixture.yaml` | Public-safe fixture contract for wrapping operational runners |
| `nxuskit-harness-devops-ollama-parity.yaml` | Opt-in local adapter shape for a private Ollama research harness checkout |
| `promptfoo-basic.yaml` | Promptfoo-compatible config that imports and runs |
| `promptfoo-requires-code.yaml` | Promptfoo config that requires explicit trust or native-reference mode |
Test blocks may include a `matrix` object to expand variants without duplicating config:
```json
{
"id": "format-{{ prompt_variant }}-think-{{ think }}",
"matrix": {
"prompt_variant": ["baseline", "strict"],
"think": ["off", "low"]
}
}
```
Each combination is merged into `test.vars`, so prompts, ids, and adapter placeholders can reference the generated values.
## Operational Adapter Mode
The harness can wrap existing operational research runners through explicit external-command tests. This is useful when a team already has domain-specific scripts for local Ollama inventory, structured extraction, image/document pipelines, cache policy, or row-level fixture scoring.
External commands are fail-closed and never run unless `--allow-external` is supplied:
```bash
cd python
python3 main.py \
--config ../configs/nxuskit-harness-external-command-fixture.yaml \
--allow-external \
--json
```
The fixture config runs only checked-in deterministic fixture commands. The DevOps parity config is a template for private/local use and expects `OLLAMA_MODEL_TESTING_ROOT` to point at an existing `ollama-model-testing` checkout:
```bash
export OLLAMA_MODEL_TESTING_ROOT=/path/to/ollama-model-testing
cd python
python3 main.py \
--config ../configs/nxuskit-harness-devops-ollama-parity.yaml \
--allow-external \
--only-test common-sense-carwash \
--output-dir ../.tmp/devops-parity
```
Use `--exclude-test` to skip expensive tests from a larger config. Both `--only-test` and `--exclude-test` accept comma-separated ids and may be repeated.
The public adapter normalizes DevOps-style report shapes for common-sense curation, prompted/native tool intent, direct structured extraction, two-stage OCR or VLM pipelines, safe-labs row-level scoring, and CSV/TSV comparison helpers. The DevOps parity template also includes non-mutating `ollama-cache status`, `list`, and `plan-evict` checks.
External lifecycle mutation such as pulling, removing, pinning, or evicting models requires a test with `external_command.mutation: true` and both flags:
```bash
python3 main.py \
--config ../configs/nxuskit-harness-lifecycle-mutation-fixture.yaml \
--allow-external \
--allow-lifecycle-mutations
```
Public configs should keep mutation commands behind explicit customer policy bounds.
## Output
Each run can write:
- `result.json`
- `summary.md`
- Promptfoo compatibility report when importing Promptfoo configs
- Scenario-level pass/fail matrix
- Provider/model recommendation table
- Capability truth table
The capability truth table separates native provider guarantees from harness-side validation and repair. For v1.0.0, Groq remains provider id `groq` with `GROQ_API_KEY`; xAI Grok uses provider id `xai` with `XAI_API_KEY`.
## Live Mode
Live mode uses nxusKit provider factories for `ollama`, `lmstudio`, `openai`, `claude`, `groq`, and `xai` when credentials or local services are configured:
```bash
cd python
python3 main.py --config ../configs/nxuskit-harness-basic.yaml --mode live --provider ollama --model llama3.2
```
Strict schema support, native tool calling, and thinking controls vary by provider and model. The harness reports those differences instead of treating every backend as equivalent.
For Ollama features that are not yet normalized across every provider, set `native_ollama: true` on the provider or test. That path uses Ollama's local `/api/chat` API directly and supports `schema`/JSON `format`, `think`, `tools`, image files, `options`, and `num_predict`. If an Ollama build rejects the `think` field, the harness retries once without it and records the observed metadata.
## Promptfoo Compatibility
Portable Promptfoo configs import directly. Prompt/provider matrices expand to harness tests. Configs with executable or provider-native behavior fail closed unless the caller acknowledges the trust boundary:
```bash
python3 main.py --import-promptfoo ../configs/promptfoo-requires-code.yaml --allow-code --json
python3 main.py --import-promptfoo ../configs/promptfoo-requires-code.yaml --promptfoo-native-reference --json
```
With `--allow-code`, JavaScript assertions are executed through `node` when available. Unsupported assertions still fail closed instead of silently disappearing from the score.
## nxusKit Engine Hooks
The default configs are fixture-safe and run with stdlib Python. Engine configs demonstrate how the same harness can call nxusKit-native reasoning providers:
- `policy.engine: "nxuskit-clips"` loads a CLIPS rules file through `ClipsSession`, asserts the model output as a fact, and converts emitted finding facts into policy dispositions. `on_engine_unavailable: "fallback-python"` keeps public smoke tests runnable when native CLIPS dependencies are not installed.
- `bayesian.engine: "nxuskit-bn"` loads a BIF model through nxusKit BN, maps test scores into evidence, and queries a configured posterior. `on_engine_unavailable: "fallback-beta"` keeps reports useful on machines without native BN dependencies.
Native-engine smoke example:
```bash
export NXUSKIT_SDK_DIR="${NXUSKIT_SDK_DIR:-$HOME/.nxuskit/sdk/current}"
export NXUSKIT_LIB_PATH="$NXUSKIT_SDK_DIR/lib/libnxuskit.dylib"
# Pick a Python with cffi installed. On this development Mac, Homebrew Python works.
/opt/homebrew/bin/python3 -c "import cffi"
/opt/homebrew/bin/python3 python/main.py \
--config configs/nxuskit-harness-clips-engine.yaml \
--json
/opt/homebrew/bin/python3 python/main.py \
--config configs/nxuskit-harness-bn-engine.yaml \
--json
```
## Release Notes For Review
- Python is the authoritative implementation. Bash remains a thin wrapper for automation-friendly entry points.
- Promptfoo import covers common portable config shapes, prompt/provider matrices, explicit trust gates for code/native behavior, and JavaScript assertion execution under `--allow-code`.
- CLIPS and Bayesian examples include both deterministic/fallback checks and opt-in nxusKit-native engine execution.
- Operational parity is provided through explicit external-command adapters, not private baked-in assumptions. Public releases should keep private rankings, fixture paths, and cache policy defaults out of bundled configs.
- Lifecycle mutation remains blocked unless both `--allow-external` and `--allow-lifecycle-mutations` are supplied, and customer auto-approval should be bounded in config.
---
# Ollama
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/integrations/ollama
Connect to a local Ollama instance for private LLM inference
> Run open-source LLMs on your own hardware using the same nxusKit interface you already use for Claude and OpenAI.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Using Ollama for local inference
- **Scenario:** Connect to a local Ollama instance for private LLM inference
- **`tech_tags` in manifest:** `LLM` — example id **`ollama`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
On-premise AI deployment, air-gapped inference
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/ollama`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/ollama
```
---
# ZEN Decision Tables -- Personality Variants & Hit Policies
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/integrations/zen-decisions
Demonstrates ZEN JSON Decision Model (JDM) evaluation through three scenarios: a maze-navigating rat with interchangeable personality variants, a potion recipe selector using collect hit policy, and a food truck planner combining decision tables with expression nodes. This is the first nxusKit example built on the ZEN decision engine.
> Evaluate business decision tables in Go, Rust, and Python using the ZEN engine — from pricing rules to eligibility checks, with first-hit and collect hit policies.
**Scenarios**: `maze-rat` · `potion` · `food-truck`
## Edition
**Pro** — requires a Pro (or trial) entitlement for ZEN evaluation APIs.
## What this demonstrates
**Difficulty: Starter** 🟢 · ZEN
- **Summary:** ZEN decision table evaluation via nxusKit SDK
- **Scenario:** Evaluate business decision tables using the ZEN engine
- **`tech_tags` in manifest:** `ZEN` — example id **`zen-decisions`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description | Rust | Go |
|---------|-------------|------|-----|
| **ZEN Evaluate** | Stateless JDM evaluation | `nxuskit_zen_evaluate()` | `nxuskit-go.ZenEvaluate()` |
| **First Hit Policy** | Return first matching rule | `"hitPolicy": "first"` | `"hitPolicy": "first"` |
| **Collect Hit Policy** | Return all matching rules | `"hitPolicy": "collect"` | `"hitPolicy": "collect"` |
| **Expression Nodes** | Computed fields in pipeline | `expressionNode` | `expressionNode` |
| **Personality Variants** | Same input, different models | Multiple JDM files | Multiple JDM files |
| **Result Freeing** | Memory management for results | `nxuskit_zen_free_result()` | Automatic (Go wrapper) |
## Real-World Application
Pricing rules, eligibility determination, policy evaluation.
## Technologies
ZEN
## Pipeline Architecture
### Maze Rat (First Hit Policy)
```
┌──────────────────┐
│ cautious JDM │──> action: sniff_around
└──────────────────┘
┌───────────┐ ┌──────────────────┐
│ Input │──┬──>│ greedy JDM │──> action: go_right
│ (shared) │ │ └──────────────────┘
└───────────┘ │ ┌──────────────────┐
└──>│ explorer JDM │──> action: go_right
└──────────────────┘
```
### Potion (Collect Hit Policy)
```
┌───────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Input │──>│ Decision Table │──>│ All Matching │
│ │ │ (collect policy) │ │ Recipes │
└───────────┘ └──────────────────┘ └──────────────────┘
```
### Food Truck (Decision + Expression Pipeline)
```
┌───────────┐ ┌──────────────────┐ ┌──────────────────┐ ┌──────────┐
│ Input │──>│ Decision Table │──>│ Expression Node │──>│ Output │
│ │ │ (location/price) │ │ (menu/restock) │ │ │
└───────────┘ └──────────────────┘ └──────────────────┘ └──────────┘
```
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/integrations/zen-decisions`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario maze-rat
cargo run -- --scenario potion --verbose
cargo run -- --scenario food-truck --step
```
### Go
```bash
cd go
make build
./bin/zen-decisions --scenario maze-rat
./bin/zen-decisions --scenario potion --verbose
./bin/zen-decisions --scenario food-truck --step
```
Or directly:
```bash
cd go
go run . --scenario maze-rat
```
## Scenarios
### Maze Rat (Personality Variants)
A maze-navigating rat with three interchangeable personality variants, each encoded as a separate JDM file. All share the same input schema but produce different actions.
**Input fields**: `scent_strength` (1-10), `dead_ends_nearby` (0-5), `hunger_level` (1-10)
**Output fields**: `action` (go_left, go_right, backtrack, sniff_around, rest), `confidence` (0.0-1.0)
| Personality | Strategy | Key Trait |
|-------------|----------|-----------|
| **Cautious** | Avoids dead ends, backtracks when risky | High dead_ends triggers backtrack |
| **Greedy** | Always follows scent, ignores dead ends | Strong scent always means go_right |
| **Explorer** | Seeks new paths, ignores scent | Prefers go_left to explore unknown areas |
With the default input (`scent_strength=7, dead_ends_nearby=2, hunger_level=4`):
- Cautious: sniff_around (0.60 confidence) -- strong scent but hesitant
- Greedy: go_right (0.95 confidence) -- immediately follows strong scent
- Explorer: go_right (0.80 confidence) -- few dead ends, worth exploring right
### Potion (Collect Hit Policy)
A potion recipe selector that returns all matching recipes using the collect hit policy. Multiple recipes can match the same ingredients and desired effect.
**Input fields**: `ingredients` (comma-separated list), `desired_effect` (healing, strength, invisibility, speed), `caution_level` (low, medium, high)
**Output fields**: `recipe_name`, `recipe_steps`, `warnings`
With the default input (`ingredients=mushroom,moonstone, desired_effect=healing, caution_level=medium`):
- Healing Tonic (mushroom + healing matches)
- Unknown Brew (default catch-all also matches under collect policy)
### Food Truck (Expression Nodes)
A food truck location and menu planner that chains a decision table with an expression node. The decision table selects location and base pricing; the expression node computes menu adjustments.
**Input fields**: `time_of_day`, `weather`, `nearby_events`, `inventory_level`
**Output fields**: `location`, `price_multiplier`, `menu_adjustment`, `restock_alert`
With the default input (`time_of_day=lunch, weather=sunny, nearby_events=large, inventory_level=medium`):
- Location: Main Street Park (lunch + sunny + large event)
- Price multiplier: 1.3 (premium for large event)
- Menu: full menu (medium inventory)
- Restock alert: false
## Decision Table Concepts
### Hit Policies
| Policy | Behavior | Use Case |
|--------|----------|----------|
| **first** | Return the first matching rule | Prioritized rules, fallback chains |
| **collect** | Return all matching rules | Multiple recommendations, audit trails |
With **first** hit policy, rule order matters -- the first match wins. With **collect**, all matching rules are returned as an array.
### Expression Nodes
Expression nodes compute derived fields using simple expressions:
```json
{
"type": "expressionNode",
"content": {
"expressions": [
{"key": "output_field", "value": "input_field"},
{"key": "computed", "value": "if condition then 'a' else 'b'"}
]
}
}
```
Expressions support:
- Field references: `field_name` passes through a value
- Conditionals: `if condition then value1 else value2`
- Comparisons: `==`, `!=`, `>`, `<`, `>=`, `<=`
- String literals: `'single quoted'`
### CLIPS vs ZEN Comparison
| Aspect | CLIPS (Rule Engine) | ZEN (Decision Tables) |
|--------|--------------------|-----------------------|
| **Model format** | `.clp` rule files | `.json` JDM files |
| **Evaluation** | Forward-chaining inference | Table lookup + expressions |
| **State** | Working memory (facts) | Stateless per evaluation |
| **Complexity** | Arbitrary rule logic | Structured table/expression |
| **Best for** | Complex reasoning chains | Configuration-driven decisions |
| **Hit policies** | N/A (all matching rules fire) | first, collect |
| **Session management** | Required (create/destroy) | None (stateless) |
## JDM (JSON Decision Model) Format
The JDM format follows the GoRules specification:
```json
{
"contentType": "application/vnd.gorules.decision",
"edges": [
{"id": "e1", "sourceId": "input", "targetId": "dt1", "type": "edge"}
],
"nodes": [
{"id": "input", "type": "inputNode", ...},
{"id": "dt1", "type": "decisionTableNode", "content": {...}},
{"id": "output", "type": "outputNode", ...}
]
}
```
### Supported Node Types
| Type | Description |
|------|-------------|
| `inputNode` | Entry point; passes input data to connected nodes |
| `outputNode` | Exit point; returns the final result |
| `decisionTableNode` | Evaluates input against rules with configurable hit policy |
| `expressionNode` | Computes derived fields from expressions |
| `switchNode` | Routes to different branches based on conditions |
**Note**: `functionNode` (JavaScript) is not supported by the nxusKit ZEN provider.
### Rule Field Formats
- Comparison operators: `> 30`, `<= 10`, `>= 7`, `== 5`, `!= 0`
- String values (in outputs): `"\"cool\""` (double-quoted inside JSON)
- Numeric values: `0.85`, `1.3`
- Boolean values: `true`, `false`
- Empty field: `""` (matches any value / wildcard)
## Interactive Modes
```bash
# Verbose mode -- show raw JSON results
cargo run -- --scenario maze-rat --verbose # Rust
go run . --scenario maze-rat --verbose # Go
# Step mode -- pause at each step with explanations
cargo run -- --scenario potion --step # Rust
go run . --scenario potion --step # Go
# Combined mode
cargo run -- --scenario food-truck --verbose --step
go run . --scenario food-truck --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
Each scenario includes an `expected-output.json` that describes expected results for regression testing.
---
# Auth Helper
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/auth-helper
Demonstrates OAuth login flow and credential management using the nxuskit SDK.
> Wire up OAuth flows and API key credentials across every provider your app supports, with a single unified auth interface.
**Scenarios**: `status` · `set` · `remove` · `dashboard`
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · Auth · OAuth
- **Summary:** OAuth login flow and credential management helper *(from `conformance/examples_manifest.json`: **auth-helper**)*.
- **Scenario:** List providers, check auth status, set credentials, initiate OAuth flows.
- **`tech_tags`:** `Auth`, `OAuth`.
- Listing all supported providers and their authentication methods
- Checking authentication status for individual providers
- Setting and removing API key credentials
- Initiating an OAuth login flow (for OAuth-capable providers)
- Viewing a complete authentication status dashboard
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** Go, Rust (CLI and egui GUI).
## Tier
Community (free)
## Languages
| Language | Path | Description |
|----------|------|-------------|
| Go | [go/](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/auth-helper/go/) | CLI-based auth management |
| Rust (CLI) | [cli/](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/auth-helper/cli/) | Terminal-based OAuth + credential management |
| Rust (core) | [core/](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/auth-helper/core/) | Shared auth library used by CLI and egui |
| Rust (egui) | [egui/](https://github.com/nxus-SYSTEMS/nxusKit-examples/tree/main/examples/patterns/auth-helper/egui/) | GUI-based OAuth flow with egui |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# Go
cd go && make build
# Rust CLI
cd cli && cargo build
# Rust GUI (requires egui dependencies)
cd egui && cargo build
```
## Run
```bash
# Go
cd go && ./bin/auth-helper
# Rust CLI
cd cli && cargo run
# Rust GUI
cd egui && cargo run
```
## Notes
- No current providers support OAuth yet (infrastructure is ready for future providers)
- API key authentication works with all providers that require credentials
- The OAuth flow launches a browser and starts a localhost callback server
---
# Basic Chat
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/basic-chat
Send a single chat message and receive a response.
> Send your first LLM chat message in minutes, then swap providers without touching your application code.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Basic chat completion with a simple prompt
- **Scenario:** Send a single chat message and receive a response
- **`tech_tags` in manifest:** `LLM` — example id **`basic-chat`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Customer support chatbot, FAQ assistant
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
## Build
Use an installed SDK (`NXUSKIT_SDK_DIR`); from the repo root, `scripts/test-examples.sh` patches `nxuskit` path deps to that tree and builds this crate.
```bash
cd rust && cargo build
cd ../go && make build
cd ../python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/basic-chat
```
### Python
```bash
cd python
python main.py
```
See also: [`EXAMPLE_README_TEMPLATE.md`](https://github.com/nxus-SYSTEMS/nxusKit-examples/blob/main/examples/EXAMPLE_README_TEMPLATE.md) for the standard README sections.
---
# Bayesian Inference Pattern
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/bayesian-inference
Demonstrates Bayesian Network inference using multiple algorithms: load a BIF model, set observed evidence, and compute posterior probability distributions over unobserved variables using exact and approximate methods.
> Run exact and approximate Bayesian inference on real-world diagnostic models using four algorithms and three themed scenarios — all from a single SDK call.
**Scenarios**: `haunted-house` · `coffee-shop` · `plant-doctor`
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · BN
- **Summary:** Bayesian network inference via nxusKit SDK
- **Scenario:** Build a Bayesian network and perform probabilistic inference
- **`tech_tags` in manifest:** `BN` — example id **`bayesian-inference`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **BIF Model Loading** | Parse Bayesian Interchange Format files into a directed acyclic graph with conditional probability tables |
| **Evidence Setting** | Clamp observed variables to known values before inference |
| **Variable Elimination (VE)** | Exact inference by marginalizing out variables in an optimal elimination order |
| **Junction Tree (JT)** | Exact inference via clique tree message passing with global consistency |
| **Loopy Belief Propagation (LBP)** | Approximate inference via iterative message passing on the factor graph |
| **Gibbs Sampling** | Approximate MCMC inference by sampling each variable conditioned on its Markov blanket |
| **Streaming Results** | Progressive output of posteriors as each algorithm step completes |
| **Algorithm Comparison** | Side-by-side comparison of exact and approximate posteriors with tolerance checking |
**Provider Compatibility**: Uses the nxusKit Bayesian Network provider (no LLM provider required)
## Technologies
BN
## Pattern Overview
Many real-world diagnosis and prediction problems can be modeled as Bayesian Networks -- directed acyclic graphs where nodes represent random variables and edges encode conditional dependencies. Given partial observations (evidence), inference computes updated beliefs (posteriors) about unobserved variables. This pattern walks through four inference algorithms on scenario-driven models loaded from BIF files, comparing exact and approximate results.
## Scenarios
Three themed scenarios are included under `scenarios/`:
- **Haunted House** -- Investigate a supposedly haunted house by observing cold spots, flickering lights, and muddy footprints, then infer the probability of a ghost, raccoon, wiring fault, and cold draft. 8 variables, 8 CPTs.
- **Coffee Shop** -- Diagnose a bad espresso shot by observing bitter taste, no sourness, and no wateriness, then infer extraction level, grind size, water temperature, bean age, and freshness. 8 variables, 8 CPTs.
- **Plant Doctor** -- Diagnose a sick plant by observing yellow leaves, wilting, no spots, and slow growth, then infer overwatering, nutrient deficiency, sunlight issues, disease, and pest infestation. 9 variables, 9 CPTs.
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/bayesian-inference`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario haunted-house
cargo run -- --scenario coffee-shop --verbose
cargo run -- --scenario plant-doctor --step
```
### Go
```bash
cd go
make build
./bin/bayesian-inference --scenario haunted-house
./bin/bayesian-inference --scenario coffee-shop --verbose
./bin/bayesian-inference --scenario plant-doctor --step
```
### Python
```bash
cd python
pip install -e ../../../../packages/nxuskit-py # if not already installed
python main.py --scenario haunted-house
python main.py --scenario coffee-shop --step
```
## Inference Steps
Each run progresses through four algorithm steps:
| Step | Algorithm | Type | What It Does |
|------|-----------|------|--------------|
| 1 | **Variable Elimination** | Exact | Eliminates variables one at a time, computing exact marginal posteriors via factor multiplication and summation |
| 2 | **Junction Tree** | Exact | Builds a clique tree from the model, propagates messages for globally consistent exact posteriors |
| 3 | **Loopy Belief Propagation** | Approximate | Passes messages iteratively on the factor graph until convergence (or max iterations) |
| 4 | **Gibbs Sampling** | Approximate | Draws MCMC samples from the posterior, estimating marginals from sample frequencies |
## Scenario Data Format
Each scenario is a directory containing two files:
### `model.bif` -- Bayesian Interchange Format
Defines the network structure, variable domains, and conditional probability tables:
```bif
network unknown {
}
variable ghost {
type discrete [ 2 ] { yes, no };
}
variable cold_spots {
type discrete [ 2 ] { yes, no };
}
probability ( ghost ) {
table 0.05, 0.95;
}
probability ( cold_spots | ghost, cold_draft ) {
(yes, yes) 0.9, 0.1;
(yes, no) 0.8, 0.2;
(no, yes) 0.6, 0.4;
(no, no) 0.05, 0.95;
}
```
### `evidence.json` -- Observed Variables
Maps variable names to their observed values:
```json
{
"cold_spots": "yes",
"flickering_lights": "yes",
"footprints": "muddy"
}
```
### `expected-output.json` -- Golden Output
Contains exact posteriors from VE/JT and tolerance bounds for LBP/Gibbs, plus qualitative observations about the inference results. Used for automated validation of implementation correctness.
## Algorithm Comparison
| Property | Variable Elimination | Junction Tree | Loopy BP | Gibbs Sampling |
|----------|---------------------|---------------|----------|----------------|
| **Type** | Exact | Exact | Approximate | Approximate |
| **Method** | Factor marginalization | Clique tree message passing | Iterative factor graph messages | MCMC sampling |
| **Guarantees** | Exact posteriors | Exact posteriors | No convergence guarantee on loopy graphs | Converges asymptotically |
| **Speed** | Fast for small networks | Fast after tree construction | Fast per iteration, may need many | Slow (many samples needed) |
| **Memory** | Exponential in treewidth | Exponential in max clique size | Linear in edges | Linear in variables |
| **Best For** | Small-medium networks | Repeated queries on same model | Large networks with weak loops | Complex models, posterior samples |
| **Parameters** | Elimination order | None (automatic) | Max iterations, damping factor | Num samples, burn-in, seed |
VE and JT should produce identical posteriors (both are exact). LBP and Gibbs posteriors should fall within the tolerance bounds specified in `expected-output.json`.
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Haunted House | Fault diagnosis, anomaly detection, sensor fusion from multiple noisy sensors pointing to hidden causes |
| Coffee Shop | Manufacturing quality control, process parameter tuning, root cause analysis in production |
| Plant Doctor | Medical diagnosis, agricultural advisory systems, multi-symptom differential diagnosis |
## Interactive Modes
All implementations support debugging flags:
```bash
# Verbose mode - show CPTs, elimination orders, message schedules, and sample traces
cargo run -- --scenario haunted-house --verbose # Rust
./bin/bayesian-inference --scenario haunted-house --verbose # Go
python main.py --scenario haunted-house --verbose # Python
# Step mode - pause at each algorithm with explanations
cargo run -- --scenario haunted-house --step # Rust
./bin/bayesian-inference --scenario haunted-house --step # Go
python main.py --scenario haunted-house --step # Python
# Combined mode
cargo run -- --scenario haunted-house --verbose --step
```
Or use environment variables (Rust and Go only):
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python
cd python && python -m pytest
```
## Production Considerations
1. **Algorithm selection**: Use VE or JT for small-to-medium networks where exact inference is tractable. Switch to LBP or Gibbs for large networks where treewidth makes exact inference infeasible.
2. **Convergence monitoring**: LBP may not converge on graphs with strong loops. Monitor message deltas and set a maximum iteration count.
3. **Sample size tuning**: For Gibbs sampling, increase `num_samples` and `burn_in` for tighter posterior estimates. Use a fixed seed for reproducibility in testing.
4. **Evidence validation**: Verify that evidence variable names and values match the BIF model before running inference. Mismatched evidence silently produces incorrect posteriors.
---
# Blocking API
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/blocking-api
Make synchronous LLM calls without async runtime
> Call LLMs synchronously from any Rust code — no async runtime required, no await syntax, no tokio dependency to manage.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Synchronous blocking API for simpler use cases
- **Scenario:** Make synchronous LLM calls without async runtime
- **`tech_tags` in manifest:** `LLM` — example id **`blocking-api`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
CLI tools, batch processing scripts
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/blocking-api`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/blocking-api
```
---
# Capability Detection
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/capability-detection
Query provider capabilities before dispatching requests
> Stop hardcoding model names — query provider capabilities at runtime and let task requirements drive model selection across any LLM backend.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Detecting provider capabilities at runtime
- **Scenario:** Query provider capabilities before dispatching requests
- **`tech_tags` in manifest:** `LLM` — example id **`capability-detection`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Adaptive AI middleware, feature-gated UX
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/capability-detection`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/capability-detection
```
---
# Convenience API
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/convenience-api
Use simplified one-liner API for quick LLM calls
> Skip the boilerplate: call any LLM with a single line, letting nxusKit detect your provider and credentials automatically.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** LiteLLM-style convenience API usage
- **Scenario:** Use simplified one-liner API for quick LLM calls
- **`tech_tags` in manifest:** `LLM` — example id **`convenience-api`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Rapid prototyping, scripting with LLM capabilities
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/convenience-api`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/convenience-api
```
---
# Model Router (Cost Tiers) Pattern
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/cost-routing
Demonstrates intelligent routing of requests to different models based on task complexity to optimize cost and quality.
> Route every LLM request to the right model for the job, so you stop paying premium prices for economy-grade tasks.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Cost-aware provider routing and selection
- **Scenario:** Route requests to the cheapest capable provider
- **`tech_tags` in manifest:** `LLM` — example id **`cost-routing`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **Provider Abstraction** | Same interface for all models enables seamless tier switching |
| **Request Portability** | `ChatRequest` works identically across model tiers |
| **Token Normalization** | Consistent token usage tracking for cost calculations |
**Provider Compatibility**: Works with any provider supporting multiple models (OpenAI, Ollama, etc.)
## Pattern Overview
Not all prompts need the most expensive model. This pattern analyzes prompt characteristics and routes requests to an appropriate cost tier, balancing quality requirements with cost efficiency.
## Cost Tiers
| Tier | Model | Use Case | Cost |
|------|-------|----------|------|
| Economy | gpt-4o-mini | Simple queries, lookups | $ |
| Standard | gpt-4o | General tasks, explanations | $$ |
| Premium | gpt-4-turbo | Complex analysis, reasoning | $$$ |
## Classification Heuristics
The example uses simple heuristics to classify tasks:
1. **Premium tier triggers**:
- Keywords: "analyze", "compare", "evaluate", "synthesize", "critique"
- Prompt length > 1000 characters
2. **Standard tier**:
- Prompt length > 200 characters (without premium keywords)
3. **Economy tier**:
- Short, simple prompts
## Real-World Application
Cost-optimized AI platform, budget-aware inference.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/cost-routing`:
cd rust && cargo build
cd go && make build
```
## Library usage
### Rust
```rust
use cost_routing::{classify_task, routed_chat, CostTier};
// Classify without making API call
let tier = classify_task(prompt);
println!("Would use: {} tier", tier.as_str());
// Or route and execute
let result = routed_chat(&provider, prompt).await?;
println!("Used {} tier", result.tier.as_str());
```
### Go
```go
// Classify without making API call
tier := ClassifyTask(prompt)
fmt.Println("Would use:", tier.Name(), "tier")
// Or route and execute
result, err := RoutedChat(ctx, provider, prompt)
fmt.Println("Used", result.Tier.Name(), "tier")
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Advanced Classification
For production, consider more sophisticated approaches:
1. **Intent classification**: Use a small model to classify intent first
2. **Historical data**: Learn from past prompt/tier success rates
3. **User preferences**: Allow users to specify quality requirements
4. **Dynamic pricing**: Adjust tiers based on current API pricing
## Production Considerations
1. **Calibration**: Tune thresholds based on your specific use cases
2. **Monitoring**: Track accuracy and cost savings by tier
3. **Override capability**: Allow manual tier selection for edge cases
4. **A/B testing**: Validate routing decisions improve outcomes
---
# Multi Provider
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/multi-provider
Configure and switch between multiple LLM providers at runtime
> Run the same prompt across Claude, OpenAI, and Ollama simultaneously using one unified interface that normalizes responses and token usage.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Using multiple providers in one application
- **Scenario:** Configure and switch between multiple LLM providers at runtime
- **`tech_tags` in manifest:** `LLM` — example id **`multi-provider`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Multi-vendor AI gateway, provider comparison tool
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/multi-provider`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/multi-provider
```
### Python
```bash
cd python
python main.py
```
---
# Polymorphic
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/polymorphic
Use trait objects and interfaces to abstract over providers
> Swap LLM providers at runtime without touching your application logic — nxusKit's polymorphic patterns keep your code provider-agnostic from day one.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Polymorphic provider patterns with trait objects
- **Scenario:** Use trait objects and interfaces to abstract over providers
- **`tech_tags` in manifest:** `LLM` — example id **`polymorphic`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Plugin architecture, provider-agnostic application layer
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/polymorphic`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/polymorphic
```
---
# Multi-Provider Fallback Pattern
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/retry-fallback
Demonstrates automatic failover between multiple LLM providers for improved reliability.
> Chain multiple LLM providers together so a failed request automatically reroutes to the next available provider without changing your application code.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Retry and fallback strategies across providers
- **Scenario:** Automatically retry failed requests and fall back to alternate providers
- **`tech_tags` in manifest:** `LLM` — example id **`retry-fallback`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **Provider Abstraction** | `LLMProvider` trait/interface enables heterogeneous provider collections |
| **Unified Error Handling** | Same error types across all providers enable consistent fallback logic |
| **Provider Interchangeability** | Swap providers without changing application code |
**Provider Compatibility**: Claude, OpenAI, Ollama, and any custom provider implementing `LLMProvider`
## Pattern Overview
When working with LLM APIs, network issues, rate limits, or provider outages can interrupt service. This pattern chains multiple providers together, automatically falling back to the next provider when one fails.
## Key Features
- Sequential provider chain with automatic failover
- First successful response wins
- Error aggregation for debugging
- Provider-agnostic implementation
## Real-World Application
High-availability AI service, resilient inference pipeline.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/retry-fallback`:
cd rust && cargo build
cd go && make build
```
## Library usage
### Rust
```rust
use retry_fallback::chat_with_fallback;
use nxuskit::prelude::*;
// Create multiple providers (could be different providers in production)
let providers: Vec> = vec![
Box::new(OllamaProvider::builder().base_url("http://primary:11434").model("llama3").build()?),
Box::new(OllamaProvider::builder().base_url("http://secondary:11434").model("llama3").build()?),
];
// Request automatically falls back on failure
let response = chat_with_fallback(&providers, &request).await?;
```
### Go
```go
import llmkit "github.com/llmkit/nxuskit-go"
// Create multiple providers
providers := []llmkit.LLMProvider{provider1, provider2, provider3}
// Request automatically falls back on failure
resp, err := ChatWithFallback(ctx, providers, req)
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
Both implementations include unit tests using mock providers:
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Production Considerations
1. **Provider diversity**: Use different providers (OpenAI, Claude, Ollama) for true redundancy
2. **Timeout handling**: Set appropriate timeouts to avoid long waits before failover
3. **Circuit breakers**: Consider adding circuit breaker pattern for repeated failures
4. **Metrics**: Track which providers are failing to identify systemic issues
---
# Solver Pattern
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/solver
Demonstrates the full solver lifecycle: satisfaction checking, single- and multi-objective optimization, soft constraints, and what-if analysis using push/pop scoping.
> Define variables, add constraints, and solve complex planning problems with Z3 — without leaving your nxusKit workflow.
**Scenarios**: `theme-park` · `space-colony` · `fantasy-draft`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · Solver
- **Summary:** Z3 constraint solver integration via nxusKit SDK
- **Scenario:** Define and solve constraint satisfaction problems with Z3
- **`tech_tags` in manifest:** `Solver` — example id **`solver`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **SolverSession Lifecycle** | Create, build model incrementally, solve, and close via the nxuskit SDK |
| **Variable & Constraint Model** | Define typed variables with domains and add hard/soft constraints |
| **Satisfaction Solving** | Check feasibility before optimizing |
| **Single & Multi-Objective Optimization** | Maximize/minimize one or many weighted objectives |
| **Soft Constraints** | Weighted preferences the solver satisfies when possible |
| **Push/Pop Scoping** | Reversible what-if analysis without rebuilding the model |
**Provider Compatibility**: Uses the nxusKit Z3-based constraint solver (no LLM provider required)
## Technologies
Solver
## Pattern Overview
Many real-world planning problems require finding valid assignments to decision variables that satisfy a set of constraints, then optimizing one or more objectives. This pattern walks through five progressive solver steps using scenario-driven problem definitions loaded from JSON files.
## Scenarios
Three themed scenarios are included under `scenarios/`:
- **Theme Park Planning** -- Decide how many rides to build, staff to hire, land to allocate, and ticket prices to set while staying within budget and space constraints. Objectives: maximize rides, minimize budget.
- **Space Colony Planning** -- Design a self-sustaining colony by balancing population against habitat modules, solar panels, water recyclers, and food domes. What-if: simulate a solar storm that degrades panel efficiency by 30%.
- **Fantasy Sports Draft** -- Build an optimal roster under a $50,000 salary cap by selecting stats across QB, RB, WR, TE, and DEF positions to maximize total fantasy points. What-if: simulate key player injuries.
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/solver`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario theme-park
cargo run -- --scenario space-colony --verbose
cargo run -- --scenario fantasy-draft --step
```
### Go
```bash
cd go
make build
./bin/solver --scenario theme-park
./bin/solver --scenario space-colony --verbose
./bin/solver --scenario fantasy-draft --step
```
### Python
```bash
cd python
pip install -e ../../../../packages/nxuskit-py # if not already installed
python main.py --scenario theme-park
python main.py --scenario fantasy-draft --step
```
## Solver Steps
Each run progresses through five steps (steps are skipped when a scenario lacks the relevant definitions):
| Step | Name | What It Does |
|------|------|--------------|
| 1 | **Satisfaction** | Adds hard constraints and checks whether any feasible assignment exists (`sat` / `unsat`) |
| 2 | **Optimization** | Sets a single objective (maximize or minimize) and finds the optimal assignment |
| 3 | **Multi-objective** | Combines multiple objectives with weights into a single weighted optimization |
| 4 | **Soft constraints** | Adds weighted preference constraints the solver may violate if necessary |
| 5 | **What-if analysis** | Uses `push` / `pop` to temporarily add constraints, solve, then restore the base model |
## Scenario Data Format
Each scenario is a directory containing a `problem.json` file with the following structure:
```jsonc
{
"name": "Scenario Name",
"description": "Human-readable description of the planning problem.",
"variables": [
{
"name": "budget",
"var_type": "integer", // "integer", "real", or "boolean"
"domain": { "min": 50000, "max": 500000 }, // omitted for booleans
"label": "Total budget in dollars"
}
],
"constraints": [
{
"name": "cost_constraint",
"constraint_type": "ge", // "ge", "le", "eq", etc.
"variables": ["budget", "ride_count"],
"parameters": {}, // solver-specific parameters
"expression": "budget >= ride_count * 25000", // human-readable
"label": "Cost constraint"
}
],
"soft_constraints": [
// Same structure as constraints, with an additional "weight" field
{ "weight": 5.0, "..." : "..." }
],
"objectives": [
{
"name": "maximize_rides",
"direction": "maximize", // "maximize" or "minimize"
"expression": "ride_count",
"variable": "ride_count", // primary variable for simple objectives
"weight": 1.0, // relative weight for multi-objective
"priority": 1, // priority ordering
"label": "Maximize the number of rides"
}
],
"what_if_scenarios": [
{
"name": "Add Roller Coaster",
"description": "What happens if we commit to a roller coaster?",
"additional_constraints": [
// Same structure as constraints; added temporarily via push/pop
]
}
]
}
```
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Theme Park Planning | Facility layout, capital budgeting, resource allocation |
| Space Colony Planning | Infrastructure sizing, capacity planning, disaster recovery modeling |
| Fantasy Sports Draft | Portfolio optimization, team composition, auction bidding strategies |
## Interactive Modes
All implementations support debugging flags:
```bash
# Verbose mode - show solver stats, variable details, and intermediate state
cargo run -- --scenario theme-park --verbose # Rust
./bin/solver --scenario theme-park --verbose # Go
python main.py --scenario theme-park --verbose # Python
# Step mode - pause at each phase with explanations
cargo run -- --scenario theme-park --step # Rust
./bin/solver --scenario theme-park --step # Go
python main.py --scenario theme-park --step # Python
# Combined mode
cargo run -- --scenario theme-park --verbose --step
```
Or use environment variables (Rust and Go only):
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python
cd python && python -m pytest
```
## Production Considerations
1. **Timeout handling**: Set `timeout_ms` in `SolverConfig` to bound solve time on large models
2. **Incremental solving**: Add constraints and re-solve rather than rebuilding from scratch
3. **Soft constraint weights**: Calibrate weights based on domain expertise; higher weights are harder to violate
4. **What-if batching**: Use push/pop for rapid scenario comparison without session recreation
---
# Solver What-If Pattern
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/solver-what-if
Demonstrates push/pop scoping, assumption-based solving, and what-if analysis using the nxusKit constraint solver. Each scenario defines a base problem and several what-if variants that temporarily modify the model to explore alternative outcomes.
> Explore alternative outcomes without rebuilding your model — push constraints, solve, compare, and pop back to baseline in one clean pattern.
**Scenarios**: `wedding` · `mars` · `recipe`
## Edition
**Pro** — requires a Pro (or trial) entitlement.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · Solver
- **Summary:** What-if scenario analysis with solver streaming
- **Scenario:** Stream solver results for interactive what-if scenario exploration
- **`tech_tags` in manifest:** `Solver, Streaming` — example id **`solver-what-if`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust, python, bash (paths under this directory).
- **Solver entitlement:** Requires a Pro or trial entitlement because it uses the Z3-backed solver. No LLM provider is required.
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **SolverSession Lifecycle** | Create, build model incrementally, solve, and close via the nxuskit SDK |
| **Push/Pop Scoping** | Save and restore model state for reversible experimentation |
| **What-If Analysis** | Add temporary constraints, solve, compare deltas, then restore |
| **Explanation / Unsat Core** | Retrieve constraint labels that cause infeasibility via `Explanation()` |
| **Delta Comparison** | Compare base vs. what-if variable assignments and objective values |
**Provider Compatibility**: Uses the nxusKit Z3-based constraint solver (no LLM provider required)
## Technologies
Solver, Streaming
## Pattern Overview
Real-world planning often involves asking "what if?" -- exploring how changes to assumptions affect the optimal solution. This pattern uses the solver's push/pop mechanism to efficiently evaluate multiple alternative scenarios without rebuilding the model from scratch.
The pipeline for each run:
1. **Load** a problem with base constraints, objective, and what-if scenario definitions
2. **Solve** the base problem to establish a baseline optimal solution
3. **For each what-if scenario**:
- **Push** the current solver state (saves all constraints and objective)
- **Add** temporary constraints that define the alternative scenario
- **Solve** under the modified model
- If UNSAT, **retrieve explanation** (unsat core labels)
- **Compare** the what-if result to the baseline (show variable deltas)
- **Pop** the solver state (restores the base model)
4. **Summarize** all scenarios in a comparison table
## Scenarios
Three themed scenarios are included under `scenarios/`:
- **Wedding Budget Planning** -- Allocate a $25,000 wedding budget across venue, catering, flowers, photography, music, and decor. What-if: splurge on a fancy venue, cut the DJ, or double the budget.
- **Mars Colony Resource Allocation** -- Design a Mars colony by balancing colonists against solar panels, water recyclers, greenhouses, habitats, and power storage under a cargo mass limit. What-if: require 50+ colonists, simulate a dust storm, or get extra cargo capacity.
- **Recipe Scaling** -- Scale a baking recipe by adjusting flour, sugar, eggs, butter, milk, and vanilla while maintaining proper ratios. What-if: limited eggs, go fully vegan (may be UNSAT), or bake for a party.
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/solver-what-if`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
cd bash && make build
```
## Run
### Rust
```bash
cd rust
cargo run -- --scenario wedding
cargo run -- --scenario mars --verbose
cargo run -- --scenario recipe --step
```
### Go
```bash
cd go
make build
./bin/solver-what-if --scenario wedding
./bin/solver-what-if --scenario mars --verbose
./bin/solver-what-if --scenario recipe --step
```
### Python
```bash
cd python
python3 main.py --scenario wedding
python3 main.py --scenario mars --verbose
python3 main.py --scenario recipe --step
```
### CLI/Bash
```bash
cd bash
make run
make run ARGS="--scenario mars"
make run ARGS="--scenario recipe --verbose"
```
## Push/Pop Concepts
The solver's push/pop mechanism works like a stack of model snapshots:
```
Base model: [variables + constraints + objective]
|
push() --> saves state
|
add_constraints([temporary constraints])
solve() --> result under modified model
|
pop() --> restores base model (temporary constraints removed)
```
Key properties:
- **Push** creates a new scope level; all subsequent additions are scoped
- **Pop** removes everything added since the last push
- Multiple push/pop levels can be nested
- The solver does not re-initialize -- it reuses learned information for efficiency
## Unsat Core Explanation
When a what-if scenario makes the model infeasible (UNSAT), the solver can report which constraints are responsible:
1. Enable explanation with `ProduceExplanation: true` in the solve config
2. After an UNSAT result, call `Explanation()` to retrieve the unsat core
3. The `unsat_core_labels` array contains the constraint labels that form a minimal conflicting set
This is particularly useful for understanding *why* a scenario is impossible (e.g., the vegan recipe scenario where eggs=0 conflicts with the eggs-per-flour ratio constraint).
## Scenario Data Format
Each scenario is a directory containing a `problem.json` file:
```jsonc
{
"name": "Scenario Name",
"description": "Human-readable description.",
"variables": [
{
"name": "venue_cost",
"var_type": "integer",
"domain": { "min": 5000, "max": 15000 },
"label": "Cost of the venue in dollars"
}
],
"constraints": [
{
"name": "budget_limit",
"constraint_type": "le",
"variables": ["venue_cost", "catering_cost"],
"parameters": { "budget": 25000 },
"expression": "venue_cost + catering_cost <= 25000",
"label": "Budget constraint"
}
],
"objectives": [
{
"name": "maximize_total_quality",
"direction": "maximize",
"expression": "venue_cost + catering_cost",
"variable": "venue_cost",
"weight": 1.0,
"label": "Maximize total quality"
}
],
"what_if_scenarios": [
{
"name": "fancy_venue",
"description": "What if we splurge on a fancy venue?",
"additional_constraints": [
{
"name": "fancy_venue_min",
"constraint_type": "ge",
"variables": ["venue_cost"],
"parameters": { "min_value": 12000 },
"expression": "venue_cost >= 12000",
"label": "Fancy venue minimum"
}
]
}
]
}
```
## Real-World Applications
| Application | How this example applies |
|-------------|--------------------------|
| Wedding Budget Planning | Event planning, capital budgeting, portfolio allocation |
| Mars Colony Planning | Infrastructure sizing, supply chain planning, disaster preparedness |
| Recipe Scaling | Manufacturing scaling, formulation optimization, process engineering |
## Interactive Modes
All implementations support debugging flags:
```bash
# Verbose mode - show solver stats and constraint details
cargo run -- --scenario wedding --verbose # Rust
./bin/solver-what-if --scenario wedding --verbose # Go
python3 main.py --scenario wedding --verbose # Python
make run ARGS="--scenario wedding --verbose" # CLI/Bash
# Step mode - pause at each phase with explanations
cargo run -- --scenario wedding --step # Rust
./bin/solver-what-if --scenario wedding --step # Go
python3 main.py --scenario wedding --step # Python
make run ARGS="--scenario wedding --step" # CLI/Bash
# Combined mode
cargo run -- --scenario wedding --verbose --step
```
Or use environment variables where supported:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python smoke
cd python && python3 main.py --help
# CLI/Bash
cd bash && make test
```
## Production Considerations
1. **Push/Pop depth**: Keep nesting shallow; deep push/pop stacks add solver overhead
2. **Explanation cost**: Producing unsat cores adds overhead; only enable when needed
3. **Constraint interaction**: What-if constraints are *added* to existing constraints via push, not *replaced*. Design base constraints to be compatible with what-if additions.
4. **Timeout handling**: Set `timeout_ms` in `SolverConfig` to bound solve time on large models
---
# Streaming
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/streaming
Stream tokens from a chat completion as they arrive
> Stream LLM responses token by token with a unified async interface that works across Claude, OpenAI, and Ollama without changing your code.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · LLM · Streaming
- **Summary:** Streaming chat completion with real-time output
- **Scenario:** Stream tokens from a chat completion as they arrive
- **`tech_tags` in manifest:** `LLM, Streaming` — example id **`streaming`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Real-time chat interface, live transcription display
## Technologies
LLM, Streaming
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/streaming`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/streaming
```
### Python
```bash
cd python
python main.py
```
---
# Structured Output (JSON Mode) Pattern
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/structured-output
Demonstrates extracting typed, validated structured data from LLM responses using JSON mode.
> Stop parsing free-form LLM text — get typed, validated JSON structs back every time, across every provider.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** JSON mode and structured output generation
- **Scenario:** Request and parse structured JSON responses from an LLM
- **`tech_tags` in manifest:** `LLM` — example id **`structured-output`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **JSON Mode Abstraction** | nxusKit handles provider-specific JSON mode implementations |
| **Type-Safe Responses** | Strong typing with serde (Rust) / json (Go) for reliability |
| **Provider-Agnostic Schemas** | Same schema works across OpenAI, Claude, and Ollama |
**Provider Compatibility**: Ollama (format parameter), OpenAI (response_format), Claude (via tool use)
## Pattern Overview
LLMs naturally produce unstructured text, but many applications need structured data. This pattern uses JSON mode to ensure valid JSON output, then parses and validates it into typed structures.
## Key Features
- JSON mode ensures valid JSON response
- Type-safe parsing into structs
- Validation of enumerated fields
- Helper functions for testing
## Real-World Application
Data extraction, form auto-fill, API response generation.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/structured-output`:
cd rust && cargo build
cd go && make build
```
## Log Classification Example
The example classifies log entries into structured categories:
```json
{
"severity": "error",
"category": "auth",
"summary": "Failed login attempt for admin user",
"actionable": true
}
```
### Valid Values
- **severity**: `info`, `warning`, `error`, `critical`
- **category**: `auth`, `network`, `system`, `application`
## Library usage
### Rust
```rust
use structured_output::{classify_log, LogClassification};
let classification = classify_log(&provider, "llama3", log_entry).await?;
println!("Severity: {}", classification.severity);
println!("Actionable: {}", classification.actionable);
```
### Go
```go
classification, err := ClassifyLog(ctx, provider, "llama3", logEntry)
fmt.Println("Severity:", classification.Severity)
fmt.Println("Actionable:", classification.Actionable)
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
```
## Prompt Engineering Tips
1. **Be explicit**: Specify the exact JSON format in the system prompt
2. **List valid values**: Enumerate allowed values for each field
3. **Provide examples**: Include example JSON in complex cases
4. **Validate output**: Always validate parsed JSON against your schema
## Production Considerations
1. **Retry on validation failure**: LLMs may occasionally produce invalid values
2. **Fallback handling**: Have a default category for edge cases
3. **Schema evolution**: Version your schemas for backward compatibility
4. **Rate limiting**: JSON mode may use more tokens due to formatting
---
# Timeout Config
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/timeout-config
Configure request timeouts and connection pool settings
> Take control of LLM request timing with per-phase timeout configuration that catches network failures fast without killing long-running streams.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Timeout configuration and connection management
- **Scenario:** Configure request timeouts and connection pool settings
- **`tech_tags` in manifest:** `LLM` — example id **`timeout-config`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, rust (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys and/or run **Ollama** locally when you execute the **Run** steps (interactive flags like `--help` / `--verbose` are documented below).
## Real-World Application
Latency-sensitive services, SLA-bound AI endpoints
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/timeout-config`:
cd rust && cargo build
cd go && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/timeout-config
```
---
# Streaming with Token Budget Pattern
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/token-budget
Demonstrates cost control by enforcing token limits during streaming responses.
> Stop paying for tokens you don't need — enforce real-time streaming budgets and cancel LLM requests the moment your limit is reached.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Starter** 🟢 · LLM
- **Summary:** Token budget management and cost estimation
- **Scenario:** Track and limit token usage across requests
- **`tech_tags` in manifest:** `LLM` — example id **`token-budget`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust, bash (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** CLI/Bash defaults to the `loopback` provider for credential-free smoke tests. Set cloud provider API keys or run **Ollama** locally when using live providers in the **Run** steps.
## Key nxusKit Features Demonstrated
| Feature | Description |
|---------|-------------|
| **Unified Streaming** | Same streaming interface across all providers (Stream in Rust, channels in Go) |
| **Stream Cancellation** | Graceful cancellation supported by all provider implementations |
| **Token Tracking** | Normalized token usage in final chunk regardless of provider |
**Provider Compatibility**: Any provider supporting streaming (Claude, OpenAI, Ollama)
## Pattern Overview
When streaming LLM responses, you may want to stop generation early to control costs or enforce response length limits. This pattern monitors token usage during streaming and cancels the request when a budget is reached.
## Key Features
- Real-time token estimation during streaming
- Graceful stream cancellation when budget exceeded
- Returns partial content and budget status
- Works with any streaming-capable provider
## Real-World Application
Usage metering, per-user quota enforcement.
## Technologies
LLM
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
| CLI/Bash | `bash/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/token-budget`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
cd bash && make build
```
## Token Estimation
Since exact token counts aren't available during streaming, we use a simple heuristic:
- ~4 characters per token (works well for English text)
- Adjust this ratio for other languages or specialized content
## Library usage
### Rust
```rust
use token_budget::stream_with_budget;
// Stream with a 100 token budget
let result = stream_with_budget(&provider, &request, 100).await?;
println!("Content: {}", result.content);
println!("Tokens used: {}", result.estimated_tokens);
if result.budget_reached {
println!("Budget limit reached - response truncated");
}
```
### Go
```go
// Stream with a 100 token budget
result, err := StreamWithBudget(ctx, provider, req, 100)
fmt.Println("Content:", result.Content)
fmt.Println("Tokens used:", result.EstimatedTokens)
if result.BudgetReached {
fmt.Println("Budget limit reached - response truncated")
}
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
go run .
```
### Python
```bash
cd python
python3 main.py
```
### CLI/Bash
```bash
cd bash
make run
TOKEN_BUDGET_MAX=40 make run ARGS="ollama"
```
## Interactive Modes
All examples support debugging flags:
```bash
# Verbose mode - show raw HTTP request/response data
cargo run -- --verbose # Rust
go run . --verbose # Go
make run ARGS="--verbose" # CLI/Bash
# Step mode - pause at each step with explanations
cargo run -- --step # Rust
go run . --step # Go
make run ARGS="--step" # CLI/Bash
# Combined mode
cargo run -- --verbose --step
```
Or use environment variables:
```bash
export NXUSKIT_VERBOSE=1
export NXUSKIT_STEP=1
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python smoke
cd python && python3 main.py --help
# CLI/Bash
cd bash && make test
```
## Production Considerations
1. **Calibrate token ratio**: Adjust the 4 chars/token estimate for your specific use case
2. **Buffer margin**: Set budget slightly below hard limits to account for estimation error
3. **User feedback**: Indicate when responses are truncated due to budget
4. **Combine with max_tokens**: Use both streaming budget and API max_tokens for defense in depth
---
# Vision
URL: https://docs.nxus.systems/v1.0.0/nxuskit/examples/patterns/vision
Send images alongside text prompts for multimodal analysis
> Send images alongside text to any LLM provider using one consistent API that handles encoding, formatting, and provider differences for you.
## Edition
**Community** — runs on the OSS / Community SDK edition.
## What this demonstrates
**Difficulty: Intermediate** 🟦 · LLM · Vision
- **Summary:** Vision and multimodal capabilities with images
- **Scenario:** Send images alongside text prompts for multimodal analysis
- **`tech_tags` in manifest:** `LLM, Vision` — example id **`vision`** in `conformance/examples_manifest.json`.
## Prerequisites
- **SDK:** Use an installed SDK tree (`NXUSKIT_SDK_DIR`, `NXUSKIT_LIB_PATH` as needed); `test-examples.sh` resolves Go/Rust/Python deps from that tree only — see [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples), `scripts/setup-sdk.sh`, and `scripts/test-examples.sh`.
- **Languages in this example:** go, python, rust, bash (paths under this directory; Python may live under a sibling `python/` or shared reference per **Language Implementations**).
- **Models:** Set cloud provider API keys for live Claude/OpenAI calls, or run metadata-only CLI/Bash mode with `VISION_RUN_LIVE=0`. Ollama vision models can be selected when the local provider path is available.
## Real-World Application
Image captioning, visual QA, document understanding
## Technologies
LLM, Vision
## Language Implementations
| Language | Path | Status |
|----------|------|--------|
| Rust | `rust/` | Available |
| Go | `go/` | Available |
| Python | `python/` | Available |
| CLI/Bash | `bash/` | Available |
## Build
Attach an **installed SDK** (`NXUSKIT_SDK_DIR`). See the repository [README.md](https://github.com/nxus-SYSTEMS/nxusKit-examples) and `scripts/test-examples.sh`.
```bash
# From `/examples/patterns/vision`:
cd rust && cargo build
cd go && make build
cd python && python3 main.py --help
cd bash && make build
```
## Run
### Rust
```bash
cd rust
cargo run
```
### Go
```bash
cd go
make build && bin/vision
```
### Python
```bash
cd python
python main.py
```
### CLI/Bash
```bash
cd bash
make run
VISION_RUN_LIVE=0 make run
make run ARGS="openai"
```
## Testing
```bash
# Rust
cd rust && cargo test
# Go
cd go && go test -v
# Python smoke
cd python && python3 main.py --help
# CLI/Bash
cd bash && make test
```
---
# Authentication
URL: https://docs.nxus.systems/v1.0.0/nxuskit/getting-started/authentication
## Overview
nxusKit supports multiple authentication methods depending on the provider.
This matrix shows which methods are available for each provider and how to
configure them.
## Provider Matrix
| Provider | Auth Required | API Key | OAuth | Env Variable | Dashboard |
|----------|:------------:|:-------:|:-----:|--------------|-----------|
| OpenAI / GPT | Yes | Yes | — | `OPENAI_API_KEY` | [platform.openai.com/api-keys](https://platform.openai.com/api-keys) |
| Anthropic / Claude | Yes | Yes | — | `ANTHROPIC_API_KEY` | [console.anthropic.com/settings/keys](https://console.anthropic.com/settings/keys) |
| xAI Grok | Yes | Yes | — | `XAI_API_KEY` | [console.x.ai](https://console.x.ai/) |
| Groq | Yes | Yes | — | `GROQ_API_KEY` | [console.groq.com/keys](https://console.groq.com/keys) |
| Mistral AI | Yes | Yes | — | `MISTRAL_API_KEY` | [console.mistral.ai/api-keys](https://console.mistral.ai/api-keys) |
| Fireworks AI | Yes | Yes | — | `FIREWORKS_API_KEY` | [fireworks.ai/account/api-keys](https://fireworks.ai/account/api-keys) |
| Together AI | Yes | Yes | — | `TOGETHER_API_KEY` | [api.together.ai/settings/api-keys](https://api.together.ai/settings/api-keys) |
| OpenRouter | Yes | Yes | — | `OPENROUTER_API_KEY` | [openrouter.ai/settings/keys](https://openrouter.ai/settings/keys) |
| Perplexity | Yes | Yes | — | `PERPLEXITY_API_KEY` | [perplexity.ai/settings/api](https://www.perplexity.ai/settings/api) |
| Ollama | No | — | — | `OLLAMA_HOST` | — |
| LM Studio | No | — | — | `LM_STUDIO_HOST` | — |
**Legend**: Yes = supported, — = not applicable/not yet available
## Authentication Methods
### API Key
The standard authentication method for cloud providers. Obtain a key from
the provider's dashboard, then configure via any of these methods:
**Environment variable** (recommended for development and CI/CD):
```bash
export OPENAI_API_KEY="sk-..."
```
**Credential store** (recommended for persistent local development):
```bash
nxuskit-cli provider set openai sk-...
```
This stores the key in the OS credential store (macOS Keychain, Windows
Credential Manager, or Linux secret-service). Falls back to a file-based
store with 0600 permissions if no system store is available.
**Explicit parameter** (for programmatic use):
```python
provider = Provider.create("openai", api_key="sk-...")
```
### OAuth (Infrastructure Ready)
OAuth authentication infrastructure is implemented in v0.9.1 but no current
providers require it. When a provider enables OAuth support, the flow will
be:
```bash
# Start OAuth login
nxuskit-cli provider login
# Check auth status
nxuskit-cli provider status
```
The OAuth flow uses:
- PKCE (SHA-256 code challenge) for security
- Localhost callback on an ephemeral port
- State/CSRF validation
- Automatic browser launch
### No Authentication
Local providers (Ollama, LM Studio) run on the local machine and do not
require authentication. The host env variable is optional and defaults to
`localhost` on the provider's default port.
## Credential Precedence
When multiple credential sources exist, the SDK uses this precedence order:
| Priority | Source | Example |
|----------|--------|---------|
| 1 (highest) | Explicit API parameter | `Provider.create("openai", api_key="sk-...")` |
| 2 | Environment variable | `OPENAI_API_KEY=sk-...` |
| 3 (lowest) | OS credential store | Via `nxuskit-cli provider set` |
## Checking Auth Status
View authentication status for all providers:
```bash
nxuskit-cli provider status
```
For a specific provider:
```bash
nxuskit-cli provider status openai
```
JSON output (for scripts):
```bash
nxuskit-cli provider status --json
```
Example output:
```
Provider Status Source Auth Methods
─────────────────────────────────────────────────────────────
openai Authenticated env api_key
claude Authenticated store api_key
xai Not authenticated — api_key
groq Not authenticated — api_key
ollama Not required — —
lm-studio Not required — —
```
## Managing Credentials
```bash
# Store a credential
nxuskit-cli provider set
# Remove a stored credential
nxuskit-cli provider remove
# View status
nxuskit-cli provider status [provider]
```
## Per-Language Configuration
### Rust
```rust
use nxuskit::{auth_status, auth_set_credential, auth_resolve};
// Check status
let status = auth_status("openai")?;
// Store credential
auth_set_credential("openai", "sk-...")?;
// Resolve credential (follows precedence chain)
let resolution = auth_resolve("openai", None)?;
```
### Go
```go
import "github.com/nxus-SYSTEMS/nxuskit-go"
// Check status
status, err := nxuskit.AuthStatus("openai")
// Store credential
err = nxuskit.AuthSetCredential("openai", "sk-...")
// Resolve credential
resolution, err := nxuskit.AuthResolve("openai", "")
```
### Python
```python
from nxuskit import auth_status, auth_set_credential, auth_resolve
# Check status
status = auth_status("openai")
# Store credential
auth_set_credential("openai", "sk-...")
# Resolve credential
resolution = auth_resolve("openai")
```
---
# First Call
URL: https://docs.nxus.systems/v1.0.0/nxuskit/getting-started/first-call
This guide assumes you have installed the SDK and configured at least one
provider credential. If you have not done that yet, start with
[Installation](/v1.0.0/nxuskit/getting-started/installation/) and
[Authentication](/v1.0.0/nxuskit/getting-started/authentication/).
## Fastest Path: CLI
Set a provider API key, then send a single chat request:
```bash
export OPENAI_API_KEY="sk-..."
nxuskit-cli chat \
--provider openai \
--model gpt-4o \
"Say hello from nxusKit in one sentence."
```
For structured shell workflows, use the Level 1 `call` command:
```bash
echo '{"provider":"openai","model":"gpt-4o","prompt":"Say hello from nxusKit."}' \
| nxuskit-cli call --input - --format json
```
## Rust
Use the Rust wrapper bundled with the SDK as a path dependency:
```toml
# Cargo.toml
[dependencies]
nxuskit = { path = "/absolute/path/to/nxuskit-sdk-{version}-{platform}/rust" }
```
```rust
use nxuskit::{ChatRequest, Message, NxuskitProvider, ProviderConfig};
fn main() -> Result<(), nxuskit::NxuskitError> {
let provider = NxuskitProvider::new(ProviderConfig {
provider_type: "openai".into(),
..Default::default()
})?;
let request = ChatRequest::new("gpt-4o")
.with_message(Message::user("Say hello from Rust."))
.with_max_tokens(100);
let response = provider.chat(request)?;
println!("{}", response.content);
Ok(())
}
```
## Go
Add the Go wrapper and alias the package as `nxuskit` in your import block:
```bash
go get github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go
```
```go
package main
import (
"context"
"fmt"
"os"
nxuskit "github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go"
)
func main() {
provider, err := nxuskit.NewOpenAIProvider(
nxuskit.WithAPIKey(os.Getenv("OPENAI_API_KEY")),
)
if err != nil {
panic(err)
}
req := nxuskit.ChatRequest{
Model: "gpt-4o",
Messages: []nxuskit.Message{
{Role: nxuskit.RoleUser, Content: "Say hello from Go."},
},
}
resp, err := provider.Chat(context.Background(), req)
if err != nil {
panic(err)
}
fmt.Println(resp.Content)
}
```
## Python
Install the Python wrapper, then create a provider and call it:
```bash
pip install nxuskit-py
```
```python
from nxuskit import Provider
provider = Provider.create("openai")
response = provider.chat(
model="gpt-4o",
messages=[{"role": "user", "content": "Say hello from Python."}],
max_tokens=100,
)
print(response.content)
```
## C
The SDK bundle includes `include/nxuskit.h` and platform libraries under
`lib/`. Compile against those files and set the provider API key in the
environment:
```bash
export OPENAI_API_KEY="sk-..."
cc -I "$NXUSKIT_SDK_DIR/include" \
-o basic_chat basic_chat.c \
-L "$NXUSKIT_SDK_DIR/lib" \
-lnxuskit \
-Wl,-rpath,"$NXUSKIT_SDK_DIR/lib"
```
Use the [C ABI Reference](/v1.0.0/nxuskit/reference/api-reference/) for function,
ownership, and error-handling details.
## Local Providers
Local providers do not require API keys:
```bash
# Ollama default
export OLLAMA_HOST="http://localhost:11434"
# LM Studio default
export LMSTUDIO_HOST="http://localhost:1234/v1"
```
Use [Local LLM Providers](/v1.0.0/nxuskit/reference/providers/local-llms/) for model
setup and provider-specific options.
## Next Steps
| Goal | Read |
|------|------|
| Configure credentials | [Authentication](/v1.0.0/nxuskit/getting-started/authentication/) |
| Browse runnable projects | [Examples](/v1.0.0/nxuskit/examples/) |
| Stream responses | [Streaming](/v1.0.0/nxuskit/guides/streaming/) |
| Choose a provider | [Provider Model](/v1.0.0/nxuskit/concepts/provider-model/) |
| Use CLI JSON contracts | [CLI Input Format Reference](/v1.0.0/nxuskit/reference/cli-reference/) |
| Integrate through native boundaries | [C ABI Reference](/v1.0.0/nxuskit/reference/api-reference/) |
---
# Installation
URL: https://docs.nxus.systems/v1.0.0/nxuskit/getting-started/installation
This guide walks you through downloading, installing, and using the nxuskit SDK
to call LLM providers from Rust, Go, Python, or the C ABI.
## Prerequisites
- [GitHub CLI](https://cli.github.com/) (`gh`) installed
- Optional: authenticate with `gh auth login` for CI reliability, higher API
limits, or entitlement-gated/private assets
## 1. Download and Install the SDK
The examples below download Community Edition from the public
`nxus-SYSTEMS/nxusKit` release. Current release asset names use `oss` for the
Community Edition archive segment. Pro users can replace `oss` with `pro` in the
asset patterns and extracted directory names after activating or receiving a Pro
entitlement.
### macOS (Apple Silicon)
```bash
# Download, extract, and remove macOS quarantine in one go
gh release download --repo nxus-SYSTEMS/nxusKit \
--pattern "nxuskit-sdk-*-oss-macos-arm64.tar.gz" \
--pattern "nxuskit-sdk-*-oss-macos-arm64.tar.gz.sha256"
shasum -a 256 -c nxuskit-sdk-*-oss-macos-arm64.tar.gz.sha256
tar xzf nxuskit-sdk-*-oss-macos-arm64.tar.gz
xattr -dr com.apple.quarantine nxuskit-sdk-*/
```
The `xattr` step removes the Gatekeeper quarantine flag that macOS applies to
downloaded files. Without it you'll get "can't be opened because Apple cannot
check it for malicious software" when loading the dylib.
### Linux (x86_64)
```bash
gh release download --repo nxus-SYSTEMS/nxusKit \
--pattern "nxuskit-sdk-*-oss-linux-x86_64.tar.gz" \
--pattern "nxuskit-sdk-*-oss-linux-x86_64.tar.gz.sha256"
sha256sum -c nxuskit-sdk-*-oss-linux-x86_64.tar.gz.sha256
tar xzf nxuskit-sdk-*-oss-linux-x86_64.tar.gz
```
### Windows (x86_64)
```powershell
gh release download --repo nxus-SYSTEMS/nxusKit `
--pattern "nxuskit-sdk-*-oss-windows-x86_64.zip" `
--pattern "nxuskit-sdk-*-oss-windows-x86_64.zip.sha256"
# Extract
Expand-Archive nxuskit-sdk-*-oss-windows-x86_64.zip -DestinationPath .
```
### Set SDK Path
After extracting, set the SDK path. **Use an absolute path** — relative paths
can fail because `cargo` and other tools may change the working directory during
builds.
```bash
# Get the absolute path to the extracted SDK directory
export NXUSKIT_SDK_DIR="$(cd nxuskit-sdk-*/ && pwd)"
echo "NXUSKIT_SDK_DIR=${NXUSKIT_SDK_DIR}"
```
To persist across sessions, add to your shell profile (`~/.bashrc`, `~/.zshrc`,
etc.):
```bash
export NXUSKIT_SDK_DIR="/absolute/path/to/nxuskit-sdk-1.0.0-oss-macos-arm64"
```
For CI systems, see [Download via PAT](#download-via-pat) below.
### CLI shell completions (optional)
The bundle includes `nxuskit-cli`. Generate shell completions with:
```bash
nxuskit-cli completions bash > /usr/local/etc/bash_completion.d/nxuskit-cli
nxuskit-cli completions zsh > ~/.zfunc/_nxuskit-cli # add ~/.zfunc to $fpath
nxuskit-cli completions fish > ~/.config/fish/completions/nxuskit-cli.fish
```
Supported shells for `completions` in v1.0.0: **bash**, **zsh**, **fish**.
PowerShell completion is **not generated** in v1.0.0 (the `completions` command
accepts only those three shell names). JSON schemas referenced by the CLI ship
under the bundle's `include/` (the C header) and `conformance/` (packet/pipeline
schemas) directories; see [SDK Bundle Contents](#2-sdk-bundle-contents) above.
## 2. SDK Bundle Contents
```
nxuskit-sdk-{version}-{edition}-{platform}/
├── include/
│ └── nxuskit.h # C header — all API declarations
├── lib/
│ ├── libnxuskit.so # Shared library (Linux)
│ │ libnxuskit.dylib # Shared library (macOS)
│ │ nxuskit.dll # Shared library (Windows)
│ ├── libnxuskit.a # Static library (Linux/macOS)
│ │ nxuskit.lib # Static library (Windows)
│ └── nxuskit.dll.lib # Import library (Windows only)
├── rust/ # nxuskit Rust SDK wrapper (use as path dependency)
├── docs/ # This documentation
└── examples/ # Working examples in C, Rust, Go, Python
```
## 3. First Example — C
Set your provider API key, then compile and run:
```bash
export OPENAI_API_KEY="sk-..." # or ANTHROPIC_API_KEY, etc.
cd nxuskit-sdk-*/examples/c
make basic_chat
./bin/basic_chat
```
See [nxusKit examples](/v1.0.0/nxuskit/examples/) for the source.
## 4. First Example — Go
```bash
export OPENAI_API_KEY="sk-..."
cd nxuskit-sdk-*/examples/go
go run basic_chat.go
```
See [nxusKit examples](/v1.0.0/nxuskit/examples/) for the source.
## 5. First Example — Rust
The SDK bundles `nxuskit`, a safe Rust wrapper. Add it as a path dependency
in your `Cargo.toml` using the **absolute path** to the SDK's `rust/` directory:
```toml
# Cargo.toml
[dependencies]
nxuskit = { path = "/Users/you/nxuskit-sdk-1.0.0-oss-macos-arm64/rust" }
```
Then set your environment and run:
```bash
# NXUSKIT_SDK_DIR tells the wrapper where to find libnxuskit at runtime.
# Must be an absolute path (relative paths are unreliable across tools).
export NXUSKIT_SDK_DIR="/Users/you/nxuskit-sdk-1.0.0-oss-macos-arm64"
export OPENAI_API_KEY="sk-..."
cargo run
```
```rust
use nxuskit::{ChatRequest, Message, NxuskitProvider, ProviderConfig};
fn main() -> Result<(), nxuskit::NxuskitError> {
let provider = NxuskitProvider::new(ProviderConfig {
provider_type: "openai".into(),
..Default::default()
})?;
let request = ChatRequest::new("gpt-4o")
.with_message(Message::user("Hello from Rust!"))
.with_max_tokens(100);
let response = provider.chat(request)?;
println!("{}", response.content);
Ok(())
}
```
**Path troubleshooting:** If you see `LibraryNotFound`, verify:
1. `NXUSKIT_SDK_DIR` is set and is an absolute path (check with `echo $NXUSKIT_SDK_DIR`)
2. The `lib/` subdirectory exists: `ls $NXUSKIT_SDK_DIR/lib/`
3. On macOS: quarantine was removed (see Step 1 above)
See [nxusKit examples](/v1.0.0/nxuskit/examples/) for a runnable project, and
[Rust SDK API documentation](/v1.0.0/nxuskit/reference/api/) for the full nxuskit API documentation.
## 6. First Example — Python
```bash
pip install nxuskit-py
export OPENAI_API_KEY="sk-..."
python examples/python/basic_chat.py
```
See [nxusKit examples](/v1.0.0/nxuskit/examples/) for the source.
## Core Concepts
### JSON-in / JSON-out
All data crosses the FFI boundary as JSON strings. You send a JSON config to
create a provider, send a JSON request for chat, and receive a JSON response.
### Provider Lifecycle
```
create_provider(config_json) → provider handle
↓
chat(provider, request_json) → response handle → response_json(response) → JSON
↓
free_response(response)
free_provider(provider)
```
### Streaming
```
chat_stream(provider, request_json, on_chunk, on_done, user_data) → stream handle
↓ (callbacks fire from background thread)
on_chunk(chunk_json, user_data) ← called per chunk
on_done(final_json, user_data) ← called once at end
↓
free_stream(stream)
```
### Thread Safety
- All `nxuskit_*` functions are thread-safe
- Provider handles can be shared across threads
- Error messages are thread-local (`nxuskit_last_error()`)
### Supported Providers
| Provider | Config `provider_type` | Required Env Var |
|----------|----------------------|------------------|
| OpenAI | `openai` | `OPENAI_API_KEY` |
| Anthropic Claude | `claude` | `ANTHROPIC_API_KEY` |
| Ollama | `ollama` | `OLLAMA_HOST` (optional) |
| LM Studio | `lmstudio` | — |
| xAI Grok | `xai` | `XAI_API_KEY` |
| Groq | `groq` | `GROQ_API_KEY` |
| Fireworks | `fireworks` | `FIREWORKS_API_KEY` |
| Together | `together` | `TOGETHER_API_KEY` |
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` |
| Perplexity | `perplexity` | `PERPLEXITY_API_KEY` |
| Mistral | `mistral` | `MISTRAL_API_KEY` |
| CLIPS | `clips` | — |
| MCP | `mcp` | — |
| Mock (testing) | `mock` | — |
| Loopback (testing) | `loopback` | — |
`xai` is xAI Grok and uses `XAI_API_KEY`. `groq` is Groq, Inc.'s provider and
uses `GROQ_API_KEY`. There is no `grok` provider alias.
### CLIPS Quick Start
CLIPS runs in-process (no API key needed). Create a provider with
`provider_type: "clips"` and `model` pointing to your rules directory. Send
facts as JSON in the user message:
```c
const char *input = "{\"facts\": [{\"template\": \"sensor\", \"values\": {\"name\": \"temp\", \"value\": 150}}]}";
// ... create provider, build request with input as user message, call nxuskit_chat()
```
The user message must conform to the `ClipsInput` schema — see the
[Rule Authoring Guide](/v1.0.0/nxuskit/guides/clips-rule-authoring/#clipsinput-json-reference) for the full
field reference. CLIPS also provides a session API for direct engine access; see
the [API Reference](/v1.0.0/nxuskit/reference/api-reference/#clips-session-api).
## Linking Reference
### GCC / Clang (dynamic)
```bash
cc -I sdk/include -o myapp myapp.c -L sdk/lib -lnxuskit -Wl,-rpath,sdk/lib
```
### GCC / Clang (static)
```bash
cc -I sdk/include -o myapp myapp.c sdk/lib/libnxuskit.a -lpthread -ldl -lm
```
### MSVC (dynamic — recommended)
```
cl /I sdk\include myapp.c /link sdk\lib\nxuskit.dll.lib
```
### MSVC (static)
```
cl /I sdk\include myapp.c /link sdk\lib\nxuskit.lib ucrt.lib userenv.lib ntdll.lib ws2_32.lib bcrypt.lib advapi32.lib
```
### CGo
```go
// #cgo CFLAGS: -I${SRCDIR}/sdk/include
// #cgo linux LDFLAGS: -L${SRCDIR}/sdk/lib -lnxuskit -Wl,-rpath,${SRCDIR}/sdk/lib
// #cgo darwin LDFLAGS: -L${SRCDIR}/sdk/lib -lnxuskit -Wl,-rpath,${SRCDIR}/sdk/lib
// #cgo windows LDFLAGS: -L${SRCDIR}/sdk/lib -lnxuskit
// #include "nxuskit.h"
import "C"
```
### Python (cffi)
```python
from cffi import FFI
ffi = FFI()
ffi.cdef(open("sdk/include/nxuskit.h").read())
lib = ffi.dlopen("sdk/lib/libnxuskit.so") # or .dylib / .dll
```
## Download via PAT
For CI systems that can't use `gh`, or that need authenticated GitHub API
access:
1. Create a fine-grained PAT at https://github.com/settings/personal-access-tokens
- **Repository access**: Select `nxus-SYSTEMS/nxusKit`
- **Permissions**: Contents → Read-only
2. Use the token:
```bash
export GH_TOKEN="github_pat_..."
# List available SDK releases
curl -H "Authorization: Bearer $GH_TOKEN" \
"https://api.github.com/repos/nxus-SYSTEMS/nxusKit/releases?per_page=5" \
| jq '.[].tag_name'
# Download a specific asset
curl -L -H "Authorization: Bearer $GH_TOKEN" \
-H "Accept: application/octet-stream" \
"https://api.github.com/repos/nxus-SYSTEMS/nxusKit/releases/assets/{ASSET_ID}" \
-o nxuskit-sdk.tar.gz
```
## Next Steps
- [API Reference](/v1.0.0/nxuskit/reference/api-reference/) — full C ABI documentation
- [Provider Reference](/v1.0.0/nxuskit/reference/providers/cloud-llms/) — provider-specific configuration
- [Rule Authoring Guide](/v1.0.0/nxuskit/guides/clips-rule-authoring/) — writing, testing, and deploying custom CLIPS rules
- [nxusKit examples](/v1.0.0/nxuskit/examples/) — working code for SDK languages and C ABI workflows
---
# CLIPS Rule Authoring Guide
URL: https://docs.nxus.systems/v1.0.0/nxuskit/guides/clips-rule-authoring
This guide explains how to write, test, and deploy custom CLIPS rules with the nxusKit SDK.
## CLIPS Rule Syntax
nxusKit uses CLIPS 6.4, a forward-chaining inference engine. Rules follow the pattern:
```clips
(defrule rule-name
"Documentation string"
;; LHS: conditions (pattern matching)
(template-name (slot-name ?variable))
(test (< ?variable 100))
=>
;; RHS: actions (assertions, side effects)
(assert (alert
(alert-type "threshold_exceeded")
(severity "warning")
(message (str-cat "Value " ?variable " is out of range"))
(recommendation "Check your input data")
(entity-id ?id)
(rule-name "rule-name")
(module-name "data-qc"))))
```
## Defining Templates
Templates define the fact schemas your rules operate on. Define them in shared template files loaded before any module rules:
```clips
;;; shared/000-core.clp — Core templates
(deftemplate input-data
"A single data record to evaluate"
(slot record-id (type INTEGER))
(slot value (type FLOAT))
(slot category (type STRING))
(slot confidence (type FLOAT) (range 0.0 1.0)))
(deftemplate threshold-config
"Configurable thresholds for QC checks"
(slot value-min (type FLOAT))
(slot value-max (type FLOAT))
(slot confidence-min (type FLOAT) (default 0.5)))
(deftemplate alert
"Output: a raised alert from rule inference"
(slot alert-type (type STRING))
(slot severity (type STRING)) ;; "critical", "high", "warning", "info"
(slot message (type STRING))
(slot recommendation (type STRING))
(slot entity-id (type INTEGER))
(slot rule-name (type STRING))
(slot module-name (type STRING)))
```
## Modules
CLIPS modules provide namespace isolation for rules. Each module groups related rules:
```clips
;;; In data-qc/bounds-check.clp
(defmodule data-qc (export ?ALL))
(defrule bounds-check
"Flag records outside configured bounds"
(threshold-config (value-min ?vmin) (value-max ?vmax))
(input-data (record-id ?rid) (value ?v&:(or (< ?v ?vmin) (> ?v ?vmax))))
=>
(assert (alert
(alert-type "out_of_bounds")
(severity "high")
(message (str-cat "Record " ?rid " value " ?v " outside [" ?vmin "-" ?vmax "]"))
(recommendation "Verify input data or adjust thresholds")
(entity-id ?rid)
(rule-name "bounds-check")
(module-name "data-qc"))))
```
## Directory Structure
Organize rules with shared templates loaded first, then per-module rule files:
```
rules/
shared/ # Shared templates (loaded first, alphabetically)
000-core.clp # input-data, threshold-config, alert
010-domain.clp # Additional domain-specific templates
data-qc/ # Data quality checks
bounds-check.clp
confidence-check.clp
classification/ # Classification rules
category-classifier.clp
custom/ # User-defined rules
my-custom-check.clp
```
## CLIPS Integration Paths
nxusKit provides two ways to use CLIPS:
- **Provider chat** — CLIPS as a standard chat provider. Send `ClipsInput` JSON
as the user message; receive `ClipsOutput` JSON in the response content.
Best for request/response workflows and cross-language portability.
- **Session API** — Direct engine access via `ClipsSession` (Rust, Go, Python)
or the C ABI (`nxuskit_clips_session_*`). Best for interactive, multi-step
rule authoring, debugging, and fine-grained fact manipulation.
This guide focuses on the **provider chat** path. For the session API, see the
[API Reference](/v1.0.0/nxuskit/reference/api-reference/#clips-session-api).
## ClipsInput JSON Reference
The user message JSON must conform to the `ClipsInput` schema. Unknown fields
are rejected (the engine uses strict deserialization).
```json
{
"facts": [
{"template": "sensor", "values": {"name": "temp-1", "value": 150}}
],
"templates": [
{"name": "alert", "slots": [{"name": "type", "type": "STRING"}, {"name": "severity", "type": "STRING"}]}
],
"rules": [
{"name": "high-temp", "source": "(defrule high-temp (sensor (value ?v&:(> ?v 100))) => (assert (alert (type \"over-threshold\") (severity \"high\"))))"}
],
"config": {
"max_rules": 1000,
"include_trace": true,
"derived_only_new": true
},
"focus": ["data-qc"],
"globals": {"*threshold*": 100}
}
```
All fields are optional. The minimal valid input is `{}` (empty object).
| Field | Type | Description |
|-------|------|-------------|
| `facts` | array of `{template, values}` | Facts to assert before running inference |
| `templates` | array of `{name, slots}` | Templates to create (if not in rule base) |
| `rules` | array of `{name, source}` or `{name, conditions, actions}` | Rules to create programmatically |
| `config` | object | Request-level overrides (see below) |
| `focus` | array of strings | Module focus stack (controls which rules fire) |
| `globals` | object | Global variable values to set |
| `command` | string | Special command: `"reset"`, `"clear"`, `"retract"` |
| `modules` | array of `{name, doc, imports}` | Modules to create |
| `policy_id` | string | Cache key for session reuse |
**Config fields:**
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `max_rules` | integer | -1 (unlimited) | Maximum rules to fire |
| `include_trace` | boolean | false | Include rule firing trace in output |
| `derived_only_new` | boolean | false | Only return newly derived facts |
| `output_templates` | array of strings | all | Only return facts matching these templates |
## Rule Loading
nxusKit's CLIPS provider loads rules through the `ClipsInput` configuration. Rules can be loaded from:
1. **Text strings** — CLIPS source passed directly via `rules_text`
2. **File paths** — `.clp` files loaded at runtime via `rules` array
3. **Binary images** — Pre-compiled `.bin` files via `binary_rules`
### Loading Order
1. Shared templates are loaded first (alphabetically by filename)
2. Module rules are loaded next, in the order specified by the `focus` configuration
3. User override rules are loaded last (taking precedence)
### Rust Example
```rust
use nxuskit::{AsyncProvider, ChatRequest, Message, NxuskitProvider, ProviderConfig};
let config = ProviderConfig {
provider_type: "clips".into(),
model: Some("/path/to/rules".into()),
..Default::default()
};
let provider = NxuskitProvider::new(config)?;
let request = ChatRequest::new("clips")
.with_message(Message::user(r#"{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 150.0}}]}"#))
.with_provider_options(serde_json::json!({
"focus": ["data-qc"],
"derived_only_new": true
}));
let response = provider.chat(request).await?;
println!("Alerts: {}", response.content);
```
### Go Example
```go
import "github.com/nxus-SYSTEMS/nxusKit/packages/nxuskit-go"
config := nxuskit-go.ProviderConfig{
ProviderType: "clips",
Model: strPtr("/path/to/rules"),
}
provider, _ := nxuskit-go.NewProvider(config)
request := nxuskit-go.NewChatRequest("clips").
AddMessage(nxuskit-go.UserMessage(`{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 150.0}}]}`))
request.ProviderOptions = map[string]interface{}{
"focus": []string{"data-qc"},
"derived_only_new": true,
}
response, _ := provider.Chat(ctx, request)
fmt.Println("Alerts:", response.Content)
```
### Python Example
```python
from nxuskit-py import create_provider, Message
provider = create_provider("clips", model="/path/to/rules")
response = provider.chat(
model="clips",
messages=[Message.user('{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 150.0}}]}')],
provider_options={
"focus": ["data-qc"],
"derived_only_new": True,
},
)
print("Alerts:", response.content)
```
## Writing Custom Rules
### 1. Create a Rule File
Place your `.clp` file in the appropriate module directory:
```
/path/to/my-rules/data-qc/my-custom-check.clp
```
### 2. Reference Shared Templates
Do NOT redefine templates. Use templates from the shared `shared/*.clp` files:
```clips
;;; my-custom-check.clp
;;; Custom confidence check for strict environments
(defrule strict-confidence-check
"Flag records with confidence below 0.8"
(input-data (record-id ?rid) (confidence ?c&:(< ?c 0.8)))
=>
(assert (alert
(alert-type "low_confidence")
(severity "warning")
(message (str-cat "Record " ?rid " confidence " ?c " below threshold 0.8"))
(recommendation "Review data source quality")
(entity-id ?rid)
(rule-name "strict-confidence-check")
(module-name "data-qc"))))
```
### 3. Use Configurable Thresholds
Reference the `threshold-config` fact instead of hard-coding values:
```clips
(defrule configurable-bounds-check
"Flag records outside configured bounds"
(threshold-config (value-min ?vmin) (value-max ?vmax))
(input-data (record-id ?rid) (value ?v&:(or (< ?v ?vmin) (> ?v ?vmax))))
=>
(assert (alert
(alert-type "value_out_of_bounds")
(severity "high")
(message (str-cat "Record " ?rid " value " ?v " outside [" ?vmin "-" ?vmax "]"))
(recommendation "Check data or adjust threshold configuration")
(entity-id ?rid)
(rule-name "configurable-bounds-check")
(module-name "data-qc"))))
```
### 4. Naming Conventions
- **File names**: `NNN-descriptive-name.clp` (NNN = numeric prefix for load order)
- **Rule names**: `kebab-case`, descriptive of what is being checked
- **Alert types**: `snake_case`, machine-readable identifiers
- **Module names**: `kebab-case`, matching the directory name
## Testing Custom Rules
### Rust
```rust
use nxuskit::{AsyncProvider, ChatRequest, Message, MockProvider};
// Unit test with MockProvider (no SDK binary required)
#[tokio::test]
async fn test_with_mock() {
let provider = MockProvider::new(r#"{"alerts": [{"type": "low_confidence"}]}"#);
let request = ChatRequest::new("clips")
.with_message(Message::user("test input"));
let response = provider.chat(request).await.unwrap();
assert!(response.content.contains("low_confidence"));
}
// Integration test with real CLIPS engine (requires SDK binary)
#[tokio::test]
#[ignore = "requires libnxuskit runtime"]
async fn test_with_clips_engine() {
use nxuskit::{NxuskitProvider, ProviderConfig};
let config = ProviderConfig {
provider_type: "clips".into(),
model: Some("tests/rules".into()),
..Default::default()
};
let provider = NxuskitProvider::new(config).unwrap();
let request = ChatRequest::new("clips")
.with_message(Message::user(r#"{"facts": [{"template": "input-data", "values": {"record-id": 1, "value": 999.0}}]}"#));
let response = provider.chat(request).await.unwrap();
assert!(response.content.contains("out_of_bounds"));
}
```
### Go
```go
func TestRulesWithMock(t *testing.T) {
provider := nxuskit-go.NewMockProvider(
nxuskit-go.WithResponse(`{"alerts": [{"type": "low_confidence"}]}`),
)
req := nxuskit-go.NewChatRequest("clips").
AddMessage(nxuskit-go.UserMessage("test input"))
resp, err := provider.Chat(context.Background(), req)
require.NoError(t, err)
assert.Contains(t, resp.Content, "low_confidence")
}
```
### Python
```python
import pytest
from nxuskit-py import create_provider, Message
def test_rules_with_mock():
provider = create_provider("mock", responses=["low_confidence alert fired"])
response = provider.chat(
model="clips",
messages=[Message.user("test input")],
)
assert "low_confidence" in response.content
```
## Debugging Rules
### Enable Tracing
Set the `RUST_LOG` environment variable when using the Rust SDK:
```bash
RUST_LOG=nxuskit=debug cargo test -- --nocapture
```
This shows:
- Which rule files are loaded
- Module loading order and file counts
- Warnings for syntax errors
### Inspect CLIPS Facts
Access the CLIPS session API directly (Rust SDK):
```rust
use nxuskit::ClipsSession;
let session = ClipsSession::create()?;
session.load_string("(deftemplate input-data (slot record-id (type INTEGER)) (slot value (type FLOAT)))")?;
session.load_string("(deftemplate alert (slot alert-type (type STRING)) (slot severity (type STRING)))")?;
session.load_string(r#"(defrule check (input-data (record-id ?rid) (value ?v&:(> ?v 100.0))) =>
(assert (alert (alert-type "over-threshold") (severity "high"))))"#)?;
session.reset()?;
session.assert_string(r#"(input-data (record-id 1) (value 150.0))"#)?;
session.run(-1)?;
// List facts by template
let facts_json = session.facts_by_template("alert")?;
println!("Alert facts: {}", facts_json);
// Drop destroys the session automatically
```
### Step Limit Debugging
If inference hits the step limit, check for rule cycles. Common causes:
- Rules that assert facts matching their own LHS (infinite loop)
- Missing `not` patterns allowing rules to fire repeatedly
- Very large fact sets with cross-product patterns
Increase the step limit if needed:
```rust
session.run(500000)?; // Pass -1 to run until agenda exhausted
```
## Best Practices
1. **Keep rules simple** — One check per rule. Complex logic should be split across multiple rules.
2. **Use configurable thresholds** — Reference threshold facts instead of hard-coding values.
3. **Document every rule** — Use the CLIPS documentation string for a brief description.
4. **Test in isolation** — Load only shared templates and the single rule file under test.
5. **Use meaningful names** — Rule names should describe what is checked, not how.
6. **Set appropriate salience** — Use `(declare (salience N))` to control firing order when needed.
---
# CLIPS Excluded Capabilities & Workarounds
URL: https://docs.nxus.systems/v1.0.0/nxuskit/guides/clips-workarounds
Four CLIPS capabilities are intentionally excluded from the Session API.
This document explains why and provides working alternatives.
## 1. User-Defined Functions (UDFs)
**What it is:** CLIPS allows registering C functions callable from rule RHS actions
(`(my-custom-fn ?arg)`).
**Why excluded:** UDFs require raw C function pointers — exposing this through the
session-based FFI would bypass safety guarantees and create ABI fragility.
**Workaround:** Use `nxuskit_clips_eval()` to call built-in CLIPS functions, or
encode custom logic as rules:
```c
// Instead of a UDF that computes weighted score:
// (my-weighted-score ?base ?multiplier)
// Use a rule that computes and asserts the result:
nxuskit_clips_session_load_string(s,
"(defrule compute-weighted-score"
" (input (base ?b) (multiplier ?m))"
" =>"
" (assert (result (score (* ?b ?m)))))");
```
For complex custom functions, pre-compute values in your host language and assert
them as facts:
```c
// Compute in C, assert as fact
double score = my_complex_calculation(base, mult);
char buf[256];
snprintf(buf, sizeof(buf), "(result (score %f))", score);
nxuskit_clips_fact_assert_string(s, buf);
```
## 2. I/O Routers
**What it is:** CLIPS uses I/O routers to redirect `printout`, `read`, and other
I/O operations to custom handlers.
**Why excluded:** Router registration requires persistent C callbacks with
environment-specific state — incompatible with the session handle model.
**Workaround:** Use dribble logging to capture output:
```c
// Capture all CLIPS output to a file
nxuskit_clips_dribble_on(s, "/tmp/clips-output.log");
nxuskit_clips_session_run(s, -1);
nxuskit_clips_dribble_off(s);
// Read /tmp/clips-output.log for captured output
```
For structured output, use facts instead of `printout`:
```c
// Instead of: (printout t "Result: " ?value crlf)
// Use: (assert (output (message (str-cat "Result: " ?value))))
// Then query output facts:
char *outputs = nxuskit_clips_facts_by_template(s, "output");
// Parse JSON array of output facts
nxuskit_free_string(outputs);
```
## 3. Periodic Functions
**What it is:** CLIPS supports registering functions that execute between rule
firings (e.g., for progress callbacks or heartbeat checks).
**Why excluded:** Requires raw function pointers called from within the CLIPS
engine loop — cannot be safely exposed through FFI session handles.
**Workaround:** Use batch `run()` with a step limit and poll between batches:
```c
// Instead of a periodic callback, run in controlled batches
int64_t total_fired = 0;
while (true) {
int64_t fired = nxuskit_clips_session_run(s, 100); // 100 rules per batch
if (fired <= 0) break;
total_fired += fired;
// Your "periodic" logic here:
printf("Progress: %lld rules fired\n", total_fired);
// Check if we should halt
if (should_stop()) {
nxuskit_clips_session_halt(s);
break;
}
}
```
For thread-safe cancellation from another thread:
```c
// Thread 1: run inference
int64_t fired = nxuskit_clips_session_run(s, -1);
// Thread 2: signal halt after timeout
sleep(5);
nxuskit_clips_session_halt(s); // Thread-safe
```
## 4. External Addresses
**What it is:** CLIPS external addresses allow storing opaque C pointers as slot
values, enabling rules to reference host-language objects.
**Why excluded:** External address values are raw `void*` pointers — they cannot
be safely serialized through JSON and would create dangling pointer risks across
session boundaries.
**Workaround:** Use string or integer keys as indirect references:
```c
// Instead of storing a pointer to a connection object:
// (connection (handle ))
// Store an integer key and maintain a lookup table in your host code:
nxuskit_clips_session_load_string(s,
"(deftemplate connection (slot handle (type INTEGER)) (slot status (type SYMBOL)))");
// In C: maintain a mapping
int handle_id = register_connection(conn); // Your lookup table
char buf[128];
snprintf(buf, sizeof(buf), "(connection (handle %d) (status active))", handle_id);
nxuskit_clips_fact_assert_string(s, buf);
// When a rule fires referencing the handle, look up the real object:
// (defrule process-connection
// (connection (handle ?h) (status active))
// =>
// (assert (connection-result (handle ?h) (processed TRUE))))
```
## Summary
| Capability | Status | Workaround Pattern |
|------------|--------|-------------------|
| User-Defined Functions | Excluded | Encode as rules or pre-compute in host language |
| I/O Routers | Excluded | Dribble logging or output facts |
| Periodic Functions | Excluded | Batch `run()` with step limit + polling |
| External Addresses | Excluded | Integer/string keys with host-side lookup table |
All four exclusions are by design — they involve raw C pointers or callbacks that
cannot be safely exposed through the session-handle FFI boundary. The workarounds
provide equivalent functionality using the session API's safe data exchange patterns.
---
# Streaming
URL: https://docs.nxus.systems/v1.0.0/nxuskit/guides/streaming
## Overview
Streaming lets your application receive partial model output as it is produced.
Use it for chat UIs, long-running responses, progress reporting, and command-line
tools that should show output immediately instead of waiting for the final
message.
Most LLM providers support token-by-token streaming. Deterministic providers
such as CLIPS and Z3 may emit a single result chunk or a small number of status
updates, depending on the operation.
## When to Use Streaming
| Use streaming when | Use a regular call when |
|--------------------|-------------------------|
| Users should see output immediately | You need one complete JSON response |
| Responses may be long | Responses are small and predictable |
| You want progress or partial results | You need simpler error handling |
| You are building CLI or chat interfaces | You are running batch jobs |
## Rust
```rust
use futures::StreamExt;
use nxuskit::{completion_stream, NxuskitError};
#[tokio::main]
async fn main() -> Result<(), NxuskitError> {
let mut stream = completion_stream("gpt-4o", "Count from one to five.").await?;
while let Some(chunk) = stream.next().await {
print!("{}", chunk?);
}
Ok(())
}
```
## CLI
```bash
nxuskit-cli chat \
--provider openai \
--model gpt-4o \
--stream \
"Explain streaming responses in one paragraph."
```
For machine-readable output, use the Level 1 `call` command with JSONL:
```bash
echo '{"provider":"openai","model":"gpt-4o","prompt":"Count to five."}' \
| nxuskit-cli call --input - --format jsonl --stream
```
## Stream Events
Streaming APIs generally emit:
- **Content chunks** — Partial text or structured deltas.
- **Metadata** — Provider, model, token usage, timing, or trace information when available.
- **Completion** — Final status, finish reason, or terminal error.
The exact fields vary by provider. Code that handles multiple providers should
append content chunks as they arrive and treat metadata as optional.
## Error Handling
Handle errors in the stream loop, not only at stream creation time. A provider
can accept a request and still fail later because of rate limits, network
interruptions, token limits, or a cancelled operation.
## Related Reference
- [Provider Model](/v1.0.0/nxuskit/concepts/provider-model/)
- [Cloud LLM Providers](/v1.0.0/nxuskit/reference/providers/cloud-llms/)
- [Local LLM Providers](/v1.0.0/nxuskit/reference/providers/local-llms/)
- [CLI Input Format Reference](/v1.0.0/nxuskit/reference/cli-reference/)
---
# CLIPS Session Migration
URL: https://docs.nxus.systems/v1.0.0/nxuskit/migration/clips-session-migration
This guide covers migrating from the legacy `ClipsEnvironment` / `nxuskit_clips_env_*` API
to the new `ClipsSession` / `nxuskit_clips_session_*` API introduced in SDK v0.9.1.
## What Changed
| Aspect | Old API | New API |
|--------|---------|---------|
| Handle type | Opaque pointer (`NxuskitClipsEnv*`) | `uint64_t` session handle |
| Safety | Manual pointer management | Generational index (use-after-free protection) |
| Fact builder | Separate `NxuskitClipsFactBuilder` type | `nxuskit_clips_fact_assert_structured()` (JSON slots) |
| Fact iteration | Pointer chain (`first_fact` → `fact_next`) | `nxuskit_clips_facts_by_template()` (JSON array) |
| Template lookup | `nxuskit_clips_find_template()` → pointer | `nxuskit_clips_template_exists()` / `template_list()` |
| Thread safety | Not guaranteed | Session registry with RwLock; `session_halt()` for cross-thread signalling |
## Who Needs to Migrate
- **Chat provider users** (`NxuskitProvider` / `ChatRequest`): **No changes needed.** The Chat provider interface is unchanged.
- **Direct C ABI users** (`nxuskit_clips_env_*` functions): **Must migrate.** Old functions are removed.
- **Rust SDK users** (`nxuskit::ClipsEnvironment`): **Must migrate** to `nxuskit::ClipsSession`.
## C ABI Migration
### Session Lifecycle
```c
// OLD
struct NxuskitClipsEnv *env = nxuskit_clips_env_create();
nxuskit_clips_env_load_file(env, "rules.clp");
nxuskit_clips_env_reset(env);
nxuskit_clips_env_run(env, -1);
nxuskit_clips_env_destroy(env);
// NEW
uint64_t s = nxuskit_clips_session_create();
nxuskit_clips_session_load_file(s, "rules.clp");
nxuskit_clips_session_reset(s);
nxuskit_clips_session_run(s, -1);
nxuskit_clips_session_destroy(s);
```
### Asserting Facts
```c
// OLD — string-based
nxuskit_clips_env_assert_string(env, "(sensor (name \"t1\") (value 42))");
// OLD — fact builder
struct NxuskitClipsFactBuilder *fb = nxuskit_clips_fb_create(env, "sensor");
nxuskit_clips_fb_put_string(fb, "name", "t1");
nxuskit_clips_fb_put_integer(fb, "value", 42);
nxuskit_clips_fb_assert(fb);
// NEW — string-based (unchanged pattern)
nxuskit_clips_fact_assert_string(s, "(sensor (name \"t1\") (value 42))");
// NEW — structured (replaces fact builder)
nxuskit_clips_fact_assert_structured(s, "sensor",
"{\"name\":\"t1\",\"value\":42}");
```
### Querying Facts
```c
// OLD — pointer iteration
struct NxuskitClipsTemplate *tmpl = nxuskit_clips_find_template(env, "sensor");
struct NxuskitClipsFact *fact = nxuskit_clips_template_first_fact(tmpl);
while (fact) {
char *slot = nxuskit_clips_fact_get_slot(fact, "value");
// use slot...
nxuskit_free_string(slot);
struct NxuskitClipsFact *next = nxuskit_clips_fact_next(fact);
nxuskit_clips_fact_destroy(fact);
fact = next;
}
nxuskit_clips_template_destroy(tmpl);
// NEW — JSON array
char *facts = nxuskit_clips_facts_by_template(s, "sensor");
// facts is a JSON array of fact objects — parse with your JSON library
nxuskit_free_string(facts);
```
## Rust SDK Migration
### Basic Usage
```rust
// OLD
use nxuskit::ClipsEnvironment;
let env = ClipsEnvironment::new()?;
env.load_from_string("(deftemplate sensor (slot name) (slot value))")?;
env.reset()?;
env.assert_string("(sensor (name \"t1\") (value 42))")?;
env.run(None)?;
if let Some(tmpl) = env.find_template("sensor")? {
for fact in tmpl.facts().flatten() {
println!("{:?}", fact.get_slot("value")?);
}
}
// NEW
use nxuskit::ClipsSession;
let session = ClipsSession::create()?;
session.load_string("(deftemplate sensor (slot name) (slot value))")?;
session.reset()?;
session.assert_string("(sensor (name \"t1\") (value 42))")?;
session.run(-1)?;
let facts = session.facts_by_template("sensor")?;
println!("{}", facts);
// session is destroyed on drop
```
### FBP (Fact-Based Processing) Pattern
```rust
use nxuskit::ClipsSession;
// Create a persistent session for iterative processing
let session = ClipsSession::create()?;
session.load_file("rules/shared/000-core.clp")?;
session.load_file("rules/data-qc/bounds-check.clp")?;
// Cycle 1: Load initial data
session.reset()?;
session.assert_string(r#"(input-data (record-id 1) (value 150.0))"#)?;
session.run(-1)?;
let alerts = session.facts_by_template("alert")?;
// Cycle 2: New data, same rules (facts persist unless reset)
session.assert_string(r#"(input-data (record-id 2) (value 200.0))"#)?;
session.run(-1)?;
let more_alerts = session.facts_by_template("alert")?;
```
### LKS (Load-知識-Solve) Pattern
```rust
use nxuskit::ClipsSession;
// Load once, solve many times
let session = ClipsSession::create()?;
session.load_file("expert-system.clp")?;
for case in cases {
session.reset()?; // Clear facts, keep rules
session.assert_string(&format!("(case-data (id {}) (symptoms {}))",
case.id, case.symptoms))?;
session.run(-1)?;
let diagnosis = session.facts_by_template("diagnosis")?;
println!("Case {}: {}", case.id, diagnosis);
}
```
## New Capabilities (No Old Equivalent)
These features are only available in the Session API:
| Feature | Function | Description |
|---------|----------|-------------|
| Session halt | `session_halt()` | Thread-safe inference cancellation |
| Session cache | `session_preload()` / `get_cached()` | Named session caching |
| Fact retraction | `fact_retract()` / `fact_retract_by_template()` | Targeted fact removal |
| Rule debugging | `rule_breakpoint_set()` / `rule_times_fired()` | Rule-level debugging |
| Global variables | `global_get_value()` / `global_set_value()` | Defglobal access |
| Watch/dribble | `watch()` / `dribble_on()` | Tracing and logging |
| Strategy control | `strategy_get()` / `strategy_set()` | Conflict resolution |
| Module focus | `focus_push()` / `focus_pop()` | Module execution control |
| Structured assert | `fact_assert_structured()` | JSON-based fact assertion |
| Binary save/load | `session_save_binary()` / `load_binary()` | Fast environment serialization |
---
# Logprobs Migration
URL: https://docs.nxus.systems/v1.0.0/nxuskit/migration/logprobs-migration
**Audience:** SDK consumers that previously needed to request token log
probabilities through `provider_options` because the SDK had no first-class
field.
## What Changed in v0.9.3
The Rust wrapper, Python SDK, Go SDK, and the C ABI now expose first-class
unary chat logprobs:
- **Request side:** `ChatRequest.logprobs: Option` and
`ChatRequest.top_logprobs: Option` (Rust); equivalents in Python and
the C ABI envelope. Use the Rust builders `with_logprobs(true)` /
`with_top_logprobs(n)`, the Python `ChatRequest(..., logprobs=True,
top_logprobs=5)`, or set the JSON fields directly when calling the C ABI.
- **Response side:** `ChatResponse.logprobs: Option` with
typed `TokenLogprob` (selected token + bytes) and `TopLogprob` (each
alternative + bytes). The wire path is `logprobs.content[]` (matches
OpenAI; pinned by
`packages/nxuskit-engine/crates/nxuskit-core/tests/logprobs_abi_passthrough_test.rs`).
- **Engine behavior:** `parameter_adapter.rs::adapt_logprobs` performs
warn-and-drop when a provider's `ProviderCapabilities.supports_logprobs`
is `false`, emits a structured `Info` warning with
`parameter == "logprobs"`, and drops both first-class fields. It does
**not** tunnel logprobs through `provider_options`.
## Migration For Existing Callers
If you previously stuffed logprobs into `provider_options` to work around
the missing first-class field:
```rust
// OLD (pre-v0.9.3) — pattern still parses but never reaches the provider
let req = ChatRequest::new("gpt-5.4")
.with_message(Message::user("..."))
.with_provider_options(serde_json::json!({
"logprobs": true,
"top_logprobs": 5,
}));
```
Switch to the first-class fields:
```rust
// NEW (v0.9.3+) — first-class, capability-gated, surfaces typed response
let req = ChatRequest::new("gpt-5.4")
.with_message(Message::user("..."))
.with_logprobs(true)
.with_top_logprobs(5);
```
Python:
```python
from nxuskit import ChatRequest
req = ChatRequest(
model="gpt-5.4",
messages=[{"role": "user", "content": "..."}],
logprobs=True,
top_logprobs=5,
)
```
C ABI / direct JSON:
```json
{
"model": "gpt-5.4",
"messages": [{"role": "user", "content": "..."}],
"logprobs": true,
"top_logprobs": 5
}
```
## Why The Switch Matters
- **Capability gating:** the engine only forwards logprobs to providers
whose capability map enables it. The legacy `provider_options` path
bypasses this check and silently dies on unsupported providers.
- **Typed responses:** `ChatResponse.logprobs` returns a typed
`LogprobsData` rather than raw provider JSON. Selected token and
alternative tokens are addressable as fields, including UTF-8 bytes
when present.
- **Cross-language parity:** Rust, Python, Go, and the C ABI all use the
same wire shape (`logprobs.content[]` with `token`, `logprob`, `bytes`,
`top_logprobs`). Switching once works everywhere.
- **No silent drops:** unsupported providers now emit a structured
warning instead of swallowing the request, so callers can detect and
fall back.
## v0.9.4 update
- **Streaming logprobs shipped in v0.9.4** (sprint S1 / branch 098).
`StreamChunk` now carries `logprobs: Option` (Rust),
`Logprobs *StreamLogprobsDelta` (Go), `logprobs: Optional[StreamLogprobsDelta]`
(Python) - additive, defaults to `None`/`nil` for non-supporting providers.
`ProviderCapabilities.supports_streaming_logprobs` gates it (with
`supports_streaming_logprobs => supports_logprobs` enforced). OpenAI is the
only provider with `supports_streaming_logprobs = true` per fixture evidence;
all others are `false` per the evidence-first rule. See the v0.9.4 CHANGELOG
entry for the cross-language parity harness.
- **`CapabilityManifest` v2** - a public preview subset for provider/model
capability discovery was introduced in v0.9.4 (sprint S2/S3 / branch 099);
the full internal manifest is unchanged. The publication decision is recorded
in the 099 artifacts.
---
# Upgrade Path
URL: https://docs.nxus.systems/v1.0.0/nxuskit/migration/upgrade-path
## Overview
When a Pro feature is called without valid authorization, the SDK returns
a specific error type with an actionable message. This document maps every
error to its cause and resolution.
## Error Reference
### `FeatureUnavailable`
**Message**: varies by context (see sub-cases below)
This is the umbrella error returned when a Pro feature cannot be accessed.
The message text tells you exactly what to do.
---
### `LicenseRequired`
**Returned when**: A Pro feature is called but no valid license token was
found in the resolution chain (env var → file → API parameter).
**Message**:
```
License installation required.
```
**Resolution**:
1. Authenticate: `nxuskit-cli license login`
2. Activate your license: `nxuskit-cli license activate --key `
3. For CI/CD: set `NXUSKIT_LICENSE_TOKEN` environment variable with your
deployment token
4. To start a trial: `nxuskit-cli license login` then `nxuskit-cli license activate --trial`
---
### `LicenseExpired`
**Returned when**: The developer token's subscription period has ended.
**Message**:
```
License installation required.
```
**Resolution**:
1. Renew your subscription at your account dashboard
2. After renewal, run `nxuskit-cli license activate --key ` to get a
fresh token
3. Community features continue working during the gap
---
### `EditionInsufficient`
**Returned when**: You have a valid token but the binary is the Community
edition, which does not include Pro code.
**Message**:
```
This feature requires Pro edition.
```
**Resolution**:
1. Download the Pro edition binary (requires authenticated access)
2. Replace your Community binary with the Pro binary
3. Your existing license token will be recognized automatically
---
### `VersionCeilingExceeded`
**Returned when**: A deployment token's version ceiling is lower than the
running SDK version.
**Message**:
```
Deployment token covers up to v{ceiling}. Update your deployment token for v{current}+ support.
```
**Resolution**:
1. If you have an active support subscription, request an updated
deployment token from your account dashboard
2. Alternatively, pin the SDK version to stay within the token ceiling
3. Contact **support@nxus.systems** if you need help
---
### `TrialSuspended`
**Returned when**: A trial token was issued but not activated within
the 7-day grace period.
**Message**:
```
License installation required.
```
**Resolution**:
1. Run `nxuskit-cli license login` to authenticate
2. Run `nxuskit-cli license activate --trial` to resume the trial
3. This extends Pro access for the remainder of the 30-day trial period
---
### `TrialExpired`
**Returned when**: The 30-day trial period has ended.
**Message**:
```
License installation required.
```
**Resolution**:
1. Purchase a Pro license
2. Community features continue working without interruption
3. All Pro features will be restored immediately after activation
---
### `TrialIssuanceFailed`
**Returned when**: The SDK attempted to issue a trial token but could
not complete the operation.
**Message**:
```
License installation required.
```
**Resolution**:
1. Run `nxuskit-cli license login` to authenticate first
2. Then run `nxuskit-cli license activate --trial`
3. Community features remain available regardless
---
## Error Handling by Language
### Rust
```rust
use nxuskit::{FeatureUnavailableError, LicenseExpiredError, LicenseRequiredError};
match nxuskit::zen_evaluate(&table, &input) {
Ok(result) => { /* success */ }
Err(e) if e.is::() => {
eprintln!("{}", e); // "License installation required."
}
Err(e) if e.is::() => {
eprintln!("{}", e); // "License installation required."
}
Err(e) => { /* other errors */ }
}
```
### Python
```python
from nxuskit import zen_evaluate
from nxuskit import LicenseRequiredError, LicenseExpiredError, FeatureUnavailableError
try:
result = zen_evaluate(table_path, input_data)
except LicenseRequiredError as e:
print(e.message) # "License installation required."
except LicenseExpiredError as e:
print(e.message) # "License installation required."
except FeatureUnavailableError as e:
print(e.message) # generic feature gate
```
### Go
```go
import "github.com/nxus-SYSTEMS/nxuskit-go"
result, err := nxuskit.ZenEvaluate(table, input)
if err != nil {
switch {
case errors.Is(err, nxuskit.ErrLicenseRequired):
fmt.Println(err) // "License installation required."
case errors.Is(err, nxuskit.ErrLicenseExpired):
fmt.Println(err) // "License installation required."
default:
fmt.Println(err)
}
}
```
## Quick Decision Tree
```
Pro feature called
│
├─ No token found? → "License installation required."
├─ Token expired? → "License installation required."
├─ Community binary? → EditionInsufficient → download Pro binary
├─ Version ceiling hit? → VersionCeilingExceeded → update deployment token
├─ Trial not activated? → "License installation required."
├─ Trial past 30 days? → "License installation required."
├─ Can't reach service? → "License installation required."
└─ Valid token + Pro binary? → Success
```
---
# API Reference
URL: https://docs.nxus.systems/v1.0.0/nxuskit/reference/api
## Overview
nxusKit APIs are organized around a small set of shared contracts:
- **Provider configuration** creates a backend connection.
- **Chat requests** carry model names, messages, and provider options.
- **Chat responses** return content, metadata, usage, and errors.
- **Streaming calls** emit incremental chunks for interactive workflows.
- **Specialized providers** such as CLIPS and Z3 use structured JSON payloads
inside the same request/response pattern.
Use this page as the entry point for API-level reference material.
## Core References
| Reference | Use for |
|-----------|---------|
| [C ABI Reference](/v1.0.0/nxuskit/reference/api-reference/) | C functions, ownership rules, FFI handles, CLIPS session calls, and memory management. |
| [CLI Input Format Reference](/v1.0.0/nxuskit/reference/cli-reference/) | Structured JSON/YAML/JSONL input contracts for `nxuskit-cli`. |
| [Cloud LLM Providers](/v1.0.0/nxuskit/reference/providers/cloud-llms/) | Provider configuration for hosted LLM APIs. |
| [Local LLM Providers](/v1.0.0/nxuskit/reference/providers/local-llms/) | Ollama, LM Studio, and in-process local model configuration. |
| [Expert System & Utility Providers](/v1.0.0/nxuskit/reference/providers/expert-systems/) | CLIPS, MCP, Mock, and Loopback configuration. |
| [Z3 Constraint Satisfaction Provider](/v1.0.0/nxuskit/reference/providers/z3-solver/) | Z3 input, output, optimization, and streaming contracts. |
## Shared Chat Shape
The language wrappers expose native types, but the shared request shape is:
```json
{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "You are concise."},
{"role": "user", "content": "Summarize nxusKit."}
],
"max_tokens": 512,
"temperature": 0.2,
"stream": false
}
```
Responses include provider content plus optional metadata:
```json
{
"content": "nxusKit is a multi-language SDK...",
"model": "gpt-4o",
"finish_reason": "stop",
"usage": {
"input_tokens": 24,
"output_tokens": 12
}
}
```
Provider-specific options belong in the configuration object or provider options
map. See the provider reference pages before relying on a field across multiple
backends.
## Memory and Ownership
When calling through the C ABI, every returned provider handle, response handle,
stream handle, and allocated string has an explicit free function. Use the
[ownership summary](/v1.0.0/nxuskit/reference/api-reference/#ownership-summary) before
integrating from C, C++, Go FFI, Python FFI, or another native boundary.
---
# C ABI Reference
URL: https://docs.nxus.systems/v1.0.0/nxuskit/reference/api-reference
All functions are declared in `nxuskit.h`. The ABI uses opaque handles and JSON
strings for all data exchange. Every function is thread-safe unless noted.
## Version
### `nxuskit_version`
```c
const char *nxuskit_version(void);
```
Returns the library version string (e.g., `"1.0.0"`). The returned pointer is
static and valid for the process lifetime. Never returns NULL.
## Provider Lifecycle
### `nxuskit_create_provider`
```c
struct NxuskitProvider *nxuskit_create_provider(const char *config_json);
```
Creates a provider from a JSON configuration string.
**Parameters:**
- `config_json` — JSON string with at minimum `{"provider_type": "..."}`.
See [Provider Reference](../providers/cloud-llms/) for provider-specific fields.
**Returns:** Opaque provider handle, or NULL on failure. On failure, call
`nxuskit_last_error()` for the error message.
**Ownership:** Caller owns the returned handle. Must call `nxuskit_free_provider()`
when done.
**Config JSON fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `provider_type` | string | Yes | Provider identifier (see providers list) |
| `api_key` | string | Varies | API key for cloud providers |
| `model` | string | No | Default model name |
| `base_url` | string | No | Custom API endpoint |
| `timeout_ms` | integer | No | Request timeout in milliseconds |
**Example:**
```c
const char *config = "{\"provider_type\":\"openai\",\"api_key\":\"sk-...\"}";
struct NxuskitProvider *p = nxuskit_create_provider(config);
if (!p) {
fprintf(stderr, "Error: %s\n", nxuskit_last_error());
}
```
### `nxuskit_free_provider`
```c
void nxuskit_free_provider(struct NxuskitProvider *provider);
```
Frees a provider handle. Safe to call with NULL (no-op).
**Parameters:**
- `provider` — Handle from `nxuskit_create_provider()`, or NULL.
## Synchronous Chat
### `nxuskit_chat`
```c
struct NxuskitResponse *nxuskit_chat(
struct NxuskitProvider *provider,
const char *request_json
);
```
Sends a synchronous chat request. Blocks until the response is complete.
**Parameters:**
- `provider` — Provider handle (must not be NULL)
- `request_json` — JSON chat request string
**Returns:** Response handle, or NULL on failure.
**Ownership:** Caller owns the returned handle. Must call `nxuskit_free_response()`.
**Request JSON fields:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `model` | string | Yes | Model identifier |
| `messages` | array | Yes | Array of `{role, content}` objects |
| `temperature` | float | No | Sampling temperature (0.0–2.0) |
| `max_tokens` | integer | No | Maximum tokens in response |
| `top_p` | float | No | Nucleus sampling parameter |
| `stop` | array | No | Stop sequences |
| `stream` | boolean | No | Must be `false` for sync (default) |
| `response_format` | object | No | Response format constraints |
**Message object:**
| Field | Type | Description |
|-------|------|-------------|
| `role` | string | `"system"`, `"user"`, or `"assistant"` |
| `content` | string | Message content |
### `nxuskit_response_json`
```c
const char *nxuskit_response_json(const struct NxuskitResponse *response);
```
Returns the JSON string from a response handle.
**Parameters:**
- `response` — Response handle from `nxuskit_chat()` (must not be NULL)
**Returns:** JSON string pointer. Valid only while the response handle exists.
Do **not** free this pointer — it is owned by the response handle.
**Response JSON fields:**
| Field | Type | Description |
|-------|------|-------------|
| `content` | string | The model's response text |
| `model` | string | Model used |
| `provider` | string | Provider name |
| `usage` | object | Token usage (if available) |
| `usage.prompt_tokens` | integer | Input tokens |
| `usage.completion_tokens` | integer | Output tokens |
| `usage.total_tokens` | integer | Total tokens |
| `finish_reason` | string | Why generation stopped |
| `warnings` | array | Provider warnings (if any) |
### `nxuskit_free_response`
```c
void nxuskit_free_response(struct NxuskitResponse *response);
```
Frees a response handle. Safe to call with NULL.
## Streaming Chat
### Callback Types
```c
typedef int32_t (*NxuskitStreamCallback)(
const char *chunk_json,
void *user_data
);
typedef void (*NxuskitStreamDoneCallback)(
const char *final_json,
void *user_data
);
```
**`NxuskitStreamCallback`** is called for each streaming chunk. Return 0 to
continue, non-zero to request cancellation.
**`NxuskitStreamDoneCallback`** is called exactly once when streaming completes
(success, error, or cancellation).
**Important:** Callbacks fire from a **background thread**. The caller must
ensure `user_data` is thread-safe.
### `nxuskit_chat_stream`
```c
struct NxuskitStream *nxuskit_chat_stream(
struct NxuskitProvider *provider,
const char *request_json,
NxuskitStreamCallback on_chunk,
NxuskitStreamDoneCallback on_done,
void *user_data
);
```
Starts a streaming chat request. Returns immediately; chunks arrive via callbacks.
**Parameters:**
- `provider` — Provider handle (must not be NULL)
- `request_json` — JSON chat request string
- `on_chunk` — Called for each chunk (from background thread)
- `on_done` — Called once when streaming ends (from background thread)
- `user_data` — Opaque pointer passed to both callbacks
**Returns:** Stream handle, or NULL on failure.
**Chunk JSON fields:**
| Field | Type | Description |
|-------|------|-------------|
| `delta` | string | Incremental text content |
| `index` | integer | Chunk sequence number (0-based) |
| `thinking` | string | Chain-of-thought reasoning (if enabled, optional) |
| `finish_reason` | string | Why generation stopped (set on final chunk, optional) |
| `usage` | object | Token usage statistics (typically only on final chunk, optional) |
| `tool_calls` | array | Tool call deltas (if applicable, optional) |
**Done JSON fields:** Same as synchronous response JSON, plus optional `error`:
| Field | Type | Description |
|-------|------|-------------|
| `error.error_type` | string | Error category |
| `error.message` | string | Error description |
### `nxuskit_cancel_stream`
```c
void nxuskit_cancel_stream(struct NxuskitStream *stream);
```
Cancels a streaming request. Blocks until all pending callbacks have completed.
After this call returns, no further callbacks will fire.
Safe to call with NULL.
### `nxuskit_free_stream`
```c
void nxuskit_free_stream(struct NxuskitStream *stream);
```
Frees a stream handle. Must be called after the stream completes or is cancelled.
Safe to call with NULL.
**Typical lifecycle:**
```c
stream = nxuskit_chat_stream(provider, request, on_chunk, on_done, data);
// ... callbacks fire ...
// After on_done fires (or if you want to cancel):
nxuskit_cancel_stream(stream); // optional — ensures no more callbacks
nxuskit_free_stream(stream); // required — frees resources
```
## Model Discovery
### `nxuskit_list_models`
```c
char *nxuskit_list_models(struct NxuskitProvider *provider);
```
Returns a JSON array of available models.
**Parameters:**
- `provider` — Provider handle (must not be NULL)
**Returns:** JSON string (caller-owned), or NULL on failure.
**Ownership:** Caller must free the returned string with `nxuskit_free_string()`.
**Response format:**
```json
[
{"id": "gpt-4o", "name": "GPT-4o"},
{"id": "gpt-4o-mini", "name": "GPT-4o Mini"}
]
```
## Error Handling
### `nxuskit_last_error`
```c
const char *nxuskit_last_error(void);
```
Returns the last error message for the **calling thread**. Returns NULL if no
error has occurred on this thread.
**Thread-local:** Each thread has its own error state. Calling any `nxuskit_*`
function may overwrite the previous error on that thread.
**Lifetime:** The returned pointer is valid until the next `nxuskit_*` call on
the same thread.
## Memory Management
### `nxuskit_free_string`
```c
void nxuskit_free_string(char *ptr);
```
Frees a caller-owned string returned by any `nxuskit_*` function that returns
`char*` (e.g., `nxuskit_list_models()`, `nxuskit_clips_facts_list()`,
`nxuskit_clips_eval()`). Safe to call with NULL.
**Important:** Only use this for strings documented as "caller-owned". Do not
use it for strings from `nxuskit_response_json()` (those are owned by the
response handle) or `nxuskit_version()` (static).
## Ownership Summary
| Function | Returns | Owned By | Free With |
|----------|---------|----------|-----------|
| `nxuskit_version()` | `const char*` | Library (static) | Never free |
| `nxuskit_create_provider()` | `NxuskitProvider*` | Caller | `nxuskit_free_provider()` |
| `nxuskit_chat()` | `NxuskitResponse*` | Caller | `nxuskit_free_response()` |
| `nxuskit_response_json()` | `const char*` | Response handle | Freed with response |
| `nxuskit_chat_stream()` | `NxuskitStream*` | Caller | `nxuskit_free_stream()` |
| `nxuskit_list_models()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_last_error()` | `const char*` | Thread-local | Never free |
## CLIPS Session API
Direct access to the CLIPS 6.4.2 rule engine via session-based handles — create
sessions, load rules, assert facts, run inference, and inspect results without
going through the provider/chat abstraction.
All CLIPS operations use opaque `uint64_t` session handles (generational indices
that prevent use-after-free). Return conventions:
- `int32_t` functions return 0 on success, -1 on error
- `char*` functions return a JSON string (caller-owned, free with `nxuskit_free_string()`) or NULL on error
- `bool` functions return the queried value; check `nxuskit_last_error()` on unexpected results
### Session Lifecycle
#### `nxuskit_clips_session_create`
```c
uint64_t nxuskit_clips_session_create(void);
```
Creates a new isolated CLIPS session. Returns a non-zero session handle, or 0 on
failure (check `nxuskit_last_error()`).
#### `nxuskit_clips_session_destroy`
```c
void nxuskit_clips_session_destroy(uint64_t session);
```
Destroys a session and frees all resources. No-op if the handle is invalid.
#### `nxuskit_clips_session_reset`
```c
int32_t nxuskit_clips_session_reset(uint64_t session);
```
Resets the session: clears all facts, preserves rules, restores initial-fact.
#### `nxuskit_clips_session_clear`
```c
int32_t nxuskit_clips_session_clear(uint64_t session);
```
Clears everything (facts, rules, templates) — returns the session to a pristine state.
#### `nxuskit_clips_session_info`
```c
char *nxuskit_clips_session_info(uint64_t session);
```
Returns session metadata as a JSON object (module count, rule count, fact count, etc.).
### Loading Constructs
#### `nxuskit_clips_session_load_file`
```c
int32_t nxuskit_clips_session_load_file(uint64_t session, const char *path);
```
Loads constructs from a `.clp` file.
#### `nxuskit_clips_session_load_string`
```c
int32_t nxuskit_clips_session_load_string(uint64_t session, const char *constructs);
```
Loads constructs from an in-memory string.
**Example:**
```c
uint64_t s = nxuskit_clips_session_create();
nxuskit_clips_session_load_string(s,
"(deftemplate sensor (slot name) (slot value))");
```
#### `nxuskit_clips_session_load_binary`
```c
int32_t nxuskit_clips_session_load_binary(uint64_t session, const char *path);
```
Loads a pre-compiled binary image (`.bin` file created with `save_binary`).
#### `nxuskit_clips_session_save_binary`
```c
int32_t nxuskit_clips_session_save_binary(uint64_t session, const char *path);
```
Saves the current session state as a binary image for fast reloading.
#### `nxuskit_clips_session_build`
```c
int32_t nxuskit_clips_session_build(uint64_t session, const char *construct);
```
Builds a single CLIPS construct (deftemplate, defrule, etc.) from a string.
#### `nxuskit_clips_session_batch`
```c
int32_t nxuskit_clips_session_batch(uint64_t session, const char *path);
```
Executes a batch file of CLIPS commands.
#### `nxuskit_clips_session_load_json`
```c
int32_t nxuskit_clips_session_load_json(uint64_t session, const char *json);
```
Loads constructs from a JSON specification (templates, rules, facts in one call).
### Session Cache
#### `nxuskit_clips_session_preload`
```c
int32_t nxuskit_clips_session_preload(const char *name, const char *rules_json);
```
Preloads a named session into the cache. The session is created, rules are loaded,
and the session is stored for later retrieval via `get_cached`.
#### `nxuskit_clips_session_get_cached`
```c
uint64_t nxuskit_clips_session_get_cached(const char *name);
```
Returns a cached session handle by name. Returns 0 if not found.
#### `nxuskit_clips_session_cache_remove`
```c
int32_t nxuskit_clips_session_cache_remove(const char *name);
```
Removes a named session from the cache and destroys it.
### Fact Operations
#### `nxuskit_clips_fact_assert_string`
```c
int64_t nxuskit_clips_fact_assert_string(uint64_t session, const char *fact_string);
```
Asserts a fact using CLIPS syntax. Returns the fact index (>= 0) on success, or -1 on error.
**Example:**
```c
int64_t idx = nxuskit_clips_fact_assert_string(s,
"(sensor (name \"temp-1\") (value 150))");
```
#### `nxuskit_clips_fact_assert_structured`
```c
int64_t nxuskit_clips_fact_assert_structured(
uint64_t session,
const char *template_name,
const char *slots_json
);
```
Asserts a fact using a JSON slot specification. Returns the fact index or -1.
**Example:**
```c
int64_t idx = nxuskit_clips_fact_assert_structured(s, "sensor",
"{\"name\":\"temp-1\",\"value\":150}");
```
#### `nxuskit_clips_fact_retract`
```c
int32_t nxuskit_clips_fact_retract(uint64_t session, int64_t fact_index);
```
Retracts a fact by its index.
#### `nxuskit_clips_fact_retract_by_template`
```c
int32_t nxuskit_clips_fact_retract_by_template(uint64_t session, const char *template_name);
```
Retracts all facts of a given template.
#### `nxuskit_clips_fact_exists`
```c
bool nxuskit_clips_fact_exists(uint64_t session, int64_t fact_index);
```
Returns true if the fact index refers to an existing fact.
#### `nxuskit_clips_fact_get_slot`
```c
char *nxuskit_clips_fact_get_slot(uint64_t session, int64_t fact_index, const char *slot_name);
```
Returns a slot value as a type-tagged JSON string (e.g., `{"type":"integer","value":42}`).
**Slot JSON types:**
| CLIPS Type | JSON `type` | JSON `value` |
|------------|-------------|--------------|
| INTEGER | `"integer"` | number |
| FLOAT | `"float"` | number |
| STRING | `"string"` | string |
| SYMBOL | `"symbol"` | string |
| MULTIFIELD | `"multifield"` | array of typed values |
#### `nxuskit_clips_fact_slot_values`
```c
char *nxuskit_clips_fact_slot_values(uint64_t session, int64_t fact_index);
```
Returns all slot values as a JSON object.
#### `nxuskit_clips_fact_pp_form`
```c
char *nxuskit_clips_fact_pp_form(uint64_t session, int64_t fact_index);
```
Returns the pretty-printed CLIPS representation of a fact.
#### `nxuskit_clips_fact_index`
```c
int64_t nxuskit_clips_fact_index(uint64_t session, int64_t fact_index);
```
Returns the canonical CLIPS fact index, or -1 on error.
#### `nxuskit_clips_facts_list`
```c
char *nxuskit_clips_facts_list(uint64_t session);
```
Returns all facts as a JSON array.
#### `nxuskit_clips_facts_by_template`
```c
char *nxuskit_clips_facts_by_template(uint64_t session, const char *template_name);
```
Returns all facts matching a template as a JSON array.
#### `nxuskit_clips_fact_duplication_get` / `set`
```c
bool nxuskit_clips_fact_duplication_get(uint64_t session);
int32_t nxuskit_clips_fact_duplication_set(uint64_t session, bool allow);
```
Query or set whether duplicate facts are allowed.
### Template Operations
#### `nxuskit_clips_template_exists`
```c
bool nxuskit_clips_template_exists(uint64_t session, const char *name);
```
Returns true if the named template exists in the session.
#### `nxuskit_clips_template_list`
```c
char *nxuskit_clips_template_list(uint64_t session);
```
Returns all template names as a JSON array.
#### `nxuskit_clips_template_slot_names`
```c
char *nxuskit_clips_template_slot_names(uint64_t session, const char *template_name);
```
Returns slot names for a template as a JSON array.
#### `nxuskit_clips_template_slot_info`
```c
char *nxuskit_clips_template_slot_info(uint64_t session, const char *template_name);
```
Returns detailed slot information (types, defaults, constraints) as JSON.
#### `nxuskit_clips_template_facts`
```c
char *nxuskit_clips_template_facts(uint64_t session, const char *template_name);
```
Returns all facts of a template as a JSON array.
#### `nxuskit_clips_template_pp_form`
```c
char *nxuskit_clips_template_pp_form(uint64_t session, const char *template_name);
```
Returns the pretty-printed CLIPS definition of a template.
### Inference Engine
#### `nxuskit_clips_session_run`
```c
int64_t nxuskit_clips_session_run(uint64_t session, int64_t limit);
```
Runs inference. Pass `limit = -1` to run until the agenda is exhausted.
Returns the number of rules fired, or -1 on error.
#### `nxuskit_clips_session_halt`
```c
int32_t nxuskit_clips_session_halt(uint64_t session);
```
Signals the session to halt inference (thread-safe — can be called from another thread).
#### `nxuskit_clips_agenda_size`
```c
int64_t nxuskit_clips_agenda_size(uint64_t session);
```
Returns the number of activations on the agenda.
#### `nxuskit_clips_agenda_clear`
```c
int32_t nxuskit_clips_agenda_clear(uint64_t session);
```
Removes all activations from the agenda.
#### `nxuskit_clips_agenda_reorder`
```c
int32_t nxuskit_clips_agenda_reorder(uint64_t session);
```
Reorders the agenda using the current conflict resolution strategy.
#### `nxuskit_clips_strategy_get` / `set`
```c
char *nxuskit_clips_strategy_get(uint64_t session);
int32_t nxuskit_clips_strategy_set(uint64_t session, const char *strategy);
```
Get or set the conflict resolution strategy. Valid values: `"depth"`, `"breadth"`,
`"simplicity"`, `"complexity"`, `"lex"`, `"mea"`, `"random"`.
#### `nxuskit_clips_salience_mode_get` / `set`
```c
char *nxuskit_clips_salience_mode_get(uint64_t session);
int32_t nxuskit_clips_salience_mode_set(uint64_t session, const char *mode);
```
Get or set the salience evaluation mode.
### Rule Operations
#### `nxuskit_clips_rule_exists`
```c
bool nxuskit_clips_rule_exists(uint64_t session, const char *name);
```
Returns true if the named rule exists.
#### `nxuskit_clips_rule_list`
```c
char *nxuskit_clips_rule_list(uint64_t session);
```
Returns all rule names as a JSON array.
#### `nxuskit_clips_rule_times_fired`
```c
int64_t nxuskit_clips_rule_times_fired(uint64_t session, const char *rule_name);
```
Returns how many times a rule has fired, or -1 on error.
#### `nxuskit_clips_rule_breakpoint_set` / `remove` / `has_breakpoint`
```c
int32_t nxuskit_clips_rule_breakpoint_set(uint64_t session, const char *rule_name);
int32_t nxuskit_clips_rule_breakpoint_remove(uint64_t session, const char *rule_name);
bool nxuskit_clips_rule_has_breakpoint(uint64_t session, const char *rule_name);
```
Manage breakpoints on rules for debugging.
#### `nxuskit_clips_rule_refresh`
```c
int32_t nxuskit_clips_rule_refresh(uint64_t session, const char *rule_name);
```
Refreshes a rule, placing its activations back on the agenda.
#### `nxuskit_clips_rule_pp_form`
```c
char *nxuskit_clips_rule_pp_form(uint64_t session, const char *rule_name);
```
Returns the pretty-printed CLIPS definition of a rule.
#### `nxuskit_clips_rule_delete`
```c
int32_t nxuskit_clips_rule_delete(uint64_t session, const char *rule_name);
```
Deletes a rule from the session.
### Module Operations
#### `nxuskit_clips_module_exists`
```c
bool nxuskit_clips_module_exists(uint64_t session, const char *name);
```
Returns true if the named module exists.
#### `nxuskit_clips_module_list`
```c
char *nxuskit_clips_module_list(uint64_t session);
```
Returns all module names as a JSON array.
#### `nxuskit_clips_module_current_get` / `set`
```c
char *nxuskit_clips_module_current_get(uint64_t session);
int32_t nxuskit_clips_module_current_set(uint64_t session, const char *name);
```
Get or set the current module.
#### `nxuskit_clips_focus_push` / `get` / `pop` / `clear`
```c
int32_t nxuskit_clips_focus_push(uint64_t session, const char *module_name);
char *nxuskit_clips_focus_get(uint64_t session);
int32_t nxuskit_clips_focus_pop(uint64_t session);
int32_t nxuskit_clips_focus_clear(uint64_t session);
```
Manage the module focus stack (controls which module's rules are eligible to fire).
### Global Variables
#### `nxuskit_clips_global_exists`
```c
bool nxuskit_clips_global_exists(uint64_t session, const char *name);
```
Returns true if the named defglobal exists.
#### `nxuskit_clips_global_list`
```c
char *nxuskit_clips_global_list(uint64_t session);
```
Returns all global variable names as a JSON array.
#### `nxuskit_clips_global_get_value` / `set_value`
```c
char *nxuskit_clips_global_get_value(uint64_t session, const char *name);
int32_t nxuskit_clips_global_set_value(uint64_t session, const char *name, const char *value_json);
```
Get or set a global variable value. Values use the type-tagged JSON format.
#### `nxuskit_clips_reset_globals_get` / `set`
```c
bool nxuskit_clips_reset_globals_get(uint64_t session);
int32_t nxuskit_clips_reset_globals_set(uint64_t session, bool reset);
```
Query or set whether globals are reset when `session_reset` is called.
### Evaluation
#### `nxuskit_clips_eval`
```c
char *nxuskit_clips_eval(uint64_t session, const char *expression);
```
Evaluates a CLIPS expression and returns the result as a type-tagged JSON string.
#### `nxuskit_clips_function_call`
```c
char *nxuskit_clips_function_call(uint64_t session, const char *function_name, const char *args);
```
Calls a CLIPS function by name with optional arguments string.
### Debugging
#### `nxuskit_clips_watch` / `unwatch`
```c
int32_t nxuskit_clips_watch(uint64_t session, const char *item);
int32_t nxuskit_clips_unwatch(uint64_t session, const char *item);
```
Enable or disable tracing for a watch item. Valid items: `"facts"`, `"rules"`,
`"activations"`, `"compilations"`, `"statistics"`, `"globals"`, `"focus"`, `"all"`.
#### `nxuskit_clips_dribble_on` / `off`
```c
int32_t nxuskit_clips_dribble_on(uint64_t session, const char *path);
int32_t nxuskit_clips_dribble_off(uint64_t session);
```
Start or stop logging all CLIPS I/O to a file.
### CLIPS Ownership Summary
| Function | Returns | Owned By | Free With |
|----------|---------|----------|-----------|
| `nxuskit_clips_session_create()` | `uint64_t` | Session registry | `nxuskit_clips_session_destroy()` |
| `nxuskit_clips_session_get_cached()` | `uint64_t` | Session cache | `nxuskit_clips_session_cache_remove()` |
| `nxuskit_clips_session_info()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_fact_get_slot()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_fact_slot_values()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_fact_pp_form()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_facts_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_facts_by_template()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_slot_names()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_slot_info()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_facts()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_template_pp_form()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_rule_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_rule_pp_form()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_module_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_module_current_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_focus_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_global_list()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_global_get_value()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_strategy_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_salience_mode_get()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_eval()` | `char*` | Caller | `nxuskit_free_string()` |
| `nxuskit_clips_function_call()` | `char*` | Caller | `nxuskit_free_string()` |
### Complete Example
```c
#include "nxuskit.h"
#include