Skip to main content

FOLIO Python Library

FOLIO Logo

PyPI version License: MIT Python Versions

The FOLIO Python Library provides a simple and efficient way to interact with the Federated Open Legal Information Ontology (FOLIO).

FOLIO is an open, CC-BY licensed standard designed to represent universal elements of legal data, improving communication and data interoperability across the legal industry.

Features

  • Load the FOLIO ontology from GitHub or a custom HTTP URL
  • Search for classes by label or definition
  • Query concepts with composable text and structural filters (label, definition, branch, parent, regex, etc.)
  • Query properties by label, definition, domain, range, and inverse
  • Get subclasses and parent classes
  • Access detailed information about each class, including labels, definitions, and examples
  • Explore semantic relationships through object properties
  • Find connections between entities using labeled relationships
  • Analyze property usage, domains, and ranges
  • Convert classes to OWL XML, JSON-LD, or Markdown format

Who it's for

  • Legal-tech developers who need a legal taxonomy in-process — no server, no SPARQL endpoint, just pip install and an OWLClass.
  • Data and ML engineers tagging documents, matters, or intake narratives against a standard concept set (this library is the ontology layer under folio-enrich, folio-insights, folio-resolve, folio-api, and alea-intake).
  • Ontologists and researchers exploring FOLIO's classes, object properties, and the triples that connect them.
  • Firms and vendors mapping internal taxonomies to a shared standard for interoperability.

Typical use cases: resolve a free-text label to a FOLIO IRI; enumerate an Area of Law branch to populate a picker; walk folio:drafted-style object properties to find how two concepts relate; serialize a concept as JSON-LD for a knowledge graph; let an LLM pick the right concept from a candidate set.

Changelog

The changelog can be found at CHANGES.md.

Installation

You can install the FOLIO Python library using pip:

pip install folio-python

For search features (fuzzy matching, prefix search, LLM-powered search):

pip install folio-python[search]

Note: The base install includes only pydantic, lxml, and httpx. Search features (search_by_label, search_by_definition, search_by_prefix, query with fuzzy mode, and LLM search) require the [search] extra, which adds rapidfuzz, marisa-trie, and alea-llm-client.

On Python 3.13+, the optional [kaos] extra adds kaos-nlp-core (Rust BM25 indices that release the GIL). search_by_label then uses a character-trigram BM25 index (typo- and word-order-tolerant) and search_by_definition a word BM25 index, instead of a RapidFuzz scan; scores stay on a 0-100 scale. On older Pythons the extra installs nothing and RapidFuzz is used unchanged. Set FOLIO_SEARCH_BACKEND=rapidfuzz to force the RapidFuzz path.

pip install "folio-python[search,kaos]"

For the latest development version, you can install directly from GitHub:

pip install --upgrade "folio-python[search] @ https://github.com/alea-institute/folio-python/archive/refs/heads/main.zip"

Quick Start

Here's a simple example to get you started with the FOLIO Python library:

from folio import FOLIO

# Initialize the FOLIO client
folio = FOLIO()

# Search by prefix
results = folio.search_by_prefix("Mich")
for owl_class in results:
    print(f"Class: {owl_class.label}")

# Search for a class by label
results = folio.search_by_label("Mich")
for owl_class, score in results:
    print(f"Class: {owl_class.label}, Score: {score}")

# Get all areas of law
areas_of_law = folio.get_areas_of_law()
for area in areas_of_law:
    print(area.label)

# Working with object properties
properties = folio.get_all_properties()
print(f"Number of object properties: {len(properties)}")

# Get properties by label
drafted_properties = folio.get_properties_by_label("folio:drafted")
for prop in drafted_properties:
    print(f"Property: {prop.label}")
    print(f"Domain: {[folio[d].label for d in prop.domain if folio[d]]}")
    print(f"Range: {[folio[r].label for r in prop.range if folio[r]]}")

# Find connections between entities
connections = folio.find_connections(
    subject_class="https://folio.openlegalstandard.org/R8CdMpOM0RmyrgCCvbpiLS0",  # Actor/Player
    property_name="folio:drafted"
)
for subject, property_obj, object_class in connections:
    print(f"{subject.label} {property_obj.label} {object_class.label}")

Structured Queries

Use query() and query_properties() for precise, composable filtering:

from folio import FOLIO

folio = FOLIO()

# Find concepts with "trust" in any text field, limited to Area of Law branch
results = folio.query(any_text="trust", branch="AREA_OF_LAW")
for cls in results:
    print(f"{cls.label}: {cls.definition}")

# Regex match on labels
results = folio.query(label="^Contract", match_mode="regex", limit=5)

# Leaf concepts (no children) within a specific parent
results = folio.query(
    parent_iri="RSYBzf149Mi5KE0YtmpUmr",  # Area of Law
    has_children=False,
    limit=10,
)

# Find properties that have an inverse
props = folio.query_properties(has_inverse=True)
for p in props:
    print(f"{p.label} <-> {p.inverse_of}")

Combine class selections with property filters

Structured-query recipes provide three small functions that accept an already loaded FOLIO graph:

Recipe Inputs and result
classes_in_branch A text substring and branch name select a list of OWLClass descendants. Text can match a label, definition, alternative label, example, note, comment, or description.
properties_between A property-label substring plus domain and range IRIs select a list of OWLObjectProperty objects. Full and short IRIs work. Optional has_inverse=True requires an inverse declaration; False excludes it; None accepts either.
connections_between_branches Source and target text/branch selections plus a property-label substring produce (source class, property, target class) tuples. A property matching several pairs appears once for each pair.

These are repository examples: clone the repository and run Python from its root, or copy the recipe source into your project. Installing folio-python alone does not install the examples module. Importing the recipes does not load a graph. The FOLIO() construction above loads ontology data immediately and may download it or initialize an optional LLM client; use_cache=False does not make construction offline. The three recipes use substring matching and do not require the optional search dependencies or make LLM calls.

For example, reuse the folio graph above to look for declared properties between trust-related areas of law and trustees:

from examples.structured_queries import connections_between_branches

connections = connections_between_branches(
    folio,
    source_text="trust",
    source_branch="AREA_OF_LAW",
    target_text="trustee",
    target_branch="ACTOR_PLAYER",
    property_text="has",
)
for source, prop, target in connections:
    print(f"{source.label} -- {prop.label} --> {target.label}")

Results depend on the loaded ontology and may be empty. The synthetic test fixture yields nine associations for this call; those fixture labels and counts are not promises about the live ontology. Each recipe returns [] when its filters have no common match. The composition also returns [] if either class selection is empty.

Interpret the results

  • Filters intersect. Each supplied filter must match. Within any_text, a match in any supported class text field is enough. Text filters are optional; structural filters can be used alone. query_properties() has no branch or any_text argument, so the composed recipe passes selected class IRIs to it.
  • Branches select descendants. Branch enum names (such as AREA_OF_LAW) and values (such as Area of Law) are case-insensitive strings. Branch and parent_iri filters exclude the root and traverse descendants up to the current maximum depth of 16. An unknown branch produces [].
  • Property endpoints are explicit declarations. Both domain_iri and range_iri must be present in the property's stored declarations. A declaration on an ancestor does not automatically match a descendant. The composition reports matching declarations; it does not infer applicability or assert a relationship between instances.
  • Match modes differ. "substring" (the default) and "regex" ignore case; "exact" is case-sensitive. "fuzzy" requires the optional search dependency.
  • Limits select partial results. Use positive limits. Both query methods return the first matches in stored iteration order, without an alphabetical or relevance-order guarantee. Each recipe's limit defaults to 20. The composed recipe instead has independent source_limit=5, target_limit=5, and property_limit_per_pair=3 defaults: at most 75 rows, with the property limit applied separately to every pair. This is a bounded selection, not an exhaustive join; raising only the property limit cannot recover classes omitted by the source or target limit.

Executable coverage

Every query example in this section is backed by the named tests in test_structured_query_examples.py. They parse fixed RDF/XML, replace ontology loading, and disable optional search and LLM backends, so they require no ontology download or LLM call:

uv run pytest tests/test_structured_query_examples.py
Example Backing tests
Text plus branch snippet test_readme_text_and_branch
Regex labels snippet test_readme_regex_labels
Parent plus leaf snippet test_readme_leaf_descendants
Inverse-only properties snippet test_readme_inverse_properties
Import recipes without constructing a graph test_recipe_import_does_not_construct_graph
Class text and branch recipe test_classes_in_branch, test_class_filters_empty_intersection
Property text, domain, range, and inverse recipe test_properties_between, test_property_endpoints_are_explicit, test_property_filters_empty_intersection
Composed recipe and call above test_connections_between_branches, test_composition_empty_results, test_composition_limits

The existing integration tests also cover query filters against a loaded ontology, including test_query_combined_filters, test_query_regex, test_query_by_parent_iri, test_query_has_children, and test_query_properties_has_inverse.

Searching with an LLM

from folio import FOLIO

# Default: uses gpt-5.1-mini via OpenAI
folio = FOLIO()

# Recommended: gpt-5.4 with low effort and flex tier (1.8s avg, best quality)
folio = FOLIO(effort="low", tier="flex")

# Best value: Grok 4 Fast (1.1s avg, $0.20/M input tokens)
from alea_llm_client import GrokModel
folio = FOLIO(llm=GrokModel(model="grok-4-fast-non-reasoning"))

# Any provider works — effort/tier auto-translate to provider-specific params
from alea_llm_client import GoogleModel
folio = FOLIO(llm=GoogleModel(model="gemini-3-flash-preview"), effort="low")
# Search with an LLM
async def search_example():
    for result in await folio.parallel_search_by_llm(
        "redline lease agreement",
        search_sets=[
            folio.get_areas_of_law(max_depth=1),
            folio.get_player_actors(max_depth=2),
        ],
    ):
        print(result)

import asyncio
asyncio.run(search_example())

LLM search uses the alea_llm_client to provide abstraction across multiple APIs and providers. Requires pip install folio-python[search].

LLM Benchmark Results

Tested on FOLIO ontology search across 5 legal queries (March 2026):

Config Avg Latency Avg Results Cost/M input
grok-4-fast-non-reasoning 1.1s 4.0 $0.20
gpt-5.4 effort=low tier=flex 1.8s 3.8 $2.50
gemini-3-flash-preview effort=low 3.6s 4.8 low
gpt-4.1-mini 1.7s 4.0 $0.40

Avoid effort: "high" — benchmarks show 5x latency with no quality improvement for structured search tasks.

Migrating from soli-python? The soli-python package (v0.1.x) has been renamed to folio-python. Uninstall the old package (pip uninstall soli-python) and install folio-python to avoid dependency conflicts.

Documentation

The full library reference lives on the FOLIO standards site:

openlegalstandard.org/resources/folio-python-library

It covers installation, initialization, fuzzy and prefix search, structured queries, taxonomy traversal, object properties and triples, serialization, LLM integration, and a complete API reference for FOLIO, OWLClass, OWLObjectProperty, and FOLIOConfiguration. Every code example is validated against the published wheel.

Contributing

We welcome contributions to the FOLIO Python library! If you'd like to contribute, please follow these steps:

  1. Fork the repository
  2. Create a new branch for your feature or bug fix
  3. Make your changes and write tests if applicable
  4. Run the test suite to ensure everything is working
  5. Submit a pull request with a clear description of your changes

For more information, see our contribution guidelines.

FOLIO API

A public, freely-accessible API is available for the FOLIO ontology.

The API is hosted at https://folio.openlegalstandard.org/.

The source code for the API is available on GitHub at https://github.com/alea-institute/folio-api.

License

The FOLIO Python library is released under the MIT License. See the LICENSE file for details.

The ontology data this library fetches and redistributes at runtime is a separate work: FOLIO is licensed CC-BY 4.0, so any application built on this library must carry that attribution. Dependency licenses and the full attribution notice are in THIRD-PARTY.md.

Support

If you encounter any issues or have questions about using the FOLIO Python library, please open an issue on GitHub.

Learn More

To learn more about FOLIO, its development, and how you can get involved, visit the FOLIO website or join the FOLIO community forum.

Metadata

Release files for folio-python 0.4.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for folio-python 0.4.2
File Size Uploaded Provenance Actions
folio_python-0.4.2.tar.gz 45.4 kB Without provenance Details for folio_python-0.4.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for folio-python 0.4.2
File Interpreter ABI Platform Actions
folio_python-0.4.2-py3-none-any.whl Python 3 none any Details for folio_python-0.4.2-py3-none-any.whl

Total release size: 92.3 kB

Release files / folio_python-0.4.2.tar.gz

Download URL folio_python-0.4.2.tar.gz
Size 45.4 kB
Tags Source
SHA-256 checksum
How to use checksums
8345ef1fb05d58a6628dd64a48337aaead296db6554bdd77e77f3c6eb771e627
BLAKE2b-256 checksum
How to use checksums
dfa7c55df4524cf26ab75c8f473ac2221c910a0fccfead4d551773ac2cb78430
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.17

Release files / folio_python-0.4.2-py3-none-any.whl

Download URL folio_python-0.4.2-py3-none-any.whl
Size 46.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b9e291758cca045b0308cadf01e50e92799b56d9349f7628875f2efb3771e877
BLAKE2b-256 checksum
How to use checksums
ba6d94be01c07fd6d68d63a14a5a5e2db5dab12dc16bdb2dd9dfbe2a192187ec
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.17

Security for folio-python 0.4.2

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page