Skip to main content

Website Discord PyPI version

Trilogy is a batteries-included data-productivity toolkit that accelerates SQL-based analytics with a typed, expressive language. It's great for humans - and even better for agents. Start with a single file and scale fast with a rich ecosystem, including UI and CLI tooling, public models to get started, rich python integration, and modern visuals and reporting.

Why Trilogy

SQL is the best way to work with data with but shows strain at scale and as it ages. Can we have the pros without the cons? We believe you can.

Trilogy adds a lightweight semantic layer to keep SQL fast through the full lifecycle of analytics - from exploration to production. It provides a full stack for interactive, visualization, and orchestration that can be adopted incrementally and without lock-in; start with checking types and asking agents questions; end with a more efficient and productive warehouse.

Headline features:

  • No manual joins; no from clause
  • Reusable models, types, and functions
  • Safe refactoring across queries
  • Supports all standard engines: BigQuery, DuckDB, Snowflake, Databricks, ClickHouse, Postgres and more
  • Easy to write - for humans and AI
  • Built-in semantic layer without boilerplate or YAML

This repo contains pytrilogy, the reference implementation of the core language and CLI.

Install To try it out, include both the CLI and serve dependencies.

pip install pytrilogy[cli,serve]

or

uv tool install "pytrilogy[cli,serve]"

Docs and Website

Hello World

Trilogy includes a public model registry with prebuilt models to let you get started on the data work fast. Run the below to import, query, and explore one of these models directly.

# 1. Pull a public model (fetches its .preql files, examples, and trilogy.toml).
trilogy public fetch faa ./faa-demo
cd faa-demo

# 2. Run a quick adhoc query (--import prepends the import for you — discover
# what's available with `trilogy explore flight.preql`)
trilogy run --import flight "select aircraft.model.name, count order by count desc limit 5;"

# Plot it
trilogy run --import flight "chart layer barh ( y_axis <- carrier.name, x_axis <- count(id) as flight_count ) order by flight_count desc limit 10;"

# 3. Build the rollup declared in example.preql (see below)
trilogy refresh example.preql

# 4. Same query, with the rollup in scope: it now reads daily_airplane_usage
# instead of joining the raw flights to aircraft and models
trilogy run --import example "select aircraft.model.name, count order by count desc limit 5;"

# 5. Launch the Studio UI against the live model (opens your browser) to explore + query
trilogy serve .

trilogy serve . --mcp (install pytrilogy[mcp]) also exposes the model to agents as an MCP server at http://localhost:8100/mcp, with tools to list models, describe their fields, read the syntax reference and run queries:

claude mcp add --transport http trilogy http://localhost:8100/mcp

serve binds to localhost by default, where /mcp needs no token (the MCP SDK's Host/Origin checks guard it). --host 0.0.0.0 exposes the server to the network; then /mcp requires the printed token as an X-Trilogy-Token header, since queries can run arbitrary SQL.

example.preql declares the rollup. The query never names it: the planner answers from any datasource that holds the concepts at the query's grain or finer, re-aggregating as needed, so the physical layer can change without touching what consumes it.

import flight;

# derive reusable concepts
auto flight_date <- dep_time::date;

# a rollup: once `trilogy refresh` builds it, queries for `count` at this grain
# or coarser (e.g. by aircraft.model.name alone) read it instead of raw flights
datasource daily_airplane_usage (
    flight_date,
    aircraft.model.name,
    count
)
grain (flight_date, aircraft.model.name)
address daily_airplane_usage;

Browse other available models with trilogy public list (filter with --engine duckdb or --tag benchmark). Every model in trilogy-public-models is pullable.

Principles

Versus SQL, Trilogy aims to:

Keep:

  • Correctness
  • Accessibility

Improve:

  • Simplicity
  • Refactoring and maintainability
  • Reusability and composability
  • Expressivness

Maintain:

  • Acceptable performance

Backend Support

Backend Status Install Notes
BigQuery Core pytrilogy[bigquery] Full support
DuckDB Core included Full support
Snowflake Core pytrilogy[snowflake] Full support
SQLite Core included Full support
ClickHouse Beta pytrilogy[clickhouse] or pytrilogy[chdb] (embedded) Executed in tests through embedded chdb; server smoke tests opt-in
Databricks Experimental pytrilogy[databricks] Smoke-tested against a SQL warehouse; opt-in live tests
Postgres Experimental pytrilogy[postgres] Rendering tests only
MySQL Experimental pytrilogy[mysql] Rendering tests only
Trino Experimental trino driver Rendering tests only
Presto Experimental pyhive driver Rendering tests only
SQL Server Experimental — SQL generation only; no built-in connection
Dataframe Experimental pandas pandas DataFrames queried through DuckDB

Syntax Overview

Trilogy preql models are compositions of types, keys, and properties

Save the following code in a file named hello.preql

# semantic model is abstract from data

type word string; # types can be used to provide expressive metadata tags that propagate through dataflow

key sentence_id int;
property sentence_id.word_one string::word; # comments after a definition 
property sentence_id.word_two string::word; # are syntactic sugar for adding
property sentence_id.word_three string::word; # a description to it

# comments in other places are just comments

# define our datasource to bind the model to data
# for most work, you can import something already defined
# testing using query fixtures is a common pattern
datasource word_one(
    sentence: sentence_id,
    word:word_one
)
grain(sentence_id)
query '''
select 1 as sentence, 'Hello' as word
union all
select 2, 'Bonjour'
''';

datasource word_two(
    sentence: sentence_id,
    word:word_two
)
grain(sentence_id)
query '''
select 1 as sentence, 'World' as word
union all
select 2 as sentence, 'World'
''';

datasource word_three(
    sentence: sentence_id,
    word:word_three
)
grain(sentence_id)
query '''
select 1 as sentence, '!' as word
union all
select 2 as sentence, '!'
''';

def concat_with_space(x,y) -> x || ' ' || y;

# an actual select statement
# joins are automatically resolved between the 3 sources
with sentences as
select sentence_id, @concat_with_space(word_one, word_two) || word_three as text;

WHERE 
    sentences.sentence_id in (1,2)
SELECT
    sentences.text
;

Run it:

trilogy run hello.preql duckdb

UI Preview

Python SDK Intro

Use the python SDK to embed Trilogy in larger python workflows.

A BigQuery example, similar to the BigQuery quickstart:

from trilogy import Dialects, Environment

environment = Environment()

environment.parse('''
key name string;
key gender string;
key state string;
key year int;
key yearly_name_count int; int;

datasource usa_names(
    name:name,
    number:yearly_name_count,
    year:year,
    gender:gender,
    state:state
)
address `bigquery-public-data.usa_names.usa_1910_2013`;
''')

executor = Dialects.BIGQUERY.default_executor(environment=environment)

results = executor.execute_text('''
WHERE
    name = 'Elvis'
SELECT
    name,
    sum(yearly_name_count) -> name_count 
ORDER BY
    name_count desc
LIMIT 10;
''')

# multiple queries can result from one text batch
for row in results:
    # get results for first query
    answers = row.fetchall()
    for x in answers:
        print(x)

LLM Usage

Connect to your favorite provider and generate queries with confidence.

from trilogy import Environment, Dialects
from trilogy.ai import Provider, text_to_query
import os

executor = Dialects.DUCK_DB.default_executor(
    environment=Environment(working_path=Path(__file__).parent)
)

api_key = os.environ.get(OPENAI_API_KEY)
if not api_key:
    raise ValueError("OPENAI_API_KEY required for gpt generation")
# load a model
executor.parse_file("flight.preql")
# create tables in the DB if needed
executor.execute_file("setup.sql")
# generate a query
query = text_to_query(
    executor.environment,
    "number of flights by month in 2005",
    Provider.OPENAI,
    "gpt-5.5",
    api_key,
)

# print the generated trilogy query
print(query)
# run it
results = executor.execute_text(query)[-1].fetchall()
assert len(results) == 12

for row in results:
    # all monthly flights are between 5000 and 7000
    assert row[1] > 5000 and row[1] < 7000, row

CLI Usage

Trilogy can be run through a CLI tool, also named 'trilogy'.

Basic syntax:

trilogy run <cmd or path to trilogy file> <dialect>

With backend options:

trilogy run "key x int; datasource test_source(i:x) grain(x) address test; select x;" duckdb --path <path/to/database>

Format code:

trilogy fmt <path to trilogy file>

Browse and pull public models:

trilogy public list [--engine duckdb] [--tag benchmark]
trilogy public fetch <model-name> [<dir>] [--no-examples]

Fetches model source files, setup scripts, and a ready-to-use trilogy.toml from trilogy-public-models into a local directory so you can immediately refresh and serve it.

Managing workspace files from the CLI

trilogy file has shell-agnostic CRUD operations on the filesystem.

trilogy file list .                      # list entries (-r for recursive, -l for size)
trilogy file read reporting.preql        # dump contents to stdout
trilogy file write path --content "..."  # create/overwrite from a string
trilogy file write path --from-file src  # copy from a local file
trilogy file write path --from-url URL   # fetch from http(s):// or file:// URL
trilogy file delete path --recursive     # remove a file or directory
trilogy file move old.preql new.preql    # rename within a backend
trilogy file exists path                 # exit 0 if present, 1 otherwise

Backend Configuration

BigQuery:

  • Uses applicationdefault authentication (TODO: support arbitrary credential paths)
  • In Python, you can pass a custom client

DuckDB:

  • --path - Optional database file path

Postgres:

  • --host - Database host
  • --port - Database port
  • --username - Username
  • --password - Password
  • --database - Database name

Snowflake:

  • --account - Snowflake account
  • --username - Username
  • --password - Password

Databricks:

  • --host - Workspace hostname (default: DATABRICKS_HOST)
  • --http_path - SQL warehouse HTTP path (default: DATABRICKS_HTTP_PATH)
  • --access_token - Personal access token (default: DATABRICKS_TOKEN)
  • --catalog / --schema - Optional default catalog and schema

Config Files

The CLI can pick up default configuration from a config file in the toml format. Detection will be recursive form parent directories of the current working directory, including the current working directory.

This can be used to set

  • default engine and arguments
  • parallelism for execute for the CLI
  • any startup commands to run whenever creating an executor.
# Trilogy Configuration File
# Learn more at: https://github.com/trilogy-data/pytrilogy

[engine]
# Default dialect for execution
dialect = "duck_db"

# Parallelism level for directory execution
# parallelism = 2

# Connection parameters for the dialect; ${env:VAR} reads an environment variable
[engine.config]
# db_location = "local.duckdb"

# Startup scripts to run before execution
[setup]
# startup_trilogy = []
sql = ['setup/setup_dev.sql']

trilogy init [path] [dialect] scaffolds this file, alongside root/ (where trilogy ingest writes generated models by default), jobs/, and an example script. Passing a dialect (trilogy init . bigquery) pins engine.dialect and stubs out that dialect's connection parameters in [engine.config]. Init refuses to run over an existing trilogy.toml; --force overwrites it and leaves every other file untouched.

Declared dependencies

Directory runs (trilogy run .) order scripts by what they import, declare and persist, and a script whose upstream failed is skipped. A [dependencies] table declares the one kind of edge content cannot express — a script that runs because another one failed:

[dependencies]
"repair.preql" = { after = ["refresh.preql"], when = "failed" }

when is completed (the default, and the derived-edge rule), failed, or always. A failed script stands down as a successful skip when its upstreams held, so the run stays green — and anything downstream of it stands down the same way, since the script it was waiting on never ran. It runs when one of them broke, and anything it hands back — a called program printing ::trilogy-output name=fix_pr value=https://… — is listed under Outputs after the summary and recorded in the --report-file report. Paths are relative to the toml, and naming a script the run does not manage is an error.

More Resources

Python API Integration

Root Imports

Are stable and should be sufficient for executing code from Trilogy as text.

from pytrilogy import Executor, Dialect

Authoring Imports

Are also stable, and should be used for cases which programatically generate Trilogy statements without text inputs or need to process/transform parsed code in more complicated ways.

from pytrilogy.authoring import Concept, Function, ...

Contributing

Clone repository and install requirements.txt and requirements-test.txt.

Please open an issue first to discuss what you would like to change, and then create a PR against that issue.

Similar Projects

Trilogy combines two aspects: a semantic layer and a query language. Examples of both are linked below:

Semantic layers - tools for defining a metadata layer above SQL/warehouse to enable higher level abstractions:

Better SQL has been a popular space. We believe Trilogy takes a different approach than the following, but all are worth checking out. Please open PRs/comment for anything missed!

Metadata

Release files for pytrilogy 0.3.516

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

Source distribution (sdist)

Source distribution for pytrilogy 0.3.516
File Size Uploaded Provenance Actions
pytrilogy-0.3.516.tar.gz 2.0 MB With provenance Details for pytrilogy-0.3.516.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for pytrilogy 0.3.516
File Actions
pytrilogy-0.3.516-cp314-cp314-pyemscripten_2026_0_wasm32.whl CPython 3.14 CPython 3.14 PyEmscripten 2026.0+ WebAssembly Details for pytrilogy-0.3.516-cp314-cp314-pyemscripten_2026_0_wasm32.whl
pytrilogy-0.3.516-cp311-abi3-win_amd64.whl CPython 3.11 abi3 Windows x86-64 Details for pytrilogy-0.3.516-cp311-abi3-win_amd64.whl
pytrilogy-0.3.516-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.11 abi3 Linux glibc 2.17+ x86-64 Details for pytrilogy-0.3.516-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
pytrilogy-0.3.516-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl CPython 3.11 abi3 Linux glibc 2.17+ ARM64 Details for pytrilogy-0.3.516-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
pytrilogy-0.3.516-cp311-abi3-macosx_11_0_arm64.whl CPython 3.11 abi3 macOS 11.0+ ARM64 Details for pytrilogy-0.3.516-cp311-abi3-macosx_11_0_arm64.whl
pytrilogy-0.3.516-cp311-abi3-macosx_10_12_x86_64.whl CPython 3.11 abi3 macOS 10.12+ x86-64 Details for pytrilogy-0.3.516-cp311-abi3-macosx_10_12_x86_64.whl

Total release size: 19.4 MB

Release files / pytrilogy-0.3.516.tar.gz

Download URL pytrilogy-0.3.516.tar.gz
Size 2.0 MB
Tags Source
SHA-256 checksum
How to use checksums
ba2c4798bbaf0de62a4f287c390055694146b9f291831d3b87ed67da0818158d
BLAKE2b-256 checksum
How to use checksums
243bf5e0a59814c86ebba1bb89cb44d4d7681fca7ae24a38dfbf6666dc7dfbe2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / pytrilogy-0.3.516-cp314-cp314-pyemscripten_2026_0_wasm32.whl

Download URL pytrilogy-0.3.516-cp314-cp314-pyemscripten_2026_0_wasm32.whl
Size 2.5 MB
Tags CPython 3.14 PyEmscripten 2026.0+ WebAssembly
SHA-256 checksum
How to use checksums
342d54aee87c27f3ff4f7130ce9a11e067fc7a9e6911c8b056eb933f08bd061d
BLAKE2b-256 checksum
How to use checksums
9d1f7a055a5e00434e207f61331ac3dc5e3df482f9c46ad2a102408901375344
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / pytrilogy-0.3.516-cp311-abi3-win_amd64.whl

Download URL pytrilogy-0.3.516-cp311-abi3-win_amd64.whl
Size 3.0 MB
Tags CPython 3.11 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
e1fc8270f1b92a4a842eb6b4f6039b234c6f1dfa00e25e8865d4b60a689b9431
BLAKE2b-256 checksum
How to use checksums
d61097e32f7cdb389169cf3637f6f87133bc0fbe92091e810708df42289e2ce2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / pytrilogy-0.3.516-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL pytrilogy-0.3.516-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 3.0 MB
Tags CPython 3.11 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
806050b1d212711f180e3971f213bf5b81c06da18944d115684286a80b3bf52f
BLAKE2b-256 checksum
How to use checksums
287831c1af6c19472e764a90fb2787d8aa16ae2ddc5894ecfdb191f461858faa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / pytrilogy-0.3.516-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl

Download URL pytrilogy-0.3.516-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
Size 3.0 MB
Tags CPython 3.11 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
4121e8fea01db1e60bb695b518f422475f703b4e872cff60db7fcfda6122adb2
BLAKE2b-256 checksum
How to use checksums
7c28eabdf85ef1ed9bdfa684f2b273db73a2b93b8ab8035e74041278723d28cd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / pytrilogy-0.3.516-cp311-abi3-macosx_11_0_arm64.whl

Download URL pytrilogy-0.3.516-cp311-abi3-macosx_11_0_arm64.whl
Size 2.9 MB
Tags CPython 3.11 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
bcff35d1faf632bd10f4e36cbcba9127dcbb4b8d27788f5d1fdded7484737620
BLAKE2b-256 checksum
How to use checksums
6c693efadd4a39c3acff53d3ae32029822b0249a337c4c4ada53f07359e6e733
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / pytrilogy-0.3.516-cp311-abi3-macosx_10_12_x86_64.whl

Download URL pytrilogy-0.3.516-cp311-abi3-macosx_10_12_x86_64.whl
Size 3.0 MB
Tags CPython 3.11 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
fd5ba1295f9c81d912a05c6254fa04ec5eb34d6c4503be5db757eac8098f5058
BLAKE2b-256 checksum
How to use checksums
681deed7387a4d4d78b2844a26164879350c0bf3b81baab7c420fd18f19d336c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Security for pytrilogy 0.3.516

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.

Full provenance

All 7 files in this release have been uploaded with provenance metadata.

Select from 7 files

Attestation for pytrilogy-0.3.516.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

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.

Release history Release notifications | RSS feed

This release

0.3.516 This release

7 release files Full provenance

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