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.505

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.505
File Size Uploaded Provenance Actions
pytrilogy-0.3.505.tar.gz 1.9 MB With provenance Details for pytrilogy-0.3.505.tar.gz

Built distributions (wheels)

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

Total release size: 19.2 MB

Release files / pytrilogy-0.3.505.tar.gz

Download URL pytrilogy-0.3.505.tar.gz
Size 1.9 MB
Tags Source
SHA-256 checksum
How to use checksums
9e5024d57a03f87115d15f6de47bc02472b5632c70bcb0b0b1409fb91275de5b
BLAKE2b-256 checksum
How to use checksums
1b8efe917c9ec398cf798fdb35d717387c6a30ca1c20f2ef19fabb414d5bf88c
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 15, 2026.

Transparency log

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

Download URL pytrilogy-0.3.505-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
6bb7b539c8756b45b6af52bad1bf6fc1413d1a7a3169c0d4d87d9cf64f79c08f
BLAKE2b-256 checksum
How to use checksums
b8e7d06c48283a4be0e8fc3a89b78ae5ff60c4b2e99252de4719232835a8bb7b
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 15, 2026.

Transparency log

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

Download URL pytrilogy-0.3.505-cp311-abi3-win_amd64.whl
Size 2.9 MB
Tags CPython 3.11 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
6f29a18d5180fce8205e7fc5e49d38074c7ede92a18e963b9daa94a7139ddc35
BLAKE2b-256 checksum
How to use checksums
18e438ecbba553f68d87b52550b7a46493fbbfa1e47dc07b05e15262b43cc607
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 15, 2026.

Transparency log

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

Download URL pytrilogy-0.3.505-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
14b775e771008dc9dc884c804be5bfa7c71fe2b219cacbf7f4ce06aee801ef82
BLAKE2b-256 checksum
How to use checksums
3ad32cabd51fca15c9baa86a07a5ee12ceceefb884c2b44f10613f19d9d8dba1
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 15, 2026.

Transparency log

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

Download URL pytrilogy-0.3.505-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
Size 2.9 MB
Tags CPython 3.11 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
b17a39f23f11bfa7dc91ee39838f152a360092f65861f53de8e385a88f7b7c89
BLAKE2b-256 checksum
How to use checksums
afb6de2bc3bc012c4cb1919c9c822712955ab8b305a3505c1f23ffa0a43085e8
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 15, 2026.

Transparency log

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

Download URL pytrilogy-0.3.505-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
8d488051a79cb3690a043e8bef61ba4ffdc3e81a068655dbe3b032ab0150f19e
BLAKE2b-256 checksum
How to use checksums
7f3a82d2d4736a17ed7861119ff8a700fed1f06af0108f1444c0d9dce11a6fc8
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 15, 2026.

Transparency log

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

Download URL pytrilogy-0.3.505-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
42138cfb8a906641bd0031e8c87162bce95b51a655dec1ef049316f03d2a633e
BLAKE2b-256 checksum
How to use checksums
5058b80a8afee604fb541f31ce59f5e42d9f5405fca00963827b0dd5290f28dc
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 15, 2026.

Transparency log

Security for pytrilogy 0.3.505

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.505.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 15, 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.505 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