A plan-and-execute agent runtime that verifies every answer and learns which tool to use from experience.
Darkrai turns a natural-language goal into a dependency graph of tasks, chooses a tool for each task with a contextual-bandit policy, executes it inside safety boundaries, has an independent evaluator verify the result, replans on failure, and composes a final answer that cites the verified results. Every decision is logged with its probability, so the policy's learning can be measured and new policies can be evaluated offline.
It understands requests with its own trained language model, a 22M-parameter MiniLM fine-tuned in this repository, with deterministic checks around everything the model produces. A second trained model, the maths model, solves multi-step word problems; it was trained on four public maths datasets (GSM8K, MAWPS, ASDiv, SVAMP) plus 10,000 generated everyday problems. It runs fully offline without any external LLM. It can optionally use one (Claude through the Anthropic SDK, or a local model through Ollama) for planning, tool arguments, code generation with self-repair, and answers, with deterministic grounding checks on everything the LLM produces.
All numbers below are measured by scripts in experiments/ and stored in
experiments/reports/. Success is judged by ground-truth checkers, never by
the agent itself. Methodology and caveats: docs/EVALUATION.md.
Tool policy learning (experiments/learning_curve.py, 5 seeds, 55 training
and 39 disjoint test tasks per seed, first-attempt accuracy on test tasks):
| Policy | Before training | After training (95% CI) |
|---|---|---|
| Random | 11.3% | 20.5% (14.1–26.9%) |
| Semantic similarity (zero-shot) | 46.2% | 46.2% |
| Legacy heuristic + memory | 33.9% | 65.6% (37.1–94.2%) |
| Contextual bandit, embeddings only (ablation) | 46.2% | 86.2% (82.5–89.8%) |
| Contextual bandit (default) | 89.7% | 100.0% (100–100%) |
End-to-end agent (experiments/e2e_harness.py, 36 generated goals across
arithmetic, list statistics, sequences, CSV-dataset questions, document
questions, and multi-step goals): 100% task success with a fresh policy and
after 30 training goals, with no false successes and 97.2% first-attempt
success. Median latency is 0.35–0.5 s per goal on a laptop CPU, depending on
machine load; most of it is starting the sandboxed Python process.
Hand-written prompts. These are free-form prompts the argument templates were not written against, including requests the agent should decline. Each set was committed to git before its first run. A false success is a goal the agent reported as fully verified although the answer was wrong.
| Prompts | Code measured | Blind | Success | False success |
|---|---|---|---|---|
| Set 1 (41) | Before fixes | yes | 51.2% | 31.7% |
| Set 2 (41) | Before fixes (control) | yes | 65.8% | 24.4% |
| Set 2 (41) | After fixes | yes | 82.9% | 2.4% |
| Set 1 / Set 2 | Current, tuned after seeing them | no | 80.5% / 92.7% | 0% / 0% |
The generated suite had hidden a serious problem. On free phrasing, the agent often answered a different question than the one asked, and still reported success:
- it dropped qualifiers such as "from the North region";
- it ignored "then …" steps;
- it accepted on-topic passages that did not answer the question.
The fix is a rule, not per-prompt patches. A template must account for every number, column, and step in the request, or decline. Retrieved passages now pass a calibrated answerability check. Every remaining failure on these sets was an honest one, mostly word problems ("7 notebooks at 45 rupees each"), which is what the trained language model below was built for.
Darkrai's own language model (how it works). A fine-tuned MiniLM reads a request into a frame, and deterministic code builds and checks the tool input.
- Training uses synthetic schemas only: no bundled dataset or column names, and near-copies of evaluation prompts are removed.
- Offline, on templates and schemas it never saw, it reaches 88.0% frame accuracy:
- vs 73.2% for TF-IDF + logistic regression;
- vs 63.4% with the encoder frozen.
End to end, on set 3 (48 prompts written before the model existed, including word problems and clarification cases):
| System | Success | False success |
|---|---|---|
| Rules, before this work | 64.6% | 2.1% |
| Rules + clarifying questions | 70.8% | 2.1% |
| Trained model alone | 79.2% | 2.1% |
| Trained model first, rules as fallback (default) | 89.6% | 4.2% |
Those are the blind numbers. Their two false successes (one from the rules, one from the model) led to general fixes. After them, every system has 0% false success on all four suites, and the default reaches 91.7% on set 3, 92.7% on set 1, and 100% on set 2 and the generated suite.
Against a local 7B LLM (qwen2.5 through Ollama, same agent, same frozen prompts, same laptop CPU):
| Set 3 | Success | False success | Median per goal |
|---|---|---|---|
| Darkrai's trained model + rules (default) | 91.7% | 0% | 0.37 s |
| Rules + 7B LLM, unchecked | 60.4% | 20.8% | 35 s |
| Rules + 7B LLM + grounding checks | 70.8% | 6.3% | 30 s |
The LLM solves word problems the rules cannot, but its plans split simple data questions into steps that cannot be verified, and unchecked it made a wrong claim one time in five. Deterministic grounding checks on its plans, inputs, and answers cut that to about one in sixteen. Details, all four suites, and what the checks still miss: EVALUATION.md §7.
Maths word problems (how the maths model works). These are test problems never seen in training, answered at confidence ≥ 0.9:
| Test set | Correct | Wrong | Declined |
|---|---|---|---|
| MAWPS (one- and two-step) | 88.3% | 0.2% | 11.5% |
| ASDiv (diverse) | 23.3% | 1.9% | 74.8% |
| SVAMP (adversarial) | 6.7% | 4.7% | 88.6% |
| GSM8K (multi-step) | 0.0% | 0.2% | 99.8% |
Standard one- and two-step problems are solved well. Adversarial and long multi-step problems are mostly declined: a 22M-parameter template classifier cannot reason through them, and on SVAMP a few wrong answers still get through. In the agent, with the maths model on, all four suites keep 0% false success. Set 3 rises to 93.8%, but that set is not blind for the maths model (EVALUATION.md §9).
Off-policy evaluation: from uniformly random logs, doubly-robust and self-normalized IPS estimate the trained policy's value within 0.04–0.05 of its true value (0.986); plain IPS is off by 0.29. With only about 4 effective samples per seed these estimates illustrate the method rather than measure it precisely.
The evaluation harness also found:
- two reward-hacking behaviours: answering follow-up steps by saving reports, and accepting irrelevant retrieved passages;
- a train/test leakage bug in the first version of the experiment.
All of these are fixed and covered by regression tests.
| Human approval before a side effect | Asking instead of guessing |
|---|---|
![]() |
![]() |
| Evaluation: rules vs trained model vs LLM | Learning curves with 95% CIs |
![]() |
![]() |
- Understand requests with its own trained language model, a 22M-parameter MiniLM fine-tuned in this repository. It reads a request into a frame (operation plus tagged columns, values, and conditions), and deterministic code turns the frame into a tool input and rejects anything it cannot account for. No external LLM is needed (how it works).
- Solve word problems with several steps ("John has 5 apples and buys 3 bags with 4 apples each") using a second trained model that picks an expression over the problem's numbers. Fixed code then checks it: confidence, every number used, units dividing the right way. Finally it calculates the answer exactly (how it works).
- Ask instead of failing when one answer would fix a request: "There is no column called 'revenu'. Did you mean 'revenue'?", or "Do you mean the highest or the lowest CGPA?".
- Plan goals into a task DAG; dependent steps receive upstream results ("calculate 100 + 200; then double it").
- Use an LLM safely, if one is configured (Claude, or a local model through Ollama): schema-validated plans and tool calls, error-driven code repair, cited answers. Grounding checks reject plans that drop the goal's numbers, inputs with invented numbers or no computation, and answers stating numbers no verified output contains; the deterministic path takes over.
- Use six tools: calculator (plain-English arithmetic), sandboxed Python (with uploaded CSV datasets), document search over uploaded
.txt/.md/.pdffiles with cited passages, web search (Wikipedia or Tavily), SSRF-protected page fetching, and a report writer that requires human approval. - Verify every attempt with an evidence-based evaluator; replan with a different tool on task-specific failures and retry the same tool on transient ones.
- Learn tool choice with a LinUCB contextual bandit whose posterior updates from verified outcomes; log propensities for off-policy evaluation.
- Recover from crashes using durable checkpoints and an action ledger that never replays an action whose outcome is unknown.
- Pause, resume, cancel, approve, and rate runs from the dashboard or API; stream live events over WebSocket.
- Serve MCP so Claude Desktop, Cursor, or any MCP client can run goals and tools.
Requires Python 3.11+ and Node 20+.
python -m venv venv
.\venv\Scripts\Activate.ps1
pip install torch --index-url https://download.pytorch.org/whl/cpu
pip install -r requirements-dev.txt
python -m ml.nlu.train # optional: trains Darkrai's language model (~45 min on a laptop CPU;
# --quick trains only the TF-IDF baseline in ~30 s)
python -m ml.mathwp.data --download # optional: the maths model's datasets (7.6 MB from Hugging Face)
python -m ml.mathwp.train --epochs 3 # optional: trains the maths model (~2 h on a laptop CPU)
uvicorn backend.api.main:app --reloadWithout a trained model the agent runs in rules mode; with one it uses the
model first and the rules as a fallback (DARKRAI_LANGUAGE_MODE=hybrid).
In a second terminal:
cd frontend
npm install
npm run devOpen http://localhost:5173, upload the sample files from examples/ on the
Documents & data page, and try the example goals on the Run page.
Interactive API docs are at http://localhost:8000/docs.
docker compose up --buildThis starts PostgreSQL with pgvector, the API (migrations run on start), and
the dashboard behind nginx at http://localhost:8080. A language model trained
on the host (ml/models/checkpoints) is mounted read-only; without one the API
runs in rules mode. Tested end to end with Docker Desktop 29.8 and Compose 5.5
(what that found).
For an LLM, add --profile llm to start Ollama in a container, then pull a
model into it. That profile has not been tested here. To use an Ollama already
running on the host instead, set DARKRAI_LLM_PROVIDER=ollama,
DARKRAI_LLM_MODEL=qwen2.5:7b-instruct, and
DARKRAI_LLM_BASE_URL=http://host.docker.internal:11434; this was tested.
Locally, the app creates its SQLite tables on first start. For a PostgreSQL
deployment, apply the schema with Alembic before starting the API
(DATABASE_URL=... alembic upgrade head); schema changes ship as new revisions
and a test fails if the models drift from the migrations.
Everything is optional; see .env.example for the full list. Set these as
environment variables, or copy .env.example to .env and start the API with
uvicorn backend.api.main:app --reload --env-file .env (without --env-file,
settings read from the process environment, such as the LLM provider, are ignored).
| Variable | Effect |
|---|---|
DARKRAI_LLM_PROVIDER |
none (default), ollama, or anthropic |
DARKRAI_MATH_MODEL |
auto (default: use the trained maths model if present), minilm, baseline, or off |
DARKRAI_LLM_MODEL |
e.g. qwen2.5:7b-instruct; Anthropic default is claude-opus-5-5 |
DARKRAI_TOOL_PERMISSIONS |
grants: network, documents:read, workspace:write (default all) |
DARKRAI_APPROVAL_POLICY |
manual (default), auto, or deny for side-effecting tools |
DARKRAI_POLICY |
bandit (default) or heuristic |
DARKRAI_API_KEY |
require X-API-Key on every API request |
DATABASE_URL, VECTOR_DATABASE_URL |
PostgreSQL / pgvector instead of SQLite and local JSON |
DARKRAI_HTTP_USER_AGENT, TAVILY_API_KEY |
web search settings (Wikimedia requires contact details in the User-Agent) |
{
"mcpServers": {
"darkrai": {
"command": "C:/path/to/DarkrAI/venv/Scripts/python.exe",
"args": ["-m", "backend.mcp_server"],
"cwd": "C:/path/to/DarkrAI"
}
}
}Tools: run_goal, calculate, run_python, search_documents,
list_datasets. Side-effecting tools are denied over MCP unless
DARKRAI_MCP_APPROVAL_POLICY=auto.
pytest -m "not slow" # 192 fast tests (6 more load flan-t5)
python experiments/learning_curve.py # ~7 min on a laptop CPU
python experiments/e2e_harness.py # ~1 min; add --online for web tasks
python experiments/e2e_harness.py --suite handwritten # set 1
python experiments/e2e_harness.py --suite handwritten --tasks experiments/tasks/handwritten_v2.json # set 2
python -m ml.nlu.train # language model: baseline, ablation, fine-tune (~45 min)
python -m ml.mathwp.data --download # maths datasets, then:
python -m ml.mathwp.train --epochs 3 # maths model and its held-out test scores (~2 h)
python experiments/language_comparison.py # rules vs models vs hybrid on every suite (~30 min)
python experiments/language_comparison.py --llm-only # the local-LLM rows (Ollama; hours on a CPU)
cd frontend; npm test # frontend unit tests (Node's built-in runner)scripts/capture_screenshots.py regenerates the screenshots with headless Edge
or Chrome.
CI runs:
- backend: ruff lint and format checks, mypy, the tests with coverage, and smoke runs of the end-to-end harness as regression gates, once with rules and once with a freshly trained baseline language model in hybrid mode;
- frontend: lint, unit tests, type check, and build.
backend/
agent/ runtime, planner, replanner, executor, argument builder, state
api/ FastAPI routers, schemas, auth and rate limiting
database/ SQLAlchemy models, repository, Alembic migrations
documents/ document and dataset store (chunking, embeddings)
llm/ providers, structured generation, planner, codegen, guardrails
tools/ calculator, Python sandbox, web, documents, report writer
mcp_server.py MCP server
ml/
policy/ contextual bandit and off-policy evaluation
evaluator/ evidence-based evaluator (+ optional seq2seq checkpoint)
goal_model/, planner_model/, training/ fine-tuning pipeline and registry
experiments/ task suite, learning curves, end-to-end harness, reports
frontend/ React + TypeScript dashboard
docs/ architecture, audit and roadmap, portfolio notes
- Darkrai's language model understands a closed set of 49 frames: single-operation arithmetic and word problems, list statistics, sequences, and dataset questions. Anything outside them, or anything it reads with doubt, is declined rather than guessed (8% of set 3 in the default mode). It is English-only and was trained on synthetic data, so its phrasing coverage is narrower than an LLM's.
- The trained models are not in git (about 90 MB each). Train them with
python -m ml.nlu.trainandpython -m ml.mathwp.train; without them the agent runs in rules mode. - The maths model handles one- and two-step word problems well (88% of MAWPS) but declines nearly all long multi-step problems (GSM8K), and on adversarial wording (SVAMP) 4.7% of problems still get a wrong answer at its 0.9 confidence threshold (details).
- The LLM path was measured with one small local model (qwen2.5 7B, 4-bit, CPU), one run per suite. With grounding checks it still makes false claims on about 5–6% of hand-written prompts (reasoning errors and answers that leave out the asked-for part). Larger hosted models were not measured.
- Wikipedia search needs a User-Agent with your contact details; otherwise use Tavily. Its keyword search is weak for questions, and the evaluator's web check (the top result must cover the question's terms) stops off-topic results but not on-topic wrong ones. The reported evaluations run offline, so web answers are not part of them.
- The Python sandbox is process-level isolation, suitable for a local demo, not for hostile multi-tenant code.
- Results come from generated tasks and 130 hand-written prompts in three sets, all written by the author of the rules, about two sample documents and two CSV files. They show the mechanisms work, that learning helps, and that the false-success fixes held on unseen prompts. They are not a broad benchmark.
- The fine-tuned flan-t5 goal parser never produced valid JSON on held-out data and is not used by default; its failed runs remain in the model registry.
More detail: architecture · evaluation · audit and roadmap · portfolio notes




