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

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.535
File Size Uploaded Provenance Actions
pytrilogy-0.3.535.tar.gz 2.0 MB With provenance Details for pytrilogy-0.3.535.tar.gz

Built distributions (wheels)

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

Total release size: 19.7 MB

Release files / pytrilogy-0.3.535.tar.gz

Download URL pytrilogy-0.3.535.tar.gz
Size 2.0 MB
Tags Source
SHA-256 checksum
How to use checksums
e42b469a5c97d46bff38f224f7a09acd991169df72ecf3992ddc4cfbebbabc77
BLAKE2b-256 checksum
How to use checksums
4206ae8fadaaa8c22495a1451ad21e97f6f6470b80780e40959052c679e172f8
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 23, 2026.

Transparency log

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

Download URL pytrilogy-0.3.535-cp314-cp314-pyemscripten_2026_0_wasm32.whl
Size 2.6 MB
Tags CPython 3.14 PyEmscripten 2026.0+ WebAssembly
SHA-256 checksum
How to use checksums
fdb4cbda8b824af3fd122d1e6199e0beb97d9ed3ffac3a0271dfc6af1fd400a2
BLAKE2b-256 checksum
How to use checksums
1ace5d6a68cb3728435cdde3ebb93a87c018490db0eb367d49b65ff18dd2cd24
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 23, 2026.

Transparency log

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

Download URL pytrilogy-0.3.535-cp311-abi3-win_amd64.whl
Size 3.0 MB
Tags CPython 3.11 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
ba066f141935cf30abdf2ee98dd4730dbb82293e10bb668eea2e0944ed3608d1
BLAKE2b-256 checksum
How to use checksums
ee28394fe73b4dceba4e645e197bda6514e4585dc837993a6ceb0568df518cd3
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 23, 2026.

Transparency log

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

Download URL pytrilogy-0.3.535-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 3.1 MB
Tags CPython 3.11 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
4737eba81253369702587a881b6526985488f2b22d221799ac15aab5d390ad65
BLAKE2b-256 checksum
How to use checksums
d2cd4b05140d6c2b849b26237e193317da8291c6864272653366fbc76ea9b5a8
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 23, 2026.

Transparency log

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

Download URL pytrilogy-0.3.535-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
0b6bbb145d170062aa366bfd8df8e0e1508367091129ea25b55a7b2dc63afdd6
BLAKE2b-256 checksum
How to use checksums
82ea6ef6bd2c0fa72d32dac1aee7123e65ccfd064586f478f7b8c753f0023c55
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 23, 2026.

Transparency log

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

Download URL pytrilogy-0.3.535-cp311-abi3-macosx_11_0_arm64.whl
Size 3.0 MB
Tags CPython 3.11 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
17c0ed989fc27e2edf5414fe995c4903a0fd71a4b50b705b54aae40a40ec92e8
BLAKE2b-256 checksum
How to use checksums
54568eca431ab1f2ca8646db003501030912bd142298be24ea59459cfae26384
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 23, 2026.

Transparency log

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

Download URL pytrilogy-0.3.535-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
a949e7f8c956780d54c0c82b6f953b26f0dd97b439eaf6b55ad7d604637aa8ec
BLAKE2b-256 checksum
How to use checksums
1a105fad7c639befacc4b261444ef86de00fcd8226a0683d2299407a36f30606
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 23, 2026.

Transparency log

Security for pytrilogy 0.3.535

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.535.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 23, 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.535 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