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
WindowCompactorfor aSummarizingCompactor) 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
MessageandDocumenttypes, 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
ReActPlannerallows 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) orreply_format=ReplyFormat.KEY_VALUE(Thought:/Action:/tool_name:/tool_input:lines, for smaller or local models that may struggle with strict JSON), andmax_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.
WorkerAgentToolwraps any agent as a typed tool andbuild_worker_managerwires 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 (FaissVectorStoreandChromaDBVectorStore) made available to the agent through theRAGQueryTool. Retrieved hits are numbered[S1]..[Sn]with a cite-only instruction; the tool accumulates a session-scopedgrounded_contextso answers can be verified after multiple retrieves.CitationVerifierthen checks generated citations and reports a fabrication rate that distinguishesnot_foundfromcould_not_checkandsource_unreachable. External locator lookup is an optionalSourceLookup, a plain async function. Seedemos/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 passingMCPToolSource([MCPServerConfig(...)])toToolRegistry.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 throughMCPServerConfig. - Streaming Responses: Opt-in end-to-end token streaming through the agent loop. Enable
streaming.enabled(or passstream=Trueto a planner orSimpleAgent) 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();ReActPlannergives a key-value filter for the text path of areply_format=KEY_VALUEplanner and a JSON filter for every other call), and that text is published asModelStreamAnswerEvent, 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. Seedemos/events/demo_streaming_agent.py. - Secure by Design: The
SecurityManagerscreens input, enforces opt-in capability grants and an egress allowlist, runs theAuthorizerpolicies an application gives it (SecurityManager(authorizers=), oragent.arun(..., authorizers=)for one run and its workers) before those checks, where anyDenyis 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 declaresIsolationLevel.BOUNDEDto run under compute bounds, orIsolationLevel.ISOLATEDto run in a child confined by Landlock and seccomp on Linux, andarun_boundedruns an application's own compute that is not a tool at the level it asks for.ShellToolruns every command, andCodeExecutionToolandRunPythonToolevery run of a file, at the isolated level through the call's workspace. See 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
AgentBuilderof(task, workspace), declare each task as aTaskSpecwith an asyncCheckerthat reads aCheckContextafter the run and answers aCheckResult, andarun_cellruns 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_reportturns the cells into aSUMMARY.mdtable with one row per label. See 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 asfairlib. The unrelated PyPI packagefairlib(0.1.0) is a different project. Always pin the correct distribution, e.g.fair-llm==1.0.0inrequirements.txtorconstraints.txt, and verify withpip show fair-llmbefore 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.
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:
cd fair_llm
uv sync --extra all --extra test # the versions in uv.lock, into .venv
or, with pip, the declared ranges:
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:
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:
pip show fair-llm # must show Name: fair-llm and your pinned version
python -c "import fairlib; print(fairlib.__version__)"
Common mistakes:
pip install fairlibinstalls an unrelated 0.1.0 project on PyPI, not this framework.- Installing an application without its constraints file can miss the application's
fair-llmpin. An application that pinsfair-llmin a rootconstraints.txtinstalls withpip install -r requirements.txt -c constraints.txtso the pin is honored. - A feature raises
MissingExtraError: install the extra it names (exc.extra), for examplepip install "fair-llm[rag]".
3. Configuration
The framework uses a centralized YAML configuration file for API keys and model settings.
- Either edit the packaged file at
fairlib/config/settings.yml, or setFAIR_LLM_SETTINGSto a consumer-owned YAML path, or callconfigure_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 usesyaml.safe_loadonly. - Add your API keys (e.g., for OpenAI, Anthropic, or Gemini).
- Review the model definitions and other settings (RAG paths, security) to suit your environment.
- 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.
# 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:
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.
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: 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.
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 withbounded_entry_point, namedpackage.module:function, in a child at the levelrequirednames, and refuses rather than run at a weaker one. Its arguments cross as plain JSON data; the JSON value it returns isresult.value, and files it writes at the top of its working directory come back asresult.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, andLocalWorkspace's child proves from the kernel that it is confined before anything runs. -
SecurityManager(workspace)takes anAbstractWorkspace, where a bounded run executes, as its first required argument;LocalWorkspaceis this host's. A backend implementsisolationandexec, and fairlib'sManagedWorkspacedrives it. Its levels are whatavailable_levelsanswers. Prove a backend of your own withawait check_conformance(WorkspaceCase(make=MyWorkspace))and pass it asSecurityManager(MyWorkspace());MinimalWorkspace, infairlib.conformance.partners, is the least a backend can be (BOUNDEDalone) 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_isolationand awaitscontext.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 bothisolationandexec_isolationis refused withConfigurationErrorwhen it first becomes visible in a run, and so is one declaringreads_host,isolationorpath_grantson a backend whoseIsolation.fairlib_insideis False. -
ISOLATEDruns 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 raisesSandboxUnavailableError, and a run that registersShellTool,RunPythonToolorCodeExecutionToolunder a security manager ends with it at run entry, before any model call; it never runs at a weaker level or in-process.BOUNDEDruns on Linux only. -
At
ISOLATEDa tool reaches the host paths itspath_grantsdeclares, each a kernel rule: a rooted file tool such asReadFileTool(root=...)declares its root (read, and written by a mutating tool such asShellToolorWriteFileTool). Without a bag the declaration alone applies. A manager that holds aCapabilityBagcarries 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 withConfigurationErrorbefore 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_tasksbounds the processes AND threads of the child's tree through asystemd-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 raisesSandboxUnavailableErrorbefore any child starts.limits.compute.file_bytesbounds each file the child writes, not the total. -
A tool's
executablesnames 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'sPATH, and one that does not resolve refuses the run before any child starts, naming it.python3andpythonstart 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 needsTMPDIRon 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()(infairlib.core.security_context) returns the level the running code is confined under: the achieved level inside a child,Nonein-process. -
The executor refuses a tool instance whose
isolationdoes not satisfy the level its class declares, withSandboxUnavailableError; an instance may raise its class's level, never lower it. -
ShellTool(root, *, executables=DEFAULT_SHELL_EXECUTABLES)declaresexec_isolationasISOLATED, its programs and its root, and runs every command assh -cbycontext.workspace.execwith its root as the working directory. It needs an executor whose manager's workspace reachesISOLATED; under a bag, one grantingshell.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 fromfairlib) names the common coreutils, grep, sed, find and diff programs and the interpreter; add one withShellTool(root, executables=(*DEFAULT_SHELL_EXECUTABLES, "git")).executablesis a tuple. Each stream keeps its first 1 MiB, clamped bylimits.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 alimits.computeone, the manager'scompute_boundsor an entry namedshellunderbounded_toolsorlimits.compute.tools, ends the command and everything it started and returns the partial output marked timed out;kill 0, and thetimeoutcommand 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 ofroot, named by the model as a path relative toroot, aspython -m pytest <test_file>would fromroot, in an isolated child: the tool runs fairlib's pytest driver throughcontext.workspace.run_entry_pointatIsolationLevel.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 addforsolution.py). It returns aCodeTestReport(exit_code,passed,stdout,stderr,timed_outand the countstests_collected,tests_passed,tests_failed,tests_skipped). It ispassedonly 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 ofrootas a script, aspython <file>would fromroot, 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 ofroot. -
A code tool's run stopped at its wall returns
timed_outwith an emptystdout, and astderrholding a note naming the bound after what reached the child's descriptors directly (a script'sos.write, not pytest's captured output): what the script printed throughsys.stdoutandsys.stderr, and the report pytest was building, are lost with the child. -
Both code tools read every file of
rootin the agent's process and send their contents to the child, which is never grantedroot: the run works on copies and cannot change the files there.wall_secondsis required and greater than 0, so a run that loops forever always returns; the manager'scompute_bounds=,limits.computeand an entry named for the tool underbounded_tools=orlimits.compute.toolstighten it. Under a capability bag, the bag grantsroot's paths, as it does for the file tools. -
GradeCodeFromRubricTool(llm, root)andGradeEssayFromRubricTool(llm, root)read the rubric, the submission and each review from files ofroot, named by the model as paths relative to it (rubric_file,code_fileoressay_file, and one field per review), and grade withllm. 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: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:
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 customAbstractModelAdapterover Ollama's HTTP API with httpx, prove it withcheck_conformanceand aModelAdapterCase, then run aSimpleAgentonChatModel(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 (whenGEMINI_API_KEYis 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 fromModelRequestEvent(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, optionalGEMINI_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 aresponse_schemachecked withresponse_schema_refusalbefore 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, withon_run_start,ToolRunContextandToolCallContext.demos/custom_tools/demo_tool_catalog_and_validation.py: One Pydantic schema writes a tool's catalog entry and validates its input, and aToolOutputof your own decides, throughrender(), 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 (ToolLookupErrorand 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 withconstrained_decoding=Falseon 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 implementingAbstractPlanner:model_needsdeclared, anaplanthat gets the request on the step that answers it andNoneon a continuation, a one-line CALL / ANSWER reply format, its stored steps and tool results rendered on each read (render_step,render_observationwithobservation_text), a tool catalog generated withPromptBuilder, the run'sgeneration_optionsforwarded 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 aSimpleAgentrun 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, underToolExecutor(parallel_read_only=, max_parallel_tools=), with eachScheduledGroupprinted (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_contextand the settingsprompts.temporal_context/prompts.temporal_context_time.demos/planner/demo_reply_formats.py: What eachReActPlannerreply format (ReplyFormat.KEY_VALUE,ReplyFormat.JSON_ACTION) asks the model to write, read off the rendered prompt (capture_rendered_prompt=True), and theToolCallBatcha reply parses into; the planner is swapped through theSimpleAgent.plannersetter (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 andShellTool, 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 oneBoundedRunEvent; with no bag an isolatedread_filereads its declared root and refuses a path outside it (Qwen3-Coder-30B through theHuggingFaceAdapter).demos/file_tools/demo_write_run_fix.py: An agent withEditFileTool(changes an existing file by an exact, unique substring),ReplaceFileTool(gives an existing one a whole new text),ReadFileToolandRunPythonToolrooted at a case folder starts from the application's buggy implementation of a small parser spec, edits or rewrites it, and runs the application'scheck.pyin an isolated child until it exits 0; every run is read off the event bus as a typedPythonRunResultand every rewrite as aReplaceResult(ToolCallPostEvent.output), and the verdict is the exit code of the last run ofcheck.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 withsession_log.positionand return the view to it withawait 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: aContextProviderof the demo's own (project instructions the application holds), proved by the context provider conformance suite, and the shippedFileContextProviderreadingconfig.pyafresh for each request; each contribution prints as theContextContributedEventa 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, implementingAbstractSessionStorewith 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 withRememberToolin aVectorLongTermMemory, the session is reset, and aRecallContextProviderputs it in front of the model in the next run, printed as theContextContributedEvent;memory.forgetby the run's stamp then removes it.demos/memory/demo_pinned_messages.py: Pinned messages survive aSummarizingCompactor's compaction verbatim, and each compaction is aMemorySummarizedEventnaming the compactor, the cause, the messages dropped and the messages read in their place.demos/memory/demo_smarter_compaction.py: ASummarizingCompactorkeeps 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 throughsession_log.compactwith a cut-off summary records nothing and publishesCompactionFailedEvent.
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 toarunfor one run that raises ends it withActionVerificationError.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 tripsimilarity_threshold, and a validator that raises ends the run withValidatorError.demos/reliability/demo_circuit_breaker.py:breaker.enabledmakes a failing provider fail fast, then recover: behind a local proxy that answers HTTP 503, fiveSERVER_ERRORcalls open the breaker (BreakerStateChangeEvent), later calls fail at once withCIRCUIT_OPEN, and after the outage ends andcooldown_secondspass, 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 typedFairlibError, and its kind chooses the action: aChatModelover anOllamaAdapterwith nothing listening at its host (CONNECTION), the same host withmax_retries=2, whoseModelRetryEventnames each resend before the same failure, one whose server never answers until the model'stimeoutends the call (TIMEOUT), an assistantMessageas 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: aPerceptiondrops a mention from the request, anAuthorizercaps a ticket read withAllow(arguments=)and denies a forbidden tool,LifecycleHooksanswer a password request with aHookVetobefore the model is called and label each observation with anObservationRewrite, and a quota passed asarun(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:LoopGuardTrippedEventand the note the model reads, thenagent.loop_guard.stop_on_tripending the run inLoopGuardStoppedError(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 (PlannerParseErrorEventwithattemptandwill_retry); pastmax_parse_attempts,arunraisesPlannerParseError(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 retryableToolInvocationErrorof kindTIMEOUTtwice, andmax_tool_retries=2re-dispatches it with aToolCallRetryEventbefore each retry.
events
demos/events/demo_subscribe_all.py: Keep a timeline of every event an agent run carries withAgentEventBus.subscribe_all, emit your ownFairlibEvent, and see the refusal of a subscription to theFairlibEventbase 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 withAgentRunTrace.load, then a session of several runs with aTraceRecorderblock, and read a failed run's trace fromrecorder.trace.
usage_telemetry
demos/usage_telemetry/demo_agent_usage_telemetry.py: Every model call's token counts and stop reason fromModelInvocationEvent, and what a LENGTH stop does to a run:TruncatedFinalAnswerEvent,PlannerParseErrorEvent(truncated=True)for a turn cut mid-answer, and thelimits.agent.length_retry_*policy that asks a cut turn again with a larger budget (Qwen2.5-7B through theHuggingFaceAdapter).demos/usage_telemetry/demo_custom_cost_ledger.py: Write your own cost ledger by implementingAbstractCostLedger, prove it withCostLedgerCase, then share it between two budgets with aPricingthat reads the model's name: anainvokeand anastreamundercost_budget_scope, and the day's ceiling refusing the second budget.demos/usage_telemetry/demo_token_cost_budgeting.py:CostBudgetsession and day ceilings with a day ledger shared across budgets, a budget built from settings, a call priced and estimated, and refusals routed byBudgetScope; plusSecurityManager'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: AnAuthorizeranswersAskfor every MUTATING call andSecurityManager(input_channel=)holds an in-processInputChannel, 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 anAsknobody answers is a deny. With the person still away, a top-level save pauses, and a second agent over the sameFileSessionStoreresumes it withResumeInput.demos/security/demo_bounded_entry_point.py: An application runs its own compute over an agent's answers witharun_bounded, outside any tool (the entry point indemos/security/number_factoring.py): aBoundedResult, aRaisedInChildfrom an input the entry point refuses, and aResourceBoundExceededErrorfrom a CPU bound the compute really exceeds.demos/security/demo_bounded_tool_evaluation.py: Tools run in child processes under bounds: the shippedAdvancedCalculusTool(IsolationLevel.BOUNDED, its bounds given asSecurityManager(LocalWorkspace(), bounded_tools=)) and a calculator of the adopter's own that declaresIsolationLevel.ISOLATED,executables,path_grantsandbounded_construction, its bounds set underlimits.compute.tools; one call runs past its wall bound and reaches the model asResourceExhaustedError, another returns a reply overlimits.compute.reply_bytes, refused as aSandboxWorkerError(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=), heredefault_input_screenwrapped 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 withInvalidAgentInputError, 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); underSecurityManager(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 throughNetworkEgressDeniedEvent(FAIR_LLM_DEMO_MODEL).demos/security/demo_secure_configuration.py: Default-deny capability grants on a local model: an emptyCapabilityBagrefuses the model, a narrow bag lets the agent read a granted file and refuses an ungranted one asCAPABILITY_DENIED, the same grants written assecurity.grantsbuild the manager throughSecurityManager.from_settings, wheresecurity.grants.hostsrefuses a tool whose declarednetwork_egresshost it does not name before the tool runs; thenReadFileTooldeclaredIsolationLevel.ISOLATEDis refused withSandboxUnavailableErroron an executor with no security manager, and under one runs every read in a confined child that reaches only the granted paths, reported throughBoundedRunEventandCapabilityDeniedEvent(FAIR_LLM_DEMO_MODEL).
rag
demos/rag/demo_custom_grounding.py: Write aGroundedContextBuilder, one async function, with a one-line-per-source presentation, pass it toRAGQueryTool(grounder=), see its block in the rendered prompt, and verify the answer's citations withCitationVerifier(Qwen2.5-14B).demos/rag/demo_document_upload.py: Uploads become a knowledge base:save_uploaded_fileandextract_segmentsunder upload settings set withsettings_overlay(files_directory,supported_extensions,max_chunk_chars, OCR withocr_dpion a scanned PDF,limits.documents.max_upload_mb), each bad upload refused withDocumentProcessingError, a refused CSV read by aTextExtractorof its own throughDocumentProcessor(extractors=...)and checked withTextExtractorCase, then an agent answers from the uploads throughRAGQueryTool.demos/rag/demo_rag_from_documents.py: A deep dive into Retrieval-Augmented Generation using ChromaDB: chunking with the named strategies, an overlappingChunkerand a whole-wordChunkerof 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 throughRAGQueryTool's grounder, then citation extraction and verification against a source lookup of your own (aSourceLookup, one async function), withGroundingAppliedEvent,CitationVerificationEventandCitationVerificationErrorwhen 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 aCrossEncoderScorer(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 withsave_agent_config, edits the role in the file, showsload_agentrefusing the unknown tool, and loads it back throughAgentFactory(llm, tool_classes=), reading the result as anAgentConfigDocument.demos/persistence/demo_save_load_multi_agent.py: Saves a manager and its calculator and calculus workers to one file withsave_multi_agent_configand loads the team back withload_multi_agent, and reads the file back as aMultiAgentConfigDocumentwithAgentFactory.read_document.demos/persistence/demo_orchestration_layer.py: A leased work queue survives its workers:WorkQueue(FileJobStore(root))withbind_event_bus, a job whose worker dies mid-run is reclaimed when the lease expires and resumed from the session store byJobRunner, a corrupt job file is quarantined by the store, a job that spendsmax_attemptsis dead-lettered, andCostBudgettotals the spend; caps set throughlimits.orchestrationwithsettings_overlay(FAIR_LLM_DEMO_MODEL).demos/persistence/demo_session_crash_recovery.py: An agent on aSessionLogopened over aSqliteSessionStoreis cancelled mid-run, the way a host dies; a later process opens the same file, marks the session interrupted withSessionRegistry.recover_interrupted, reads itsstatus, tags it withannotate, finds it withsearch, and continues it with a new agent overSessionLog.open.demos/persistence/demo_work_queue.py: Write your own job store by implementingAbstractJobStore(an in-memory dict, its four members coroutines,swaprefusing a stale revision withJobConflict), prove it withcheck_conformance(JobStoreCase(...)), drive it withWorkQueue(the lease, the attempts and the restart backoff, its job events on the busbind_event_busattaches), run one job from it withJobRunner.run_one, catch theLeaseLostErrora stalled worker gets when its lease expired and another claim took the job, and park a job whose authorizer asks a person, answering it throughqueue.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 implementingAbstractCommunicator, prove it withCommunicatorCase, hand it tobuild_worker_manager(communicator=), and read the worker summary back withareceive_message.demos/multi_agent/demo_custom_worker_agent.py: Write your own worker agent by subclassingAbstractAgent(a tool-free worker, one model call per delegation, its role set throughrole_description), then let a manager delegate to it throughWorkerAgentTool, whosecompose_taskfolds a field of the tool's own input into the worker's task, andbuild_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 throughWorkerAgentToolandbuild_worker_manager; the researcher's web search comes from a Brave Search MCP server fed to its registry by anMCPToolSource.demos/mcp/demo_mcp_agent_tool_calling.py: Local tools and MCP tools in one agent: feed oneToolRegistryfrom anMCPToolSource, 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 throughMCPServerConfig(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 spawnsdemos/mcp/chart_mcp_server.py).demos/mcp/demo_mcp_streamable_http.py: Connect aSimpleAgentto a token-protected MCP server over Streamable HTTP, throughMCPServerConfig(transport="streamable_http", url=, auth_token=)and anMCPToolSource; 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 withMCPServer, under the server's ownSecurityManager, and call it back throughMCPToolSourceover a stdioMCPServerConfig; a note quoting a prompt-injection pattern is refused by the server and reaches the model as a refusal, through thefairlib/refusedmark in the tool error's_meta(Qwen2.5-14B; it spawnsdemos/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 aSecurityManageran input screen of your own (an SSN screen), prove the screen withInputScreenCasethroughcheck_conformance, and run an agent under it throughToolExecutor; 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 withcheck_conformance, then search it from an agent throughRAGQueryTool(SimpleRetriever(store)).
evaluation
demos/evaluation/demo_evaluation_grid.py: Evaluate your own agent on your own tasks: threeTaskSpecword problems whose async checkers read only the final answer and answer aCheckResult, an asyncAgentBuilderthat builds a newSimpleAgentfor every run, with and withoutSimpleCalculatorTool, two cells run througharun_cellwith eachCellResult.directoryand its per-taskTaskResults printed, and theSUMMARY.mdthatwrite_reportwrites, one row per label (Qwen2.5-7B, greedy).
autograders
demos/autograders/demo_committee_of_agents_coding_autograder.pyanddemos/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 indemos/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, andFinalAnswer- that flow between all components.tool_executor.py/tool_registry.py: TheToolExecutorthat dispatches every tool call, and theToolRegistry(fed by anyToolSource, such as MCP, tool search or per-step filtering).types.py: Domain data types such asDocument,GradingCriterion, andFinalGrade.prompts/: The prompt engineering package - prompt item types initems.py, builders inbuilders.py, the wire models inmodels.py, and lazy re-exports of every public name from__init__.py.config.py/config_schemas.py: Pydantic-validated configuration loading, and theMCPServerConfigschema.
modules/: Contains the concrete implementations of the interfaces.mal/: The Model Abstraction Layer, with adapters forOpenAIAdapter,AnthropicAdapter,GeminiAdapter,OllamaAdapter,HuggingFaceAdapter, andLoadBalancerAdapter(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, whosereply_format(ReplyFormat.JSON_ACTIONby default, orReplyFormat.KEY_VALUEfor smaller/local models) andmax_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) andMCPServer. The client supports thestdio,SSEandStreamable HTTPtransports, with a bearer token on the HTTP ones; the server serves stdio.action/: The tool library - built-in tools (SimpleCalculatorTool, the rooted file toolsReadFileTool,ListDirTool,GlobTool,GrepTool,WriteFileTool(creates a new file),EditFileTool(replaces one exact, unique substring of an existing file) andReplaceFileTool(replaces an existing file's whole text), andShellTool, 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 withMCPServerConfigand fed to its registry by anMCPToolSource.memory/: The shipped compactors that bound the session log's view (WindowCompactor,SummarizingCompactor), the shipped context providers (FileContextProvider,RecallContextProvider), the long-term memoryVectorLongTermMemorythat keeps messages across sessions in any vector store, and the RAG components (FaissVectorStore,ChromaDBVectorStore,InMemoryVectorStore,SentenceTransformerEmbedder,SimpleRetriever,CrossEncoderRerankingRetriever), all importable fromfairlib.communication/: Agent-to-agent communication (InMemoryCommunicator).orchestration/:JobRunner, which claims a job from a work queue and runs an agent on it, andFileJobStore.security/:LocalWorkspace, the backend aSecurityManageris 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 iscore/sandbox_worker.py, and the driver over any backend iscore/managed_workspace.pywithcore/stream_run.py).
config/: Centralized YAML configuration (settings.yml).utils/: Utility code -document_processor,chunkingandresponse_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.
Metadata
Release files for fair-llm 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fair_llm-1.0.0.tar.gz | 1.5 MB | Without provenance | Details for fair_llm-1.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fair_llm-1.0.0-py3-none-any.whl | Python 3 | none | any | Details for fair_llm-1.0.0-py3-none-any.whl |
Total release size: 2.7 MB
Release files / fair_llm-1.0.0.tar.gz
| Download URL | fair_llm-1.0.0.tar.gz |
|---|---|
| Size | 1.5 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
dcc47d21060f6b57c13bae19e90770abaed6a1849e5933acdcdde2374f2c66cf
|
|
BLAKE2b-256 checksum How to use checksums |
4db7cff84281a3085929a5b23177bab2e6d58f9a94d780b7f34ebe1ef4c3064b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.3
|
Release files / fair_llm-1.0.0-py3-none-any.whl
| Download URL | fair_llm-1.0.0-py3-none-any.whl |
|---|---|
| Size | 1.2 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
bafd5bc91a5c539f8d708b7dfad485fd95ed071da493a13233a0fca52a053797
|
|
BLAKE2b-256 checksum How to use checksums |
2a8da8056be87ec89b68e1b27f6a8dd196eb8580069e3b568a1cfe3f38339834
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.3
|
Security for fair-llm 1.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.