173 lines
10 KiB
Markdown
173 lines
10 KiB
Markdown
# floop/code — v0.1 draft implementation
|
||
|
||
A **draft**: every deciding stage (formal checks, the prover, real engines) is a
|
||
stub, so the draft runs with only LLM calls (as decided) and every answer is
|
||
honestly marked **UNVERIFIED**. The architecture — states, laws, control flow —
|
||
is the real v0.1 shape; only the formal layer is missing.
|
||
|
||
## Run
|
||
|
||
```bash
|
||
cd floop/code
|
||
uv run run_app.py "What information do I need to plan a trip to Tokyo?" # any question
|
||
uv run run_app.py --verbose "..." # + "thinking" on screen, flushed
|
||
uv run run_app.py --baseline "..." # A/B control: raw LLM, ONE call, no loop
|
||
FLOOP_LM=ollama-cloud uv run run_app.py "..." # cloud LM instead of local
|
||
```
|
||
|
||
### Baselines (Emili, 2026-10-16)
|
||
|
||
The draft experts are **baseline experts**: the LLM answers each small subquestion
|
||
directly from its own knowledge — no engine, no verification yet. Each evidence row
|
||
records the honest source: `model_weights` (answered from the LLM's own knowledge) or
|
||
`given_evidence` (backed by a verbatim quote from the evidence it was given). When the
|
||
real engines arrive (knowledge first), the verification path replaces the baseline path
|
||
per expert, and every improvement becomes measurable against this baseline.
|
||
|
||
`--baseline` is the A/B control: the same LM answers the whole question in ONE raw
|
||
call — no decomposition, no experts, no evidence table. Same LM, same budget unit.
|
||
Compare: `--baseline` vs the loop's many small directed calls.
|
||
|
||
- **Always**: `runs/<ts>-<slug>/run.log` (gitignored), written with explicit flush —
|
||
`tail -f runs/<latest>/run.log` from another terminal shows progress live.
|
||
- **`--verbose`**: the **thinking stream** also prints to the screen, flushed. Thinking is
|
||
floop's future user-facing "thinking" output (what floop-as-LLM will stream); it is a
|
||
SUBSET of the log — the log keeps all technical detail (budget, provenance, raw payloads),
|
||
thinking stays readable. They will diverge over time (Emili, 2026-10-13).
|
||
- Screen thinking lines carry the `[T]` marker; recursion depth shows as `>` prefixes.
|
||
- The same events will drive the OpenAI-compatible endpoint's streaming mode (ARCHITECTURE.md §5).
|
||
|
||
`config.yaml` holds the budget knobs and the two LM providers (no keys in code:
|
||
`ollama-cloud` reads `OLLAMA_API_KEY` from the environment). Logs live in `runs/`.
|
||
|
||
## What is real vs stub (the honest map)
|
||
|
||
| Stage (ALGORITHM.md) | Status | Where |
|
||
|---|---|---|
|
||
| INIT — epistemic decomposition (LLM call) | real (dspy.Predict) | `floop/dspy_modules.py` |
|
||
| MISSING — gap decomposition on stuck goal | real (dspy) | `floop/dspy_modules.py` |
|
||
| ROUTE — one LLM judgement over the catalogue | real (dspy) | `floop/dspy_modules.py` |
|
||
| Expert attendants (the draft answer) | **BASELINE engine**: LLM answers from its weights; `verified=False`; source recorded (`model_weights`/`given_evidence`) | `floop/engine.py` |
|
||
| **knowledge** expert | **REAL pipeline** (2026-10-17): KG probe (entity+relation, stemmed) -> COMPOSE queries (deterministic, from question ∪ evidence — the old TRANSLATE LLM removed 23/10) -> en.wikipedia search -> fetch_rich (text + wikitext tables) -> section chunks -> lexical gate -> EXTRACT (verbatim quotes) -> containment check -> merge (4 contradiction cases) -> answer from quoted rows. Fallback: baseline LLM on pipeline failure. | `knowledge/` + `floop/engine.py:KnowledgeEngine` |
|
||
| Arrival check (type check + contradiction) | **STUB**: only UNKNOWN refusal | `machine._append_checked` |
|
||
| Execution branches over ambiguity (ALGORITHM §6-bis) | **REAL** (2026-10-23): lazy fork per reading of an ambiguous row with an open dependent; BranchView binds the reading (table never mutated), acquired knowledge shared + branch-tagged; death by contradiction/dead end/natural merge; nested sub-branches; conditional final answer composed by fixed code | `floop/branches.py` + `floop/machine.py:_run_branch` |
|
||
| Prover (stop condition, derivability) | **STUB**: question stack terminal | `machine._finish` |
|
||
| `user` expert | not wired — explicit failure row | `floop/engine.py` |
|
||
| Backtracking / retraction (TMS) | not in the draft (§5 comes with the prover) | — |
|
||
| The machine (stack, dependency order, budget, recursion) | real fixed code | `floop/machine.py`, `floop/state.py` |
|
||
| Evidence table (append-only, provenance, no prose) | real | `floop/state.py` |
|
||
|
||
Laws kept: the table only ever receives typed payloads (never LLM prose); rows
|
||
carry provenance + trace; the machine — not the LLM — owns sequencing, budget,
|
||
retries and stopping; answer synthesis sees only evidence rows and cites them.
|
||
|
||
## Layout
|
||
|
||
```
|
||
config.yaml budget + LM providers
|
||
run_app.py CLI entry
|
||
floop/state.py EvidenceTable, QuestionStack, Budget, slot instantiation (#En -> value)
|
||
floop/llm.py dspy LM configuration (OpenAI-compatible endpoints)
|
||
floop/dspy_modules.py every LLM call as a dspy module (INIT, ROUTE, EXPERT, MISSING, ANSWER)
|
||
floop/engine.py engine interface + draft stub engines
|
||
floop/machine.py FloopRun — the loop; recursion for the `floop` attendant
|
||
floop/recorder.py the flight recorder — events.jsonl (one JSON line per component)
|
||
floop/traces.py events.jsonl -> OpenTelemetry spans; push a run to Jaeger (post-mortem)
|
||
floop/inspect_html.py events.jsonl -> self-contained inspect.html (offline viewer)
|
||
tests/state.py unit tests (no LLM)
|
||
tests/traces.py exporter tests (no network)
|
||
```
|
||
|
||
### Knowledge pipeline structure
|
||
|
||
`KnowledgeExpert.answer_question` in `knowledge/expert.py` orchestrates proof,
|
||
stored answers, and article-by-article gathering with early exit. Focused methods
|
||
handle stored-answer gating, query composition/search, cached fetching, skimming,
|
||
and post-ingestion answer checks. Stateless module-level helpers build probe
|
||
seeds and filter goal-relevant skim notices; `knowledge/ranking.py` ranks search
|
||
results. Run-wide page
|
||
and link caches survive calls; extraction entities, skim notices, and pending
|
||
skim leads reset per call after the proof path falls through.
|
||
|
||
Offline orchestration regression tests (no Wikipedia, embedder, or LLM required):
|
||
|
||
```bash
|
||
.venv/bin/python knowledge/tests/answer_question.py
|
||
```
|
||
|
||
### Wikipedia candidate ranking
|
||
|
||
`WikipediaClient.search` returns `WikiSearchResult` objects with `title` and
|
||
plain-text `snippet` (MediaWiki's query-specific search excerpt, not the full
|
||
introductory summary). HTML highlight tags are removed and entities decoded;
|
||
missing snippets leave the title available for ranking without an extra fetch.
|
||
|
||
All searches finish before fetching articles. Results are deduplicated by title,
|
||
retaining distinct snippets from different queries. Every unique candidate is
|
||
ranked against the **original question**, using **title + snippet**, not the
|
||
composed search queries:
|
||
|
||
- BM25 lexical relevance (k1=1.5, b=0.75) over the candidate pool, using the
|
||
existing word tokenizer and stemmer.
|
||
- Cosine similarity from the configured embedding service (`embed_model` /
|
||
`embed_url`), reusing the cached question vector and batch-embedding candidates.
|
||
- Equal-weight reciprocal rank fusion, `1/(60 + lexical_rank) +
|
||
1/(60 + semantic_rank)`. Ties share ranks; final ties retain encounter order.
|
||
|
||
There is **no query-winner priority**. `max_articles` is applied only after global
|
||
ranking. If embeddings are unavailable or malformed, the failure is logged and
|
||
ranking falls back to BM25 alone. Search events retain titles and snippets;
|
||
`rank_articles` events record the question, candidates, ranking method, BM25,
|
||
cosine, and final scores. Snippets only guide retrieval; fetched-page containment
|
||
checks still govern which facts may enter the KG.
|
||
|
||
Offline API, ranking, embedding-validation and fallback tests:
|
||
|
||
```bash
|
||
.venv/bin/python knowledge/tests/semantic_fetch.py
|
||
```
|
||
|
||
## Viewing a run as traces (Jaeger, 2026-10-27)
|
||
|
||
Every run records `events.jsonl`; `floop/traces.py` replays it as one
|
||
OpenTelemetry trace and pushes it to the Jaeger container on the agentvps
|
||
(`http://10.3.14.59:16686` on the VPN; OTLP ingest on `:4318`):
|
||
|
||
```bash
|
||
uv run python -m floop.traces runs/<ts>-<slug> # one run -> Jaeger
|
||
uv run python -m floop.traces --latest 3 # the newest runs
|
||
uv run python -m floop.traces <dir> --dry # build the payload, don't push
|
||
```
|
||
|
||
The root span is the run (named by the question, final answer as an
|
||
attribute); INIT/ROUTE/EXPERT/ANSWER components nest under it, every LLM
|
||
call is a span with its stage/duration/prompt file, and recursive child
|
||
runs appear as nested run-spans. Trace ids are deterministic — re-pushing
|
||
a run lands on the same trace. Stdlib only; the run itself never touches
|
||
the network.
|
||
|
||
Since 2026-10-27 (visibility laws), inputs and outputs are data:
|
||
- Pipeline functions emit `fn.done` — spans carry in.query / out.titles
|
||
(search), in.title / out.{url, chars, tables} (fetch), the judge's
|
||
question/value, compose/skim/chunk_gate/serve_set/list_ingest/harvest/
|
||
promote/check, each with NAMED arguments.
|
||
- dspy calls emit `sig.start`/`sig.done` — the Signature's input and
|
||
output fields as typed attributes (in.question, out.entities, out.facts).
|
||
- Every LLM span carries a CHILD `prompt` span with the exact prompt and
|
||
raw response (read from prompts/NN-stage.txt at export time) — click and
|
||
read, retroactively for old runs too.
|
||
- EXPERT spans carry the attendant name (EXPERT knowledge); nested spans
|
||
use the expert prefix (knowledge.search, knowledge.state); each expert
|
||
exports under its own OTel service (floop / knowledge / ...).
|
||
|
||
## Next steps (design order from the docs)
|
||
|
||
1. Real check layer on expert arrival (well-formedness per expert kind) — the
|
||
#1 failure mode is misformalization; keep it BEFORE engines.
|
||
2. ~~`knowledge` expert with real search + verbatim quotes~~ **DONE 2026-10-17**
|
||
(Wikipedia-only, en; DuckDuckGo + general web later).
|
||
3. Prover for the stop condition (clingo/Z3) — replaces the stub derivability.
|
||
4. Log every run (v2's router will eat these trajectories).
|
||
5. Knowledge efficiency: the gather still spends extraction calls on tangential
|
||
articles (US river lists matched the "longest river" gate); tune gate/articles.
|
||
Also: KG dedupe of noisy entities from early runs (`the loire` vs `loire river`). |