Pegasus logo
Aman Sachan papers • projects • research index
Paper draft

LLM Foundry: a modular framework for orchestration, memory, compression, tools, and evaluation

This is a long-form draft for the repository. It formalises the architecture in the repo README, usage guide, and technical paper notes: the model is only one piece; the useful system is the stack around it.

Abstract

What the paper claims without the marketing sludge.

LLM Foundry is a modular framework for language-model work that treats the base model as only one component of a larger system. Real use needs more than a prompt box: it needs tokenisation, memory, compression, tool execution, trace capture, evaluation, and back-end abstraction. This paper formalises that stack as a control plane around any model source.

The core idea is brutally simple. If the model is the worker, then the surrounding machinery is the workshop: the translator, the notebook, the editor, the audit log, the test bench, and the router. Once those pieces are formalised, a model can be swapped without rebuilding the whole system.

The draft below gives a clean engineering view, a mathematical view, and an implementation view. It also stays honest about what is and is not actually in the repo today.

1. Problem statement

What goes wrong when the model is treated like a standalone product.

The model is not the system

A language model by itself is a stateless function. It takes text, emits text, and forgets the rest. That is fine for toy chat, and mediocre for real work. Real tasks need memory, constraints, observability, and control over what happens after generation.

Operational requirements

A useful system must support repeatable prompts, contextual compression, retrieval from prior work, structured tool use, and consistent testing. Otherwise every long session becomes a pile of manual prompting and crossed fingers.

Design target

The goal is a model-agnostic control plane. If the backend changes, the user should keep the same memory, trace, and evaluation contract. That is the point of a framework instead of a one-off script.

2. Notation and system model

Formal definitions so the rest does not become mush.

Let a task be represented by a prompt x, a context bundle c, and a model backend M.

We write the effective model interface as:

y = M(x, c; θ)

where θ denotes backend-specific parameters or API state. The surrounding system transforms raw user intent into a structured context bundle:

c = (c_sys, c_user, c_mem, c_tools, c_trace)

with system instructions, user prompt, retrieved memory, tool affordances, and trace history. The job of LLM Foundry is to construct c in a way that improves utility without forcing the user to think about every layer manually.

3. Architecture overview

The stack is boring on purpose. Boring is what survives.

Adapter layer

The adapter isolates backend shape. Whether the model is local, OpenAI-compatible, Hugging Face, or a multi-endpoint bundle, the rest of the stack should only need a generate(prompt) contract and a small metadata envelope.

Tokenizer layer

Tokenisation converts text into the discrete units the backend understands. The repo documents byte, character, and Hugging Face tokenisation paths. The point is compatibility, not theological purity.

Memory and compression layer

Long sessions are expensive. The system compresses prior text into notes, keeps high-value facts, and retrieves them later. The memory vault acts like a searchable notebook instead of a black hole.

4. Formal memory objective

What the compression layer is trying to optimise.

Let S be a summary candidate and T be the original transcript or working context.

U(S; T) = α · Rel(S, T) - β · Redundancy(S) + γ · Retrieval(S) - δ · Cost(S)

where Rel measures relevance to the task, Redundancy penalises repeated content, Retrieval rewards future usefulness, and Cost accounts for token count and later rehydration overhead. The coefficients are not sacred; they are a tuning problem.

A simple extractive compressor can be written as a ranking problem over sentences or spans. If σ_i is a sentence score, then we keep the top-scoring spans subject to a budget constraint:

maximize   Σ_i σ_i z_i
subject to Σ_i ℓ_i z_i ≤ B,   z_i ∈ {0, 1}

where ℓ_i is span length and B is the token budget. The relaxation z_i ∈ [0,1] gives a continuous form that is easier to optimise and easier to explain to a human.

5. Reasoning overlays

Extra passes that reduce the chance of saying something dumb with confidence.

Reflection

A draft answer is generated, then critiqued, then revised. In practice this is a cheap way to catch obvious contradictions before they become the final answer.

Consensus

If multiple samples are available, the system can vote or score them. If each independent sample is correct with probability p > 1/2, then majority vote reduces error probability by a binomial tail:

P(correct) = Σ_{k=⌈n/2⌉}^{n} C(n, k) p^k (1-p)^{n-k}

Counterfactual check

Ask whether the answer still holds if one assumption flips. That is a tiny bit of paranoia, which is often exactly what a long-running agent needs.

6. Agent runtime and trace model

Why the system can learn from itself instead of pretending every run is isolated.

Let an agent trajectory be τ = (o_1, a_1, o_2, a_2, …, o_n, a_n), where observations and actions alternate.

The runtime consumes a task, selects tools, executes calls, and records a trace:

trace = {
  task,
  steps: [
    { observation, action, tool_result },
    ...
  ],
  final_answer
}

That trace can be exported into supervised examples. A simple export objective is to maximise the likelihood of correct tool sequences while preserving enough metadata to reproduce the run later.

7. Multi-endpoint orchestration

One endpoint is nice. Two is insurance. More is strategy.

The repo documents multi-endpoint configuration for failover or round-robin routing. If each endpoint i has latency ℓ_i, cost c_i, and reliability r_i, then a routing score can be written as:

score(i) = w_ℓ · ℓ_i + w_c · c_i - w_r · r_i

The chosen backend is then argmin_i score(i), optionally subject to hard constraints such as provider availability, token limits, or policy filters. This is not fancy, but it is robust, which is the only reason it matters.

8. Evaluation harnesses

No one should trust a system without a test bench.

Reasoning

Measure consistency, self-checking, and explanation quality. The interesting metric is not style; it is whether the answer survives scrutiny.

Tool use

Measure whether the model can select a tool, call it correctly, and use the result rather than hallucinating a shortcut.

Memory

Measure whether compressed notes can be retrieved and re-injected without losing the salient facts.

A practical metric suite can include exact-match, pass@k, tool success rate, retrieval hit rate, and end-to-end task completion.

task_score = λ1·exact_match + λ2·pass@k + λ3·tool_success + λ4·retrieval_hit_rate

9. Algorithms

Pseudocode, because vibes are not a specification.

Algorithm 1 — context build

Input: user prompt x, memory store V, backend M
1. retrieve top-k notes from V using x
2. build system prompt c_sys
3. compose c = (c_sys, x, retrieved notes, tool schema, trace summary)
4. call backend M(x, c)
5. record output and metadata

Algorithm 2 — trace export

Input: run trace τ
1. normalise tool names and arguments
2. split trajectory into observation/action pairs
3. write structured record to disk
4. attach task, final answer, and outcome flags

Algorithm 3 — routing

Input: endpoint set E, task t
1. score each endpoint by latency, cost, and reliability
2. filter unavailable endpoints
3. choose argmin score
4. if the call fails, retry on the next best endpoint

10. Derivations

Enough math to be real, not enough to be a lie.

Context budget

If a session has raw length L_raw and compressed length L_cmp, then the effective budget gain is ΔL = L_raw - L_cmp. The point of memory compression is to maximise ΔL while keeping the downstream answer quality stable.

Consensus error

For independent samples with correctness p, majority voting becomes increasingly reliable as n grows, provided p > 1/2. The formula above quantifies the improvement.

Routing tradeoff

If latency, cost, and reliability are combined linearly, then weights encode policy. A budget-sensitive deployment sets w_c higher; a latency-sensitive deployment sets w_ℓ higher; a mission-critical deployment sets w_r highest. That is the whole game.

11. Training from traces

How the system can produce its own training data without self-delusion.

A trace can be turned into supervised data by pairing the observed state with the chosen action. If a policy π produced the trace, then standard sequence learning minimises:

L_sft = -Σ_t log π(a_t | o_tt}, c_t)

Additional penalties can be added for invalid tool use, incoherent reasoning, or failed retrieval. The general objective is:

L = L_sft + λ_trace L_trace + λ_mem L_mem + λ_safe L_safe

The point is not to worship one loss function. It is to make the right behaviour easy to measure and harder to fake.

12. What the repo already gives you

From the documentation, not from fantasy.

Backend abstraction

Adapters for local, OpenAI-compatible, Hugging Face, and multi-endpoint paths.

Memory utilities

Compression plus a markdown-based note vault for durable recall.

Trace export and harnesses

Structured traces and evaluation scripts for reasoning, coding, tool use, and memory.

13. Limitations

The annoying part that keeps the paper honest.

  • This is a control-plane framework, not a frontier base model.
  • Compression and memory quality depend on the backend and the task.
  • Multi-endpoint routing is only as good as the provider metadata you feed it.
  • Trace export is useful only if the traces are actually valid.
  • Evaluation must be repeated on real workloads, not just demo prompts.

14. Proposed experiments

What a serious final version would measure.

Memory compression ablation

Compare no compression, extractive compression, and retrieval-augmented compression across long tasks.

Routing ablation

Measure latency, failover success, and cost across single-endpoint and multi-endpoint deployments.

Trace training ablation

Check whether trace-derived fine-tuning improves tool choice, answer quality, or both.

15. Demo commands

The shortest path from paper to doing something useful.

python -m llm_foundry demo --provider qwen --model Qwen/Qwen2.5-0.5B-Instruct --prompt "Hello"
python -m llm_foundry proof --provider qwen --model Qwen/Qwen2.5-0.5B-Instruct
python -m llm_foundry super-suit --api-endpoints-file endpoints.json --api-strategy failover --task "Do the whole workflow"

16. Conclusion

What the reader should remember after the noise clears.

LLM Foundry is a control plane around an LLM, not a replacement for one. Its value comes from wrapping the model with memory, compression, tools, traces, evaluation, and routing so the whole thing behaves like a system instead of a toy.

The paper draft is intentionally practical. It says what the repo already does, formalises the moving parts, and leaves enough mathematical structure for a proper final manuscript. That is better than bluff.

References and links

Where to go next if you want the source material.

Repo READMEhttps://github.com/AmSach/llm-foundry/blob/main/README.md
Usage guidehttps://github.com/AmSach/llm-foundry/blob/main/USAGE.md
Docs demohttps://github.com/AmSach/llm-foundry/blob/main/docs/index.html
Paper sourcehttps://github.com/AmSach/llm-foundry/blob/main/paper.md