Metadata-Version: 2.4
Name: fair-llm
Version: 1.0.0
Summary: Modular multi-agent AI framework with provider-agnostic LLM adapters, typed tools, ReAct planning, RAG-backed memory, and MCP support (USAFA FAIR Lab)
Author-email: Ryan R <rrabinow@uccs.edu>, Austin W <austin.w@ardentinc.com>, Eli G <elijah.g@ardentinc.com>,  Chad M <Chad.Mello@afacademy.af.edu>
License-Expression: MIT
Project-URL: Homepage, https://pypi.org/project/fair-llm/
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.md
Requires-Dist: httpx<1,>=0.28.1
Requires-Dist: pydantic<3,>=2.12
Requires-Dist: pyyaml>=6.0
Provides-Extra: openai
Requires-Dist: openai<4,>=1.60; extra == "openai"
Provides-Extra: anthropic
Requires-Dist: anthropic<2,>=1.0; extra == "anthropic"
Provides-Extra: gemini
Requires-Dist: google-genai<3,>=1.50.1; extra == "gemini"
Provides-Extra: local
Requires-Dist: accelerate>=1.0; extra == "local"
Requires-Dist: packaging>=23.0; extra == "local"
Requires-Dist: torch>=2.6; extra == "local"
Requires-Dist: transformers<6,>=5.6; extra == "local"
Provides-Extra: huggingface
Requires-Dist: fair-llm[local]; extra == "huggingface"
Provides-Extra: grammar
Requires-Dist: fair-llm[local]; extra == "grammar"
Requires-Dist: xgrammar>=0.2.0; extra == "grammar"
Provides-Extra: rag
Requires-Dist: chromadb>=1.5.3; extra == "rag"
Requires-Dist: faiss-cpu>=1.9; extra == "rag"
Requires-Dist: numpy>=1.26; extra == "rag"
Requires-Dist: sentence-transformers>=5.2; extra == "rag"
Provides-Extra: documents
Requires-Dist: openpyxl>=3.1; extra == "documents"
Requires-Dist: pandas>=2.2; extra == "documents"
Requires-Dist: pdf2image>=1.17; extra == "documents"
Requires-Dist: pdfplumber>=0.11; extra == "documents"
Requires-Dist: pillow>=10.4; extra == "documents"
Requires-Dist: pytesseract>=0.3.10; extra == "documents"
Requires-Dist: python-docx>=1.1; extra == "documents"
Requires-Dist: python-pptx>=1.0; extra == "documents"
Provides-Extra: mcp
Requires-Dist: mcp<2,>=1.30; extra == "mcp"
Provides-Extra: math
Requires-Dist: sympy>=1.13.1; extra == "math"
Provides-Extra: all
Requires-Dist: fair-llm[anthropic,documents,gemini,grammar,local,math,mcp,openai,rag]; extra == "all"
Provides-Extra: test
Requires-Dist: matplotlib>=3.10.3; extra == "test"
Requires-Dist: pytest>=9.1.1; extra == "test"
Requires-Dist: pytest-asyncio>=1.4.0; extra == "test"
Requires-Dist: pytest-cov>=7.1.0; extra == "test"
Requires-Dist: pytest-xdist>=3.8.0; extra == "test"
Requires-Dist: aiohttp>=3.12.13; extra == "test"
Requires-Dist: httpx2>=2.13.1; extra == "test"
Requires-Dist: jsonschema>=4.24.0; extra == "test"
Requires-Dist: psutil>=7.2.2; extra == "test"
Requires-Dist: typing-extensions>=4.16; extra == "test"
Requires-Dist: ruff==0.16.8; extra == "test"
Requires-Dist: pip-audit>=2.10.1; extra == "test"
Requires-Dist: uv>=0.12.17; extra == "test"
Requires-Dist: twine>=6.2.0; extra == "test"
Requires-Dist: pyright[nodejs]==1.1.411; extra == "test"
Requires-Dist: starlette>=1.6; extra == "test"
Requires-Dist: uvicorn>=0.34; extra == "test"
Dynamic: license-file

# **FAIR-LLM: A Flexible, Agnostic, and Interoperable Reasoning Framework**

FAIR-LLM is a Python framework designed to accelerate the development of powerful, consistent, and modular agentic applications. It provides a structured, interface-driven architecture that allows developers to easily build and customize agents with sophisticated reasoning capabilities, long-term memory, and collaborative multi-agent systems. Crafted to help engineers build powerful AI systems without vendor lock-in.

## **Core Principles**

The FAIR framework is built on four core principles that guide its architecture and empower developers:

  * **Flexible**: The framework is highly modular. Every core component is built upon an abstract interface, allowing developers to easily swap implementations (e.g., swapping a `WindowCompactor` for a `SummarizingCompactor`) without altering the agent's core logic.
  * **Agnostic**: You are not locked into a single LLM provider. The Model Abstraction Layer (MAL) enables seamless switching between different models - from OpenAI, Anthropic, and Google Gemini to local models via HuggingFace or Ollama - ensuring you can always use the best tool for the job.
  * **Interoperable**: Components are designed to work together seamlessly. A standardized set of data structures, like the `Message` and `Document` types, ensures that data flows consistently between the agent's session log, planner, and tools.
  * **Reasoning**: At its heart, the framework is built to support sophisticated reasoning patterns. The `ReActPlanner` allows agents to "think" step-by-step to solve complex problems, and the architecture is extensible enough to support more advanced paradigms like "Plan-and-Execute".

## **Key Features**

  * **Advanced Agent Patterns**: Built-in support for the powerful **ReAct (Reason+Act)** cognitive cycle. One planner, `ReActPlanner`, takes its reply format and its per-turn action count as settings: `reply_format=ReplyFormat.JSON_ACTION` (the default, one JSON object per reply, for models like GPT-4 and Claude) or `reply_format=ReplyFormat.KEY_VALUE` (`Thought:` / `Action:` / `tool_name:` / `tool_input:` lines, for smaller or local models that may struggle with strict JSON), and `max_actions_per_turn` (1 by default; a JSON planner with a count above 1 reads several tool calls from one reply).
  * **Multi-Agent Collaboration**: Orchestrate teams of specialized agents with workers-as-tools fan-out. `WorkerAgentTool` wraps any agent as a typed tool and `build_worker_manager` wires a manager that delegates independent sub-tasks concurrently in a single turn, enabling the system to tackle complex, multi-faceted problems.
  * **Retrieval-Augmented Generation (RAG)**: Easily ground agents in your own documents and data. The framework includes all necessary components for a robust RAG pipeline, including document loaders, text splitters, embedders (`SentenceTransformerEmbedder`), and two queryable vector store backends (`FaissVectorStore` and `ChromaDBVectorStore`) made available to the agent through the `RAGQueryTool`. Retrieved hits are numbered `[S1]..[Sn]` with a cite-only instruction; the tool accumulates a session-scoped `grounded_context` so answers can be verified after multiple retrieves. `CitationVerifier` then checks generated citations and reports a fabrication rate that distinguishes `not_found` from `could_not_check` and `source_unreachable`. External locator lookup is an optional `SourceLookup`, a plain async function. See `demos/rag/demo_two_sided_grounding.py`. FAISS is the recommended default backend.
  * **Pluggable Model Support**: The **Model Abstraction Layer (MAL)** features concrete adapters for **OpenAI**, **Anthropic**, **Google Gemini**, **HuggingFace Transformers**, **Ollama** (local models), and **LoadBalancerAdapter** (distributed vLLM inference clusters), allowing for unparalleled flexibility in model selection and deployment topology.
  * **Modular & Extensible by Design**: Every core component (model adapter, tools, planner, session store, compactor) is defined by an abstract base class in the `core/interfaces/` directory. This interface-driven design makes the framework easy to extend and customize.
  * **Prompt Engineering System**: A first-class prompt engineering system lives in `core/prompts/`, providing composable building blocks: `PromptBuilder`, `RoleDefinition`, `FormatInstruction`, `Example`, `ToolInstruction`, and more. Planners merge their own mandatory format instructions with the application content these blocks provide, so prompt content and parse format cannot drift apart.
  * **MCP (Model Context Protocol) Integration**: A full `modules/mcp/` package provides first-class support for MCP tool servers. Agents can combine local FAIR tools with tools from any MCP-compatible server (stdio, SSE or Streamable HTTP transport, with a bearer token and extra headers on the HTTP transports) by passing `MCPToolSource([MCPServerConfig(...)])` to `ToolRegistry.add_source`, beside any tools registered locally. fairlib connects at the start of each run and closes at its end. MCP connections are configured in code through `MCPServerConfig`.
  * **Streaming Responses**: Opt-in end-to-end token streaming through the agent loop. Enable `streaming.enabled` (or pass `stream=True` to a planner or `SimpleAgent`) and every model call is consumed incrementally and published as typed events (`ModelStreamStartEvent`, `ModelStreamChunkEvent`, `ModelStreamEndEvent`) on the agent event bus. A planner supplies the filter that recovers the final-answer text from its own replies (`AbstractPlanner.stream_filter()`; `ReActPlanner` gives a key-value filter for the text path of a `reply_format=KEY_VALUE` planner and a JSON filter for every other call), and that text is published as `ModelStreamAnswerEvent`, so a chat surface subscribes to it and builds no filter; a planner whose replies hold no answer region supplies none, and the surface prints the returned answer. The run's return value is unchanged. See `demos/events/demo_streaming_agent.py`.
  * **Secure by Design**: The `SecurityManager` screens input, enforces opt-in capability grants and an egress allowlist, runs the `Authorizer` policies an application gives it (`SecurityManager(authorizers=)`, or `agent.arun(..., authorizers=)` for one run and its workers) before those checks, where any `Deny` is final, frames a refused call to the model as a refusal rather than a failure, and runs tools and model-written code in child processes: a tool declares `IsolationLevel.BOUNDED` to run under compute bounds, or `IsolationLevel.ISOLATED` to run in a child confined by Landlock and seccomp on Linux, and `arun_bounded` runs an application's own compute that is not a tool at the level it asks for. `ShellTool` runs every command, and `CodeExecutionTool` and `RunPythonTool` every run of a file, at the isolated level through the call's workspace. See [Security](#security).
  * **Reliable Structured Output**: Comes with patterns and demos (see `demo_arun_validator.py`) for compelling LLMs to return clean, Pydantic-validated JSON, which is essential for reliable data extraction and tool integration.
  * **Agent Evaluation**: Measure your own agent on your own tasks. Write an async `AgentBuilder` of `(task, workspace)`, declare each task as a `TaskSpec` with an async `Checker` that reads a `CheckContext` after the run and answers a `CheckResult`, and `arun_cell` runs them as one cell: a new agent for every run, every count read from the typed events on the agent's own bus, and the evidence written per task and per call. `write_report` turns the cells into a `SUMMARY.md` table with one row per label. See [Evaluate Your Agent](#evaluate-your-agent).
  * **Agent Configuration Persistence**: Save and reload complete agent configurations - including prompt definitions, tool setup, and model settings - via utilities in `fairlib.modules.agent.factory`. Enables reproducible agent setups, team sharing, and prompt optimization workflows.

## Getting Started: Your First Agent (5-Minute Quickstart)

Follow these steps to get your first agent running.

### 1\. Prerequisites

  * Python 3.11, 3.12, 3.13 or 3.14

### 2\. Installation

> **Install warning:** This framework is published on PyPI as **`fair-llm`** (hyphen), imported in Python as **`fairlib`**. The unrelated PyPI package **`fairlib`** (0.1.0) is a different project. Always pin the correct distribution, e.g. `fair-llm==1.0.0` in `requirements.txt` or `constraints.txt`, and verify with `pip show fair-llm` before debugging import errors.

**Package name vs import name:** install with `pip install fair-llm` (hyphen). Import in Python as `import fairlib`. The unrelated PyPI package `fairlib` (0.1.0) is not this framework; pin `fair-llm==1.0.0` in `constraints.txt` to avoid the footgun.

Use a virtual environment.

#### Use fairlib in a project

You want to build on the framework: install the published package, no clone needed.

The base install is what fairlib's core imports: `httpx`, `pydantic` and `pyyaml`. It runs the agent loop, the planners, the built-in tools, the security manager, the conformance suites and the `OllamaAdapter` and `LoadBalancerAdapter`. Every other backend is an extra; a feature whose extra is not installed raises `MissingExtraError` naming the extra (its `extra` field) when it is imported or constructed.

```bash
pip install fair-llm                  # the base: Ollama, the load balancer, the agent loop
pip install "fair-llm[openai]"        # + OpenAIAdapter
pip install "fair-llm[anthropic]"     # + AnthropicAdapter
pip install "fair-llm[gemini]"        # + GeminiAdapter
pip install "fair-llm[local]"         # + HuggingFaceAdapter (local models)
pip install "fair-llm[grammar]"       # + constrained decoding for local models
pip install "fair-llm[rag]"           # + vector stores, embedders, rerankers
pip install "fair-llm[documents]"     # + DocumentProcessor (PDF, Office, images)
pip install "fair-llm[mcp]"           # + Model Context Protocol client and server
pip install "fair-llm[math]"          # + AdvancedCalculusTool
pip install "fair-llm[all]"           # every extra above
```

Extras combine: `pip install "fair-llm[openai,rag]"`. `from fairlib import *` resolves every exported name, so it needs `fair-llm[all]`; on a smaller install it raises `MissingExtraError` naming a missing extra, and importing the names you use (`from fairlib import SimpleAgent`) needs only their extras.

| Extra | Installs | For |
|-------|----------|-----|
| `openai` | openai | `OpenAIAdapter` |
| `anthropic` | anthropic | `AnthropicAdapter` |
| `gemini` | google-genai | `GeminiAdapter` |
| `local` | torch, transformers, accelerate | `HuggingFaceAdapter` |
| `huggingface` | the `local` extra | an alias of `local` |
| `grammar` | the `local` extra and xgrammar | constrained decoding on `HuggingFaceAdapter` |
| `rag` | chromadb, faiss-cpu, numpy, sentence-transformers | `ChromaDBVectorStore`, `FaissVectorStore`, `SentenceTransformerEmbedder`, `CrossEncoderRerankingRetriever` |
| `documents` | pdfplumber, pdf2image, pytesseract, pillow, python-docx, python-pptx, pandas, openpyxl | `DocumentProcessor` |
| `mcp` | mcp | `MCPToolSource`, `MCPServer` |
| `math` | sympy | `AdvancedCalculusTool` |
| `all` | every extra above | everything |

Dependencies are version ranges, not pins, so fair-llm installs beside the versions your project already uses; your own lock file pins the environment. What the 1.x releases keep stable, and how a deprecation is announced, is in the versioning and deprecation policy (docs/VERSIONING.md in the source distribution).

Note: `pdf2image` and `pytesseract` also need the `poppler` and `tesseract`
system binaries, which pip cannot install (for example
`apt install poppler-utils tesseract-ocr`).

#### Develop fairlib

You want to change the framework itself: from a checkout of the source,
install it editable, so edits under `fairlib/` are live in your environment,
with every extra and the test tools. The locked environment CI uses:

```bash
cd fair_llm
uv sync --extra all --extra test          # the versions in uv.lock, into .venv
```

or, with pip, the declared ranges:

```bash
python -m venv .venv && source .venv/bin/activate
pip install -e ".[all,test]"
```

Any extra gives a lighter development install (`-e .`, `-e ".[openai]"`,
`-e ".[rag,test]"`). `pyproject.toml` declares the ranges and `uv.lock` holds
the resolved environment. `requirements.txt` is generated from `uv.lock` by
`make requirements` and is never hand-edited.

**Capability enforcement is opt-in by design:** `SecurityManager(LocalWorkspace())` leaves
grants unenforced. Pass `capability_bag=CapabilityBag()` to deny every tool,
path, host, and model, then grant only the resources your application needs,
or list the grants under `security.grants` in `settings.yml` and build the
manager with `SecurityManager.from_settings(settings, LocalWorkspace())` (`grants: {}` is
the deny-all bag; `grants: null`, the shipped value, enforces none).
This is the deliberate 1.0 default; changing it requires a major version.
See the copyable secure agent configuration (docs/SECURITY.md), the threat
model (docs/THREAT_MODEL.md), and the design record
(docs/design/0001-capability-enforcement-default.md), all in the source
distribution.

**Network egress allowlist:** `SecurityManager(LocalWorkspace(), allowed_egress=...)` and tool
`network_egress` declarations validate declared targets only. This is NOT a network
sandbox: a destination a tool takes from its input is not checked against the
allowlist or the capability bag. Without a capability bag or an allowlist, egress
checks permit all targets.

Configure the allowlist in YAML (`security.allowed_egress`) or at construction:

```python
from fairlib import LocalWorkspace, SecurityManager, settings

security = SecurityManager.from_settings(settings, LocalWorkspace())
```

Or pass `allowed_egress=settings.security.allowed_egress` explicitly.

#### Install troubleshooting

If `import fairlib` fails or imports an unexpected API, verify you installed the **correct PyPI distribution**:

```bash
pip show fair-llm    # must show Name: fair-llm and your pinned version
python -c "import fairlib; print(fairlib.__version__)"
```

Common mistakes:

- `pip install fairlib` installs an **unrelated** 0.1.0 project on PyPI, not this framework.
- Installing an application without its constraints file can miss the application's `fair-llm` pin. An application that pins `fair-llm` in a root `constraints.txt` installs with `pip install -r requirements.txt -c constraints.txt` so the pin is honored.
- A feature raises `MissingExtraError`: install the extra it names (`exc.extra`), for example `pip install "fair-llm[rag]"`.

### 3\. Configuration

The framework uses a centralized YAML configuration file for API keys and model settings.

1.  Either edit the packaged file at `fairlib/config/settings.yml`, **or** set `FAIR_LLM_SETTINGS` to a consumer-owned YAML path, **or** call `configure_settings(path=...)` to replace the module singleton, **or** pass explicit kwargs when constructing adapters. Whoever controls the process environment controls which YAML is loaded (including security-related fields); parsing uses `yaml.safe_load` only.
2.  Add your API keys (e.g., for OpenAI, Anthropic, or Gemini).
3.  Review the model definitions and other settings (RAG paths, security) to suit your environment.
4.  To change a few settings for one block of code, such as a test or a demo run, wrap it in `settings_overlay({"limits.orchestration.max_attempts": 3})`: the values are validated, applied to the live settings for the block, and restored when it ends.

#### Local Ollama + key-value replies

`ReActPlanner(llm, registry, reply_format=ReplyFormat.KEY_VALUE)` asks for a simplified key-value reply (`Thought:`, `Action:`, `tool_name:` and `tool_input:` lines) for smaller local models that struggle with strict JSON; it takes one action per turn. The agent loop tolerates consecutive `PlannerParseError` failures up to `SimpleAgent(max_parse_attempts=...)` (default 2 total parse tries before abort). Retryable transient `READ_ONLY` / `EXTERNAL_READ` tool failures can be retried within a turn via `SimpleAgent(max_tool_retries=...)` (default 0; set to a positive value to enable). `EXTERNAL` failures are never auto-retried.

| Model | Typical outcome with `reply_format=KEY_VALUE` |
|-------|----------------------------------------|
| `qwen2.5:14b` | Reliable KV compliance; completes chat turns and invokes tools correctly |
| `llama3.2` (3B) | Usually completes turns; occasional malformed KV fields |
| `llama3:8b`, `llama3.1:8b` | **Not supported** for interactive agent chat - exhaust `max_parse_attempts` and abort on typical first messages; format compliance tracks the model's instruction tuning, not its parameter count |
| `llama3.2:1b` | **Not recommended** - often fails KV parse on first attempt; may recover on parse retry but remains unreliable for capstone agent chat |
| `deepseek-r1:7b` | Generally usable when Ollama serves the model reliably |

**1B models:** Do not rely on `llama3.2:1b` (or similar 1B checkpoints) with `reply_format=KEY_VALUE` for capstone-style agent chat. They lack reliable KV compliance; a parse retry may recover on attempt 2 but aborts are still common. Prefer **3B+** for local agent loops, or keep the default **`reply_format=JSON_ACTION`** with a cloud model when format compliance is critical.

**3B tool_input mangling:** Small models sometimes write tool_input as field=value or field: value text (`path=run_checks.py start_line=1`). No planner reads such text into the tool's fields. On a call the model is not constrained on (the text path: a model that does not declare `response_schema`, a declined call, or `planner.constrained_decoding: false`), `ReActPlanner` reads exactly one JSON object as tool_input in either reply format (a key-value reply carries it on the `tool_input:` line) and refuses anything else - field text, bare text, a fence, text after the object - with a `PlannerParseError` the agent's retry sends back to the model with the tool's schema hint. The executor takes a dict, a model, or JSON text holding exactly one object, and refuses with the schema hint anything else (bare text, a fence, a JSON string literal), a key the schema does not declare, and any input that fails the schema. A tool call whose model call reports `done_reason` LENGTH (cut off by the output budget) is refused by the agent, never run; a model whose stream reports no usage cannot be judged. Direct `tool.acall` smoke tests still do not exercise the chat path - validate with a live model when format matters.

Recommendations: prefer **3B+** models for interactive agent chat; use the default **`reply_format=JSON_ACTION`** with cloud models when format compliance is critical; increase `max_parse_attempts` if you accept longer re-prompt loops on borderline models. Validate chat-path behavior separately from tool-only smoke tests.

### 4\. Run Your First Agent

The following code assembles and runs a simple agent that can use a calculator. Save it as `main.py` in the root of the project directory.

```python
# main.py
import asyncio
from fairlib import (
    settings,
    ChatModel,
    OpenAIAdapter,
    ToolRegistry,
    SimpleCalculatorTool,
    ToolExecutor,
    ReActPlanner,
    SimpleAgent,
)


async def main():
    print("Initializing a single agent...")

    # 1. The "Brain": Initialize the LLM adapter from the settings file
    llm = ChatModel(
        OpenAIAdapter(
            api_key=settings.api_keys.openai_api_key,
            model_name=settings.models["openai_gpt4"].model_name,
        )
    )

    # 2. The "Toolbelt": Create a registry and add tools
    tool_registry = ToolRegistry()
    tool_registry.register_tool(SimpleCalculatorTool())

    # 3. The "Hands": Create an executor that uses the toolbelt
    executor = ToolExecutor(tool_registry)

    # 4. The "Mind": Create the planner that uses the brain and tools
    planner = ReActPlanner(llm, tool_registry)

    # 5. Assemble the Agent: Combine all parts into a functional unit. The
    # agent keeps the conversation in a session log of its own.
    agent = SimpleAgent(llm=llm, planner=planner, tool_executor=executor)
    print(" Agent created. Ask a math question or type 'exit'.")

    # 6. Run the agent in a loop
    while True:
        try:
            user_input = input("\n You: ")
            if user_input.lower() == "exit":
                break
            response = await agent.arun(user_input)
            print(f" Agent: {response}")
        except KeyboardInterrupt:
            break


if __name__ == "__main__":
    asyncio.run(main())
```

Run the agent from your terminal:

```bash
python main.py
```

## Evaluate Your Agent

An evaluation runs your agent on tasks you declare and records what happened. You write one async function, an `AgentBuilder` of `(task, workspace)`, and list each task as a `TaskSpec`: the prompt the agent receives and a `Checker`, an async function that decides success after the run (the agent never sees it). It reads a `CheckContext` (the final answer, the run's workspace and its trace), takes a file from the workspace with `await context.read_text(path)`, and answers a `CheckResult`, whose optional `score` and `reason` are kept as evidence. `arun_cell` builds a new agent for every run of a task, counts the typed events the run publishes on the agent's own bus (`agent.events`), and writes the cell's evidence (`tasks.jsonl`, `calls.jsonl` and `cell.json`) under `out_dir/<label>/rep1`. `write_report(out_dir)` writes `SUMMARY.md`, one row per label and condition. A variant is a second builder, or a `settings_overlay` entered around the call.

```python
import asyncio
from pathlib import Path

from fairlib import (
    AbstractAgent,
    AgentBuilder,
    ChatModel,
    CheckContext,
    CheckResult,
    HuggingFaceAdapter,
    ReActPlanner,
    SimpleCalculatorTool,
    SimpleAgent,
    TaskSpec,
    ToolRegistry,
    arun_cell,
    settings_overlay,
    write_report,
)


async def change_is_correct(context: CheckContext) -> CheckResult:
    """The verdict, read after the run; the agent never sees it."""
    return CheckResult(passed="49" in context.answer)


def calculator_agents(llm) -> AgentBuilder:
    async def build(task: TaskSpec, workspace: Path) -> AbstractAgent:
        registry = ToolRegistry()
        registry.register_tool(SimpleCalculatorTool())
        planner = ReActPlanner(llm, registry)
        return SimpleAgent(llm=llm, planner=planner)

    return build


async def main() -> None:
    llm = ChatModel(
        HuggingFaceAdapter("qwen25-7b", do_sample=False), options={"max_tokens": 512}
    )
    prompt = (
        "A notebook costs 3 dollars and a pen costs 1 dollar. "
        "How much change do you get from 60 dollars after buying 3 notebooks and 2 pens?"
    )
    tasks = [TaskSpec(task_id="change", prompt=prompt, check=change_is_correct)]
    out = Path("evaluation_out")
    cell = await arun_cell(
        calculator_agents(llm), tasks, out_dir=out, label="calculator"
    )
    with settings_overlay({"planner.constrained_decoding": False}):
        await arun_cell(calculator_agents(llm), tasks, out_dir=out, label="text-path")
    print(cell.successes, "of", len(cell.tasks), "tasks passed")
    print("evidence in", cell.directory)
    write_report(out)


if __name__ == "__main__":
    asyncio.run(main())
```

## Security

Network egress policy is opt-in and layered; it is **not** a sandbox.

**What the allowlist checks:** the static `network_egress` tuples declared on each tool.
The declared tuples are checked before dispatch whatever `reaches_network` says;
`reaches_network=True` with no declaration is refused while an allowlist is configured.

**`SideEffect.EXTERNAL_READ`:** idempotent network reads
may run concurrently when `tool_dispatch.parallel_read_only` is enabled. Tools must
use async I/O (or `asyncio.to_thread` for blocking clients) or parallelism only
schedules overlap without speeding up blocking calls.

**Shipped tools:** grading tools derive
egress from the injected MAL adapter; `WorkerAgentTool` is in-process by default (`reaches_network=False`);
MCP adapters over an HTTP transport (SSE, Streamable HTTP) declare the server's host and port (stdio MCP uses
`VERIFIED_NO_AGENT_SIDE_EGRESS`).

**Compensating controls you still need:** OS/network firewalls, secret management,
MCP server trust boundaries, isolation for the tools that run in-process or at
the bounded level (see below), and reviewing tool implementations for undeclared
outbound calls. Multi-agent setups give each level's `ToolExecutor` a
`security_manager` (`build_worker_manager` forwards the manager's policy recursively to nested
worker executors).

**A host a tool learns while running** is held to the bag and the allowlist by
`context.security.check_egress(host, port)`, which the tool calls before it
connects; `context.security` is None with no manager bound and in a bounded child.

### Authorizers and refused calls

An `Authorizer` decides each tool call: `Allow(arguments=None)`, `Deny(reason,
ends_run=False)` or `Ask(prompt)`. `SecurityManager(authorizers=[...])` applies
to every run under the manager, and `agent.arun(goal, authorizers=[...])` to one
run and the runs its tools open. The chain runs after input validation and
before the manager's capability, budget, input-screen and egress checks; any
`Deny` is final, a decision is held per call id for the run, and each dispatch
that reaches the chain emits one `AuthorizationEvent`, a retry of a held call
too. An `Ask` nobody denied goes to a person through
`SecurityManager(input_channel=)`: No is a deny, all Yes runs the call; with
no channel or no answer a top-level call pauses and a delegated one is
denied. A paused `arun` returns `NeedsInput`, `session_log.pending` reads what
waits, and `arun(ResumeInput(responses))`, in this process or a later one over
the same session store, carries the run on; `session_log.abandon(reason)` ends
it instead. `JobRunner` parks a queued job that pauses, and the claim after
`WorkQueue.resume` carries it on with the answers. A refused call reads to the
model as "The call to tool 'x' was refused: <reason> It has no result, and the
same call will be refused again.", and a call that ran and failed as "Error in
tool 'x': ... The call did not work, and there is no result from it." See
docs/SECURITY.md.

### The input screen and taint

An `InputScreen` is an async function from a text to a `Verdict`, passed as
`SecurityManager(workspace, input_screen=screen)`. The one screen judges each
tool input (as JSON), each user turn and each tool result. A `Perception`
passed as `SimpleAgent(perception=)` turns what `arun` is given into the user
turn before the screen reads it and before anything is stored, so redaction
belongs there. A manager given
none screens tool input with `default_input_screen` and nothing else, since
hardening is opt-in. A rejected user turn raises `InvalidAgentInputError`
before the run starts and writes nothing; a rejected tool result reads to the
model as "The call to tool 'x' ran, but its result is withheld: it holds
text the security screen does not allow.", with an `ObservationWithheldEvent`.

`Taint` (`CLEAN` < `UNKNOWN` < `UNTRUSTED`) says how far the text in a run's
context can be trusted, and a policy reads it as `request.taint`. A tool's
results are `UNTRUSTED` unless its class declares `output_taint =
Taint.CLEAN`; the session log keeps each record's taint, the agent passes the
strongest its view reads to each dispatch, and a loop that passes none reads
`UNKNOWN`. See docs/SECURITY.md.

### Bounded and isolated runs

A tool declares where it runs; the executor's security manager runs it there.
`isolation = IsolationLevel.BOUNDED` runs the tool in a child process held to
the `limits.compute` bounds (CPU, address space, wall clock, output, per-file
size, and the task count) once some `limits.compute` bound is set; with every
bound 0, the default, it runs in-process. That child runs as the same user and
is a resource bound, not isolation: it is for fairlib's own compute, never
model-written code.
`isolation = IsolationLevel.ISOLATED` runs the tool in a confined child. What
the level promises, on every backend that declares it: the child reads only the
interpreter, its libraries, the code it runs and the programs the tool declares
in `executables`, writes only its own working directory, changes no file's
mode, owner, times or extended attributes, opens no network or listening socket
(only a connected Unix stream pair), reads no `/proc`, signals nothing outside
its own process group, leaves no process alive once its run has returned, and
cannot raise its dumpable flag. The workspace suite's escape rows, one for each
of those clauses, hold a backend to them. `LocalWorkspace` confines with
Landlock and seccomp and promises more of its own, which its own tests hold:
it grants the fairlib packages but never `fairlib/config/`, and its child
uses no System V IPC and changes the limits, priority or scheduling of no
process but itself. Its settings are a key-free file the parent writes, so no
API key reaches it. A tool whose body runs in an isolated child is rebuilt
there from its own module, which on `LocalWorkspace` may import the standard
library, installed libraries and fairlib's `core`, `modules` and `utils`, so a
tool's `check_conformance` call lives in another module.

```python
import asyncio

from fairlib import IsolationLevel, LocalWorkspace, SecurityManager, settings

manager = SecurityManager.from_settings(settings, LocalWorkspace())
print(manager.available_levels())  # the levels this host reaches
result = asyncio.run(
    manager.arun_bounded(
        "my_app.compute:total",  # a function registered with bounded_entry_point
        {"rows": [1, 2, 3]},
        required=IsolationLevel.ISOLATED,
    )
)
answer = result.value if result.completed else result.raised.text
```

- Compute that is not a tool is `SecurityManager.arun_bounded`: it runs a
  function registered with `bounded_entry_point`, named `package.module:function`,
  in a child at the level `required` names, and refuses rather than run at a
  weaker one. Its arguments cross as plain JSON data; the JSON value it returns
  is `result.value`, and files it writes at the top of its working directory
  come back as `result.artifacts`.
- Model-written code runs only at `ISOLATED`, through a code tool
  (`RunPythonTool`, `CodeExecutionTool`): its driver reads that level in the
  child and refuses below it, and `LocalWorkspace`'s child proves from the
  kernel that it is confined before anything runs.
- `SecurityManager(workspace)` takes an `AbstractWorkspace`, where a bounded
  run executes, as its first required argument; `LocalWorkspace` is this host's. A backend
  implements `isolation` and `exec`, and fairlib's `ManagedWorkspace` drives it.
  Its levels are what `available_levels` answers. Prove a backend of your own
  with `await check_conformance(WorkspaceCase(make=MyWorkspace))` and pass it
  as `SecurityManager(MyWorkspace())`; `MinimalWorkspace`, in
  `fairlib.conformance.partners`, is the least a backend can be (`BOUNDED` alone)
  and a starting copy, and the suite's rows for the isolated level read not
  applicable on a backend that does not declare it.
- A tool that runs a program declares `exec_isolation` and awaits
  `context.workspace.exec(argv)`: the executor hands it a driver over its manager's
  workspace, bus, bag and bounds, and with no manager one that refuses. A tool
  declaring both `isolation` and `exec_isolation` is refused with
  `ConfigurationError` when it first becomes visible in a run, and so is one declaring
  `reads_host`, `isolation` or `path_grants` on a backend whose
  `Isolation.fairlib_inside` is False.
- `ISOLATED` runs on Linux x86_64 with Landlock ABI 4 or later (kernel 6.7+)
  and seccomp. Everywhere else, and on aarch64 until it is verified, a run that
  requires it raises `SandboxUnavailableError`, and a run that registers
  `ShellTool`, `RunPythonTool` or `CodeExecutionTool` under a security manager
  ends with it at run entry, before any model call; it never runs at a weaker
  level or in-process. `BOUNDED` runs on Linux only.
- At `ISOLATED` a tool reaches the host paths its `path_grants` declares,
  each a kernel rule: a rooted file tool such as `ReadFileTool(root=...)`
  declares its root (read, and written by a mutating tool such as `ShellTool`
  or `WriteFileTool`). Without a bag the declaration alone applies. A manager
  that holds a `CapabilityBag` carries it into the child, and its path
  prefixes are the ceiling each tool's declaration is cut to: the tool gets
  the intersection of the two, never more than either. A granted path must
  exist; a missing one is refused with `ConfigurationError` before any child
  starts.
- The whole package directory of an isolated tool's module is readable by the
  child; keep secrets out of that package.
- `limits.compute.max_tasks` bounds the processes AND threads of the child's
  tree through a `systemd-run --user --scope`; it needs a user systemd session
  with the pids controller (a login session, or lingering for a service
  account), and without one a run with it set raises `SandboxUnavailableError`
  before any child starts. `limits.compute.file_bytes` bounds each file the
  child writes, not the total.
- A tool's `executables` names the host programs its isolated child may
  execute beyond the interpreter. It is a read and execute grant, not an
  allowlist of what the child runs: a program the child runs, or writes and
  runs, is confined like the child. Each name is looked up on a fixed search
  path (the interpreter's directory, then `/usr/local/bin`, `/usr/bin`,
  `/bin`), never the agent's `PATH`, and one that does not resolve refuses the
  run before any child starts, naming it. `python3` and `python` start the
  running interpreter as it was started, whatever its directory holds; where
  its directory's entry of the name is missing or another program, the child
  starts it through a script in its work directory, which needs `TMPDIR` on a
  mount that allows execution. A dispatch whose write grants hold what a child starts from or a declared
  program's lookup reads (the interpreter, its libraries, fairlib, the task
  scope launcher, a declared program or a link on its way) is refused before
  the child starts; grant a scratch copy. `current_isolation()` (in
  `fairlib.core.security_context`) returns the level the running code is
  confined under: the achieved level inside a child, `None` in-process.
- The executor refuses a tool instance whose `isolation` does not satisfy
  the level its class declares, with `SandboxUnavailableError`; an instance
  may raise its class's level, never lower it.
- `ShellTool(root, *, executables=DEFAULT_SHELL_EXECUTABLES)` declares
  `exec_isolation` as `ISOLATED`, its programs and its root, and runs every
  command as `sh -c` by `context.workspace.exec` with its root as the working
  directory. It needs an executor whose manager's workspace reaches `ISOLATED`;
  under a bag, one granting `shell.exec`, the agent's model and its root, and
  a root the bag leaves ungranted is refused before anything runs. The
  command writes only its root, cut to the bag's path prefixes. `DEFAULT_SHELL_EXECUTABLES` (exported from `fairlib`) names
  the common coreutils, grep, sed, find and diff programs and the
  interpreter; add one with `ShellTool(root, executables=(*DEFAULT_SHELL_EXECUTABLES, "git"))`.
  `executables` is a tuple. Each stream keeps its first 1 MiB, clamped by
  `limits.compute.output_bytes`, and a longer one ends with
  `[output truncated: the first N bytes are kept]`; the call still succeeds.
  A wall, the call's timeout or a `limits.compute` one, the manager's
  `compute_bounds` or an entry named `shell` under `bounded_tools` or
  `limits.compute.tools`, ends the command and everything it started and
  returns the partial output marked timed out; `kill 0`, and the `timeout`
  command when declared and it fires, end the command with exit -15 and keep
  its output. Output a background process writes after the command's
  foreground exits is lost. Commands that change file metadata (touch, chmod,
  cp -p) fail.
- `CodeExecutionTool(root, wall_seconds=...)` runs a pytest test file of
  `root`, named by the model as a path relative to `root`, as
  `python -m pytest <test_file>` would from `root`, in an isolated child:
  the tool runs fairlib's pytest driver through
  `context.workspace.run_entry_point` at `IsolationLevel.ISOLATED`, and the
  driver checks its own confinement, so the tool needs fairlib's isolated
  worker. The test imports the code
  under test by its own module name (`from solution import add` for
  `solution.py`). It returns a `CodeTestReport` (`exit_code`, `passed`,
  `stdout`, `stderr`, `timed_out` and the counts `tests_collected`,
  `tests_passed`, `tests_failed`, `tests_skipped`). It is `passed` only when
  pytest exited 0 and every collected test ran and passed; a skipped or
  expected-failure test is not a pass. The grade is what the confined run
  reports, not a tamper-proof one, because the code under test shares the
  interpreter with pytest and the driver.
- `RunPythonTool(root, wall_seconds=...)` runs a file of `root` as a script,
  as `python <file>` would from `root`, in an isolated child and returns its
  exit code, its output and whether it timed out. The script can import the
  modules beside it and read the files of `root`.
- A code tool's run stopped at its wall returns `timed_out` with an empty
  `stdout`, and a `stderr` holding a note naming the bound after what reached
  the child's descriptors directly (a script's `os.write`, not pytest's
  captured output): what the script printed through `sys.stdout` and
  `sys.stderr`, and the report pytest was building, are lost with the child.
- Both code tools read every file of `root` in the agent's process and send
  their contents to the child, which is never granted `root`: the run works on
  copies and cannot change the files there. `wall_seconds` is required and
  greater than 0, so a run that loops forever always returns; the manager's
  `compute_bounds=`, `limits.compute` and an entry named for the tool under
  `bounded_tools=` or `limits.compute.tools` tighten it. Under a
  capability bag, the bag grants `root`'s paths, as it does for the file
  tools.
- `GradeCodeFromRubricTool(llm, root)` and `GradeEssayFromRubricTool(llm, root)`
  read the rubric, the submission and each review from files of `root`, named
  by the model as paths relative to it (`rubric_file`, `code_file` or
  `essay_file`, and one field per review), and grade with `llm`. A file that
  does not exist yet, such as a review not written, is a typed failure naming
  it that the model reads as an observation.
- The application fills `root` (a case folder of a submission, its tests, a
  rubric and the reviews other agents write, for example) and the model names
  files in it:

  ```python
  case = Path(tmp)  # the application writes solution.py, test_solution.py here
  registry.register_tool(RunPythonTool(case, wall_seconds=30))
  registry.register_tool(CodeExecutionTool(case, wall_seconds=60))
  registry.register_tool(GradeCodeFromRubricTool(llm, case))
  executor = ToolExecutor(
      registry, SecurityManager.from_settings(settings, LocalWorkspace())
  )
  ```

See docs/SECURITY.md and docs/THREAT_MODEL.md in the source distribution for
the full boundary.

Point the framework at your own config instead of the packaged `settings.yml`:

```bash
export FAIR_LLM_SETTINGS=/path/to/your/settings.yml
```

Or construct adapters with explicit kwargs and skip the `fairlib.settings` singleton.

## Learn with Demos

The `demos/` directory contains executable scripts that are the best way to learn the framework's capabilities.
Each folder below holds the demos for one topic; a demo runs as `python demos/<folder>/<demo>.py` from the repository root.

### getting_started

  * `demos/getting_started/demo_single_agent_calculator.py`: The best place to start. Learn the fundamentals of building and running a single agent with a simple tool.
  * `demos/getting_started/demo_advanced_calculator_calculus.py`: Shows how to equip an agent with multiple, more complex tools.

### models

  * `demos/models/demo_huggingface_adapter.py`: Wrap HuggingFaceAdapter in a ChatModel and chat with it through ainvoke and astream.
  * `demos/models/demo_ollama_adapter.py`: Wrap OllamaAdapter in a ChatModel and chat with it through ainvoke and astream.
  * `demos/models/demo_openai_adapter.py`: Wrap OpenAIAdapter in a ChatModel and chat with it through ainvoke and astream.
  * `demos/models/demo_anthropic_adapter.py`: Wrap AnthropicAdapter in a ChatModel and chat with it through ainvoke and astream.
  * `demos/models/demo_gemini_adapter.py`: Wrap GeminiAdapter in a ChatModel and chat with it through ainvoke and astream.
  * `demos/models/demo_load_balancer_adapter.py`: Wrap LoadBalancerAdapter in a ChatModel and chat with it through ainvoke and astream.
  * `demos/models/demo_custom_chat_model.py`: Write a custom `AbstractModelAdapter` over Ollama's HTTP API with httpx, prove it with `check_conformance` and a `ModelAdapterCase`, then run a `SimpleAgent` on `ChatModel(adapter)` (Ollama, llama3.1:8b).
  * `demos/models/demo_model_manager.py`: Ask ModelManager for three roles (tutor, student, judge) and let a settings file pick each provider: a laptop file (all Ollama), a lab file (the student moves to HuggingFace), a cloud file when GEMINI_API_KEY is set (the judge moves to Gemini), and a file whose typo is refused by role name (`FAIR_LLM_DEMO_MODEL`, `FAIR_LLM_DEMO_HF_MODEL`, `FAIR_LLM_DEMO_GEMINI`).
  * `demos/models/demo_request_shape_across_routes.py`: One calculator agent on a HuggingFace, an Ollama and (when `GEMINI_API_KEY` is set) a Gemini model, where only the adapter construction names a provider, printing each route's answer and run time, each request's role sequence from `ModelRequestEvent` (the same on every route) and the digest of the action schema it carried, and the exact prompt the local models read, with the observation a user turn in position (`FAIR_LLM_DEMO_MODEL`, `FAIR_LLM_DEMO_OLLAMA`, `FAIR_LLM_DEMO_GEMINI`, optional `GEMINI_API_KEY`); last, what a model with no chat template reads (`ChatTemplateFallbackEvent`).
  * `demos/models/demo_model_capabilities.py`: Branch on what a model declares it can do, without naming its provider: images, seed, the sampling and stop options sent only where declared, and a `response_schema` checked with `response_schema_refusal` before it is sent.
  * `demos/models/demo_vision_message.py`: Ask a local vision model about an image carried on a Message.

### custom_tools

  * `demos/custom_tools/demo_response_pool_template_cycling.py`: Cycle through reply templates in order, and persist the cursor.
  * `demos/custom_tools/demo_per_run_tool_state.py`: Keep a tool's state per agent run, keyed by the run's id, with `on_run_start`, `ToolRunContext` and `ToolCallContext`.
  * `demos/custom_tools/demo_tool_catalog_and_validation.py`: One Pydantic schema writes a tool's catalog entry and validates its input, and a `ToolOutput` of your own decides, through `render()`, the observation the model reads.
  * `demos/custom_tools/demo_typed_tool_registry.py`: Scope an agent's tools to one group of a larger registry, and catch the lookups it refuses by type (`ToolLookupError` and its three kinds).

### planner

  * `demos/planner/demo_constrained_tool_input.py`: Constrained decoding on an Ollama and a HuggingFace model (`fair-llm[grammar]`): one planner step printing the action schema's digest (`ModelRequestEvent.response_schema_digest`), the raw JSON action object and the executor accepting its input, and a contrast run with `constrained_decoding=False` on the strict key-value text path (`FAIR_LLM_DEMO_MODEL`, `FAIR_LLM_DEMO_OLLAMA`).
  * `demos/planner/demo_custom_planner.py`: Write your own planner by implementing `AbstractPlanner`: `model_needs` declared, an `aplan` that gets the request on the step that answers it and `None` on a continuation, a one-line CALL / ANSWER reply format, its stored steps and tool results rendered on each read (`render_step`, `render_observation` with `observation_text`), a tool catalog generated with `PromptBuilder`, the run's `generation_options` forwarded to the model, one call per reply (`max_actions_per_turn`) and a tool name the format cannot write refused, the planner conformance suite run on it (`check_conformance(PlannerCase(make=LinePlanner))`), and a `SimpleAgent` run on it (Qwen2.5-7B).
  * `demos/planner/demo_multi_tool_turn.py`: Let a model issue several tool calls in one turn and run them in parallel, under `ToolExecutor(parallel_read_only=, max_parallel_tools=)`, with each `ScheduledGroup` printed (Qwen2.5-14B, greedy).
  * `demos/planner/demo_named_prompt_instructions.py`: Name prompt instructions and examples so one can be replaced or removed.
  * `demos/planner/demo_temporal_context.py`: Tell the model what time it is with the Current Time section of the system prompt: `PromptBuilder.temporal_context` and the settings `prompts.temporal_context` / `prompts.temporal_context_time`.
  * `demos/planner/demo_reply_formats.py`: What each `ReActPlanner` reply format (`ReplyFormat.KEY_VALUE`, `ReplyFormat.JSON_ACTION`) asks the model to write, read off the rendered prompt (`capture_rendered_prompt=True`), and the `ToolCallBatch` a reply parses into; the planner is swapped through the `SimpleAgent.planner` setter (Qwen2.5-7B, `constrained_decoding=False`).

### file_tools

  * `demos/file_tools/demo_sandboxed_edit_run.py`: An agent with the rooted read and edit tools and `ShellTool`, with a declared set of host programs (`executables=`), fixes a failing check script under one granted project root: every shell command runs at the isolated level through the call's workspace, writing only that root, under a per-call timeout, reported through one `BoundedRunEvent`; with no bag an isolated `read_file` reads its declared root and refuses a path outside it (Qwen3-Coder-30B through the `HuggingFaceAdapter`).
  * `demos/file_tools/demo_write_run_fix.py`: An agent with `EditFileTool` (changes an existing file by an exact, unique substring), `ReplaceFileTool` (gives an existing one a whole new text), `ReadFileTool` and `RunPythonTool` rooted at a case folder starts from the application's buggy implementation of a small parser spec, edits or rewrites it, and runs the application's `check.py` in an isolated child until it exits 0; every run is read off the event bus as a typed `PythonRunResult` and every rewrite as a `ReplaceResult` (`ToolCallPostEvent.output`), and the verdict is the exit code of the last run of `check.py` (`FAIR_LLM_DEMO_MODEL`).
  * `demos/file_tools/demo_agentic_search.py`: An agent answers questions about a file tree by searching it.

### memory

  * `demos/memory/demo_checkpoint_resume.py`: Bookmark an agent's session with `session_log.position` and return the view to it with `await session_log.rewind(position)`; the records the rewind leaves behind stay in the log.
  * `demos/memory/demo_context_providers.py`: `SimpleAgent(context_providers=)` adds text to every model request: a `ContextProvider` of the demo's own (project instructions the application holds), proved by the context provider conformance suite, and the shipped `FileContextProvider` reading `config.py` afresh for each request; each contribution prints as the `ContextContributedEvent` a subscriber sees, an edit to the file between two questions reaches the second request, and the view after the run holds no contribution.
  * `demos/memory/demo_custom_session_store.py`: A session store of the application's own, `JsonLinesSessionStore`, implementing `AbstractSessionStore` with the shared checks, proved by the session store conformance suite; two agents built over the same directory carry one conversation, and the log is rewound to a held position and reset.
  * `demos/memory/demo_long_term_memory.py`: A fact outlives the session: the agent keeps it with `RememberTool` in a `VectorLongTermMemory`, the session is reset, and a `RecallContextProvider` puts it in front of the model in the next run, printed as the `ContextContributedEvent`; `memory.forget` by the run's stamp then removes it.
  * `demos/memory/demo_pinned_messages.py`: Pinned messages survive a `SummarizingCompactor`'s compaction verbatim, and each compaction is a `MemorySummarizedEvent` naming the compactor, the cause, the messages dropped and the messages read in their place.
  * `demos/memory/demo_smarter_compaction.py`: A `SummarizingCompactor` keeps a live agent's view inside a token budget, one compaction at most per step, snipping a long observation without the model before it summarizes, with the summary cap; a compaction forced through `session_log.compact` with a cut-off summary records nothing and publishes `CompactionFailedEvent`.

### reliability

  * `demos/reliability/demo_action_verifier.py`: An action verifier checks the file an edit left on disk; a rejection is fed back so the model fixes the file, and a verifier passed to `arun` for one run that raises ends it with `ActionVerificationError`.
  * `demos/reliability/demo_arun_validator.py`: A validator on arun holds every answer to a JSON schema: a Pydantic model parses each final answer, and a rejected one is rewritten with the schema's error as feedback; rewrites that stall trip `similarity_threshold`, and a validator that raises ends the run with `ValidatorError`.
  * `demos/reliability/demo_circuit_breaker.py`: `breaker.enabled` makes a failing provider fail fast, then recover: behind a local proxy that answers HTTP 503, five `SERVER_ERROR` calls open the breaker (`BreakerStateChangeEvent`), later calls fail at once with `CIRCUIT_OPEN`, and after the outage ends and `cooldown_seconds` pass, the half-open probe reaches the real Ollama server and the breaker closes.
  * `demos/reliability/demo_error_routing.py`: Every failure out of arun is a typed `FairlibError`, and its kind chooses the action: a `ChatModel` over an `OllamaAdapter` with nothing listening at its host (`CONNECTION`), the same host with `max_retries=2`, whose `ModelRetryEvent` names each resend before the same failure, one whose server never answers until the model's `timeout` ends the call (`TIMEOUT`), an assistant `Message` as input (`InvalidAgentInputError`), then a real model's answer.
  * `demos/reliability/demo_lifecycle_hooks.py`: A help desk policy on the seam that owns each decision: a `Perception` drops a mention from the request, an `Authorizer` caps a ticket read with `Allow(arguments=)` and denies a forbidden tool, `LifecycleHooks` answer a password request with a `HookVeto` before the model is called and label each observation with an `ObservationRewrite`, and a quota passed as `arun(authorizers=)` denies a call once its count is spent.
  * `demos/reliability/demo_loop_guard.py`: A call repeated with the same input and result trips the loop guard: `LoopGuardTrippedEvent` and the note the model reads, then `agent.loop_guard.stop_on_trip` ending the run in `LoopGuardStoppedError` (Qwen2.5-1.5B, a model that re-checks an unchanged status).
  * `demos/reliability/demo_parse_error_recovery.py`: A reply that breaks the planner's format gets a correction naming the parse error and a retry (`PlannerParseErrorEvent` with `attempt` and `will_retry`); past `max_parse_attempts`, `arun` raises `PlannerParseError` (Qwen2.5-1.5B on the key-value text path, `constrained_decoding=False`).
  * `demos/reliability/demo_tool_retry.py`: A flaky tool is retried by the agent, not by your code: a READ_ONLY tool raises a retryable `ToolInvocationError` of kind `TIMEOUT` twice, and `max_tool_retries=2` re-dispatches it with a `ToolCallRetryEvent` before each retry.

### events

  * `demos/events/demo_subscribe_all.py`: Keep a timeline of every event an agent run carries with `AgentEventBus.subscribe_all`, emit your own `FairlibEvent`, and see the refusal of a subscription to the `FairlibEvent` base class.
  * `demos/events/demo_event_bus.py`: Build a live activity monitor for an agent from event-bus subscriptions alone.
  * `demos/events/demo_streaming_agent.py`: Stream an agent's model calls as typed events and pick out the final answer.
  * `demos/events/demo_structured_trace_export.py`: Record an agent run as a trace of typed events, grouped by agent step, save it and read it back with `AgentRunTrace.load`, then a session of several runs with a `TraceRecorder` block, and read a failed run's trace from `recorder.trace`.

### usage_telemetry

  * `demos/usage_telemetry/demo_agent_usage_telemetry.py`: Every model call's token counts and stop reason from `ModelInvocationEvent`, and what a LENGTH stop does to a run: `TruncatedFinalAnswerEvent`, `PlannerParseErrorEvent(truncated=True)` for a turn cut mid-answer, and the `limits.agent.length_retry_*` policy that asks a cut turn again with a larger budget (Qwen2.5-7B through the `HuggingFaceAdapter`).
  * `demos/usage_telemetry/demo_custom_cost_ledger.py`: Write your own cost ledger by implementing `AbstractCostLedger`, prove it with `CostLedgerCase`, then share it between two budgets with a `Pricing` that reads the model's name: an `ainvoke` and an `astream` under `cost_budget_scope`, and the day's ceiling refusing the second budget.
  * `demos/usage_telemetry/demo_token_cost_budgeting.py`: `CostBudget` session and day ceilings with a day ledger shared across budgets, a budget built from settings, a call priced and estimated, and refusals routed by `BudgetScope`; plus `SecurityManager`'s EXTERNAL call ceiling.
  * `demos/usage_telemetry/demo_usage_telemetry.py`: Read the token counts, duration and stop reason an adapter attaches to a reply.

### security

  * `demos/security/demo_ask_before_writes.py`: An `Authorizer` answers `Ask` for every MUTATING call and `SecurityManager(input_channel=)` holds an in-process `InputChannel`, the application's person: an agent's save is approved, and with the person away a worker's save reaches the same person through the derived manager and goes unanswered: a delegation cannot pause, so an `Ask` nobody answers is a deny. With the person still away, a top-level save pauses, and a second agent over the same `FileSessionStore` resumes it with `ResumeInput`.
  * `demos/security/demo_bounded_entry_point.py`: An application runs its own compute over an agent's answers with `arun_bounded`, outside any tool (the entry point in `demos/security/number_factoring.py`): a `BoundedResult`, a `RaisedInChild` from an input the entry point refuses, and a `ResourceBoundExceededError` from a CPU bound the compute really exceeds.
  * `demos/security/demo_bounded_tool_evaluation.py`: Tools run in child processes under bounds: the shipped `AdvancedCalculusTool` (`IsolationLevel.BOUNDED`, its bounds given as `SecurityManager(LocalWorkspace(), bounded_tools=)`) and a calculator of the adopter's own that declares `IsolationLevel.ISOLATED`, `executables`, `path_grants` and `bounded_construction`, its bounds set under `limits.compute.tools`; one call runs past its wall bound and reaches the model as `ResourceExhaustedError`, another returns a reply over `limits.compute.reply_bytes`, refused as a `SandboxWorkerError` (`FAIR_LLM_DEMO_MODEL`).
  * `demos/security/demo_input_validation.py`: A perception redacts email addresses from each request before anything reads it, and a security manager given an input screen (`SecurityManager(input_screen=)`, here `default_input_screen` wrapped to print each verdict) judges the user turn, each tool input as JSON and each tool result; a plain note is saved, and a request quoting a prompt-injection phrase is refused before the run starts with `InvalidAgentInputError`, so the model never reads it (`FAIR_LLM_DEMO_MODEL`).
  * `demos/security/demo_network_egress.py`: A network tool declares where it connects (`network_egress`, `reaches_network`); under `SecurityManager(LocalWorkspace(), allowed_egress=...)` an allowlisted target dispatches, while a target off the allowlist and an undeclared network tool are refused before the tool runs, reported through `NetworkEgressDeniedEvent` (`FAIR_LLM_DEMO_MODEL`).
  * `demos/security/demo_secure_configuration.py`: Default-deny capability grants on a local model: an empty `CapabilityBag` refuses the model, a narrow bag lets the agent read a granted file and refuses an ungranted one as `CAPABILITY_DENIED`, the same grants written as `security.grants` build the manager through `SecurityManager.from_settings`, where `security.grants.hosts` refuses a tool whose declared `network_egress` host it does not name before the tool runs; then `ReadFileTool` declared `IsolationLevel.ISOLATED` is refused with `SandboxUnavailableError` on an executor with no security manager, and under one runs every read in a confined child that reaches only the granted paths, reported through `BoundedRunEvent` and `CapabilityDeniedEvent` (`FAIR_LLM_DEMO_MODEL`).

### rag

  * `demos/rag/demo_custom_grounding.py`: Write a `GroundedContextBuilder`, one async function, with a one-line-per-source presentation, pass it to `RAGQueryTool(grounder=)`, see its block in the rendered prompt, and verify the answer's citations with `CitationVerifier` (Qwen2.5-14B).
  * `demos/rag/demo_document_upload.py`: Uploads become a knowledge base: `save_uploaded_file` and `extract_segments` under upload settings set with `settings_overlay` (`files_directory`, `supported_extensions`, `max_chunk_chars`, OCR with `ocr_dpi` on a scanned PDF, `limits.documents.max_upload_mb`), each bad upload refused with `DocumentProcessingError`, a refused CSV read by a `TextExtractor` of its own through `DocumentProcessor(extractors=...)` and checked with `TextExtractorCase`, then an agent answers from the uploads through `RAGQueryTool`.
  * `demos/rag/demo_rag_from_documents.py`: A deep dive into Retrieval-Augmented Generation using ChromaDB: chunking with the named strategies, an overlapping `Chunker` and a whole-word `Chunker` of its own, then nearest-first and filtered retrieval, and an agent answering from the README.
  * `demos/rag/demo_two_sided_grounding.py`: Cite-only source injection through `RAGQueryTool`'s grounder, then citation extraction and verification against a source lookup of your own (a `SourceLookup`, one async function), with `GroundingAppliedEvent`, `CitationVerificationEvent` and `CitationVerificationError` when the lookup breaks (`FAIR_LLM_DEMO_MODEL`).
  * `demos/rag/demo_faiss_rag_from_readme.py`: RAG using the FAISS vector store backend with cross-encoder re-ranking through a `CrossEncoderScorer` (recommended for most use cases).

### persistence

  * `demos/persistence/demo_save_load_single_agent.py`: Saves an agent with a tool of its own to a YAML file with `save_agent_config`, edits the role in the file, shows `load_agent` refusing the unknown tool, and loads it back through `AgentFactory(llm, tool_classes=)`, reading the result as an `AgentConfigDocument`.
  * `demos/persistence/demo_save_load_multi_agent.py`: Saves a manager and its calculator and calculus workers to one file with `save_multi_agent_config` and loads the team back with `load_multi_agent`, and reads the file back as a `MultiAgentConfigDocument` with `AgentFactory.read_document`.
  * `demos/persistence/demo_orchestration_layer.py`: A leased work queue survives its workers: `WorkQueue(FileJobStore(root))` with `bind_event_bus`, a job whose worker dies mid-run is reclaimed when the lease expires and resumed from the session store by `JobRunner`, a corrupt job file is quarantined by the store, a job that spends `max_attempts` is dead-lettered, and `CostBudget` totals the spend; caps set through `limits.orchestration` with `settings_overlay` (`FAIR_LLM_DEMO_MODEL`).
  * `demos/persistence/demo_session_crash_recovery.py`: An agent on a `SessionLog` opened over a `SqliteSessionStore` is cancelled mid-run, the way a host dies; a later process opens the same file, marks the session interrupted with `SessionRegistry.recover_interrupted`, reads its `status`, tags it with `annotate`, finds it with `search`, and continues it with a new agent over `SessionLog.open`.
  * `demos/persistence/demo_work_queue.py`: Write your own job store by implementing `AbstractJobStore` (an in-memory dict, its four members coroutines, `swap` refusing a stale revision with `JobConflict`), prove it with `check_conformance(JobStoreCase(...))`, drive it with `WorkQueue` (the lease, the attempts and the restart backoff, its job events on the bus `bind_event_bus` attaches), run one job from it with `JobRunner.run_one`, catch the `LeaseLostError` a stalled worker gets when its lease expired and another claim took the job, and park a job whose authorizer asks a person, answering it through `queue.resume` (`FAIR_LLM_DEMO_MODEL`).

### multi_agent

  * `demos/multi_agent/demo_multi_agent_isolation.py`: Isolate a worker agent and narrow what it may do with a capability bag.
  * `demos/multi_agent/demo_worker_fanout.py`: A manager agent delegates independent subtasks to two worker agents at once.
  * `demos/multi_agent/demo_custom_communicator.py`: Write your own communicator by implementing `AbstractCommunicator`, prove it with `CommunicatorCase`, hand it to `build_worker_manager(communicator=)`, and read the worker summary back with `areceive_message`.
  * `demos/multi_agent/demo_custom_worker_agent.py`: Write your own worker agent by subclassing `AbstractAgent` (a tool-free worker, one model call per delegation, its role set through `role_description`), then let a manager delegate to it through `WorkerAgentTool`, whose `compose_task` folds a field of the tool's own input into the worker's task, and `build_worker_manager`.
  * `demos/multi_agent/demo_multi_agent_load_balancer.py`: Run several agents at once against one load-balanced model backend.

### mcp

  * `demos/mcp/demo_multi_agent_research_team.py`: The most advanced agent demo. A manager delegates to researcher, analyst and writer workers through `WorkerAgentTool` and `build_worker_manager`; the researcher's web search comes from a Brave Search MCP server fed to its registry by an `MCPToolSource`.
  * `demos/mcp/demo_mcp_agent_tool_calling.py`: Local tools and MCP tools in one agent: feed one `ToolRegistry` from an `MCPToolSource`, list and re-discover a server's tools, then remove the server.
  * `demos/mcp/demo_mcp_hostile_server.py`: A hostile MCP server: what reaches the model by default, and when hardened.
  * `demos/mcp/demo_mcp_image_result.py`: An MCP server's PNG chart reaches a vision model as media through `MCPServerConfig(output_media=)`, the observation's text naming it, and the same tools on a text-only model are refused before any model call (qwen3-vl-instruct-16k via Ollama; it spawns `demos/mcp/chart_mcp_server.py`).
  * `demos/mcp/demo_mcp_streamable_http.py`: Connect a `SimpleAgent` to a token-protected MCP server over Streamable HTTP, through `MCPServerConfig(transport="streamable_http", url=, auth_token=)` and an `MCPToolSource`; the demo starts the server itself, shows the typed refusal of a wrong token (the HTTP status, never the token), the config with its token masked, and the tool's declared egress (Qwen2.5-7B).
  * `demos/mcp/demo_mcp_server.py`: Serve your own tool over MCP with `MCPServer`, under the server's own `SecurityManager`, and call it back through `MCPToolSource` over a stdio `MCPServerConfig`; a note quoting a prompt-injection pattern is refused by the server and reaches the model as a refusal, through the `fairlib/refused` mark in the tool error's `_meta` (Qwen2.5-14B; it spawns `demos/mcp/notebook_mcp_server.py`).

### conformance

  * `demos/conformance/demo_chat_model_conformance.py`: Prove a local adapter with the model adapter suite, then probe its real model.
  * `demos/conformance/demo_input_screen_conformance.py`: Give a `SecurityManager` an input screen of your own (an SSN screen), prove the screen with `InputScreenCase` through `check_conformance`, and run an agent under it through `ToolExecutor`; the request quoting a number is refused before the run starts.
  * `demos/conformance/demo_tool_conformance.py`: Check a tool you wrote with the tool conformance suite, then use it in an agent.
  * `demos/conformance/demo_vector_store_conformance.py`: Write your own vector store, prove it with `check_conformance`, then search it from an agent through `RAGQueryTool(SimpleRetriever(store))`.

### evaluation

  * `demos/evaluation/demo_evaluation_grid.py`: Evaluate your own agent on your own tasks: three `TaskSpec` word problems whose async checkers read only the final answer and answer a `CheckResult`, an async `AgentBuilder` that builds a new `SimpleAgent` for every run, with and without `SimpleCalculatorTool`, two cells run through `arun_cell` with each `CellResult.directory` and its per-task `TaskResult`s printed, and the `SUMMARY.md` that `write_report` writes, one row per label (Qwen2.5-7B, greedy).

### autograders

  * `demos/autograders/demo_committee_of_agents_coding_autograder.py` and `demos/autograders/demo_committee_of_agents_essay_autograder.py`: Practical examples of the multi-agent architecture applied to autograding essays and code, each submission graded from its own case folder; the helpers both share (the agent factory, the case-folder clerk and the console printers) live in `demos/autograders/autograder_common.py`.

## Learn with Our Developer's Guide

Our comprehensive developer's guide, **"A Guide to the FAIR Agentic Framework"**, is written for developers of all skill levels - from newcomers to experienced AI engineers. Whether you're building your first chatbot with a tool or architecting a complex network of distributed agents, this guide will give you the principles and practical techniques you need. The guide is available in the `docs/` directory.

## Framework Architecture

The FAIR Agentic Framework is organized into a modular architecture. Below is an overview of the most critical components:

  * `core/`: Contains the architectural DNA of the framework.
      * `interfaces/`: Abstract Base Classes defining the "contract" for every major component (`AbstractAgent`, `AbstractModelAdapter`, `AbstractPlanner`, `AbstractSessionStore`, `Compactor`, `AbstractTool`, `AbstractEmbedder`). This is the key to the framework's modularity.
      * `message.py`: Core conversational data structures - `Message`, `Thought`, `Action`, `Observation`, and `FinalAnswer` - that flow between all components.
      * `tool_executor.py` / `tool_registry.py`: The `ToolExecutor` that dispatches every tool call, and the `ToolRegistry` (fed by any `ToolSource`, such as MCP, tool search or per-step filtering).
      * `types.py`: Domain data types such as `Document`, `GradingCriterion`, and `FinalGrade`.
      * `prompts/`: The prompt engineering package - prompt item types in `items.py`, builders in `builders.py`, the wire models in `models.py`, and lazy re-exports of every public name from `__init__.py`.
      * `config.py` / `config_schemas.py`: Pydantic-validated configuration loading, and the `MCPServerConfig` schema.
  * `modules/`: Contains the concrete implementations of the interfaces.
      * `mal/`: The **Model Abstraction Layer**, with adapters for `OpenAIAdapter`, `AnthropicAdapter`, `GeminiAdapter`, `OllamaAdapter`, `HuggingFaceAdapter`, and `LoadBalancerAdapter` (distributed vLLM inference).
      * `agent/`: Agent definitions (`SimpleAgent`), the workers-as-tools fan-out path (`WorkerAgentTool`, `build_worker_manager`), and the agent factory (`factory` - build agents from config files, save them back).
      * `planning/`: Reasoning engines - `ReActPlanner`, the one text planner, whose `reply_format` (`ReplyFormat.JSON_ACTION` by default, or `ReplyFormat.KEY_VALUE` for smaller/local models) and `max_actions_per_turn` (several tool calls per turn above 1) are settings, and the key-value reply reader (`key_value_reply`). Planners contribute only their mandatory format rules and the live tool/worker catalog to the prompt - all other content (role, examples) is supplied by your application.
      * `mcp/`: Full **Model Context Protocol** support - `MCPToolSource` (connects to MCP servers and offers each server's tools as fairlib tools) and `MCPServer`. The client supports the `stdio`, `SSE` and `Streamable HTTP` transports, with a bearer token on the HTTP ones; the server serves stdio.
      * `action/`: The tool library - built-in tools (`SimpleCalculatorTool`, the rooted file tools `ReadFileTool`, `ListDirTool`, `GlobTool`, `GrepTool`, `WriteFileTool` (creates a new file), `EditFileTool` (replaces one exact, unique substring of an existing file) and `ReplaceFileTool` (replaces an existing file's whole text), and `ShellTool`, which runs every command in an isolated child) and domain tools (`RAGQueryTool`, `GradeEssayFromRubricTool`, `GradeCodeFromRubricTool`, `CodeExecutionTool`, `RunPythonTool`, `AdvancedCalculusTool`, `RememberTool`, `RecallTool`). Web search, plotting and web data extraction come from an MCP server's tools, configured with `MCPServerConfig` and fed to its registry by an `MCPToolSource`.
      * `memory/`: The shipped compactors that bound the session log's view (`WindowCompactor`, `SummarizingCompactor`), the shipped context providers (`FileContextProvider`, `RecallContextProvider`), the long-term memory `VectorLongTermMemory` that keeps messages across sessions in any vector store, and the RAG components (`FaissVectorStore`, `ChromaDBVectorStore`, `InMemoryVectorStore`, `SentenceTransformerEmbedder`, `SimpleRetriever`, `CrossEncoderRerankingRetriever`), all importable from `fairlib`.
      * `communication/`: Agent-to-agent communication (`InMemoryCommunicator`).
      * `orchestration/`: `JobRunner`, which claims a job from a work queue and runs an agent on it, and `FileJobStore`.
      * `security/`: `LocalWorkspace`, the backend a `SecurityManager` is given to run on this host, with the bounded and isolated child runner behind it (the runner, the launcher a child starts on, Landlock and seccomp confinement, and the code tools' drivers; the child worker is `core/sandbox_worker.py`, and the driver over any backend is `core/managed_workspace.py` with `core/stream_run.py`).
  * `config/`: Centralized YAML configuration (`settings.yml`).
  * `utils/`: Utility code - `document_processor`, `chunking` and `response_pool`.
  * `fairlib/__init__.py`: The central, user-facing API providing lazy-loaded access to all framework components.
  * `demos/`: A collection of scripts that serve as practical, executable examples of the framework's capabilities.

## Folder Structure

```
fair_llm/
|-- fairlib/
|   |-- config/
|   |   `-- settings.yml
|   |-- core/
|   |   |-- interfaces/
|   |   |   |-- agent.py
|   |   |   |-- chunking.py        (Chunker)
|   |   |   |-- communicator.py
|   |   |   |-- durable_executor.py (AbstractDurableExecutor)
|   |   |   |-- embedder.py
|   |   |   |-- evaluation.py      (AgentBuilder, Checker)
|   |   |   |-- extraction.py      (TextExtractor)
|   |   |   |-- long_term_memory.py (AbstractLongTermMemory)
|   |   |   |-- memory.py          (vector store, retriever)
|   |   |   |-- model_adapter.py
|   |   |   |-- planner.py
|   |   |   |-- tool_source.py     (ToolSource)
|   |   |   |-- tools.py
|   |   |   |-- validator.py       (Validator)
|   |   |   `-- workspace.py
|   |   |-- config.py
|   |   |-- config_schemas.py      (includes MCPServerConfig)
|   |   |-- managed_workspace.py   (ManagedWorkspace: what drives a backend)
|   |   |-- mcp_specs.py           (MCPPromptArgument, MCPPromptSpec, MCPResourceSpec)
|   |   |-- message.py
|   |   |-- tool_executor.py
|   |   |-- tool_registry.py
|   |   |-- prompts/               (prompt items + builders + wire models)
|   |   |-- sandbox_worker.py      (the child process)
|   |   |-- security_manager.py    (SecurityManager: screens, grants, bounded runs)
|   |   |-- stream_run.py          (a named Python run in frames over exec)
|   |   `-- types.py
|   |-- evaluation/                (arun_cell, write_report, the grid command line)
|   |-- modules/
|   |   |-- action/
|   |   |   `-- tools/
|   |   |       |-- builtin_tools/
|   |   |       |   |-- simple_calculator.py
|   |   |       |   `-- shell_tool.py      (ShellTool, DEFAULT_SHELL_EXECUTABLES)
|   |   |       |-- advanced_calculus_tool.py
|   |   |       |-- code_execution_tool.py (CodeExecutionTool, CodeTestReport)
|   |   |       |-- grading_tool.py
|   |   |       |-- memory_tools.py        (RememberTool, RecallTool)
|   |   |       |-- rag_tool.py
|   |   |       `-- run_python_tool.py     (RunPythonTool, PythonRunResult)
|   |   |-- agent/
|   |   |   |-- factory.py                 (save_agent_config, load_agent)
|   |   |   |-- simple_agent.py
|   |   |   |-- worker_manager.py          (build_worker_manager)
|   |   |   `-- worker_tool.py             (WorkerAgentTool)
|   |   |-- communication/
|   |   |   `-- in_memory_communicator.py
|   |   |-- mal/
|   |   |   |-- anthropic_adapter.py
|   |   |   |-- gemini_adapter.py
|   |   |   |-- huggingface_adapter.py
|   |   |   |-- load_balancer_adapter.py   (LoadBalancerAdapter - vLLM)
|   |   |   |-- local_llama_adapter.py     (OllamaAdapter)
|   |   |   `-- openai_adapter.py
|   |   |-- mcp/
|   |   |   |-- client/
|   |   |   |   |-- mcp_client.py
|   |   |   |   |-- mcp_tool_adapter.py
|   |   |   |   `-- mcp_tool_source.py
|   |   |   `-- server/
|   |   |       `-- mcp_server.py
|   |   |-- memory/
|   |   |   |-- compactors.py
|   |   |   |-- embedder.py
|   |   |   |-- file_context.py            (FileContextProvider)
|   |   |   |-- long_term.py               (VectorLongTermMemory)
|   |   |   |-- retriever.py
|   |   |   |-- retriever_rerank.py
|   |   |   |-- vector_chroma.py           (ChromaDB)
|   |   |   |-- vector_faiss.py
|   |   |   `-- vector_inmemory.py
|   |   |-- orchestration/
|   |   |   |-- file_job_store.py          (FileJobStore)
|   |   |   `-- job_runner.py              (JobRunner)
|   |   |-- planning/
|   |   |   |-- key_value_reply.py         (the key-value reply format)
|   |   |   |-- parse_helpers.py
|   |   |   |-- react_planner.py           (ReActPlanner)
|   |   |   `-- streaming.py               (final-answer stream filters)
|   |   `-- security/
|   |       |-- bounded_runner.py        (starts and bounds the child)
|   |       |-- confinement.py           (Landlock + seccomp)
|   |       |-- local_workspace.py       (LocalWorkspace: runs a command on this host)
|   |       `-- sandbox_launcher.py      (what the child starts on: confines, then serves)
|   |-- utils/
|   |   |-- chunking.py
|   |   |-- document_processor.py
|   |   `-- response_pool.py
|   `-- __init__.py                        (central API with lazy loading)
|-- demos/
|   |-- getting_started/
|   |-- models/
|   |-- custom_tools/
|   |-- planner/
|   |-- file_tools/
|   |-- memory/
|   |-- reliability/
|   |-- events/
|   |-- usage_telemetry/
|   |-- security/
|   |-- rag/
|   |-- persistence/
|   |-- multi_agent/
|   |-- mcp/
|   |-- conformance/
|   `-- autograders/
|-- docs/
|   |-- A Guide to the FAIR Agentic Framework.pdf
|   |-- Agentic System Design Blueprint.pdf
|   |-- CHANGELOG.md
|   |-- VERSIONING.md
|   `-- latex/
|-- tests/
|-- CODE_OF_CONDUCT.md
|-- CONTRIBUTING.md
|-- Jenkinsfile
|-- LICENSE.md
|-- pyproject.toml
|-- README.md
|-- requirements.txt
|-- SECURITY.md
`-- uv.lock
```

## Contact

fair-llm is developed by the USAFA AI Center's Falcon AI Research (FAIR) Lab.
Questions, security reports and code of conduct concerns go to
austin.w@ardentinc.com. Report a suspected vulnerability privately to that
address, never in a public issue. Include the fair-llm version, the Python
version and platform, a description of the problem, and the smallest steps
that reproduce it. SECURITY.md in the source distribution has the full
policy.

## Contributing

Contributions are welcome. CONTRIBUTING.md in the source distribution says how a
change is designed (interface first), the per-PR design checklist, the
conformance suites a new adapter, tool, vector store, job store, authorizer
or workspace passes, the checks you run (`make qa-fast`, `make qa`) and the ones the
maintainer runs, and how to sign off your commits. Everyone taking part
follows the code of conduct (CODE_OF_CONDUCT.md, Contributor Covenant 2.1).
docs/QA_AND_DEPENDENCIES.md describes the
gates, the coverage floor and the dependency-update policy.
