Python API

This reference is generated from trailhead docstrings and signatures. It covers the stable extension point (custom language adapters) and the core data/query APIs described in the Extending and HTTP API guides.

Application setup

Source code in src/trailhead/server/app.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def create_app(
    *,
    default_model: str = DEFAULT_MODEL,
    cache_dir: str | None = None,
    sqlite_db: str | None = None,
    watch_directory: str | None = None,
    preload_default_model: bool = True,
    run_indexer: bool = False,
    cors_origins: list[str] | None = None,
    rate_limit: int = 120,
) -> FastAPI:
    config = AppConfig(
        default_model=default_model,
        cache_dir=cache_dir,
        configured_sqlite_db=str(Path(sqlite_db).resolve()) if sqlite_db else None,
        configured_watch_directory=str(Path(watch_directory).resolve()) if watch_directory else None,
        preload_default_model=preload_default_model,
        run_indexer=run_indexer,
    )

    app = FastAPI(
        title="trailhead API",
        version="0.1.0",
        description="Warm-model API for embeddings and SQLite-backed code queries.",
        lifespan=_build_lifespan(config),
    )
    app.state.config = config

    if cors_origins:
        app.add_middleware(
            CORSMiddleware,
            allow_origins=cors_origins,
            allow_methods=["GET", "POST"],
            allow_headers=["Content-Type"],
        )

    if rate_limit > 0:
        app.add_middleware(RateLimitMiddleware, requests_per_minute=rate_limit)

    _register_routes(app)

    return app

Language adapters

Bases: ABC

Parse source files of a specific language into a PropertyGraph.

Subclasses must define a class-level extensions frozenset and implement :meth:parse. Optionally override :meth:is_available to report whether the required tree-sitter language package is installed.

Source code in src/trailhead/services/indexing/adapters/base.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
class LanguageAdapter(ABC):
    """Parse source files of a specific language into a PropertyGraph.

    Subclasses must define a class-level ``extensions`` frozenset and implement
    :meth:`parse`.  Optionally override :meth:`is_available` to report whether
    the required tree-sitter language package is installed.
    """

    extensions: frozenset[str]

    @classmethod
    def is_available(cls) -> bool:
        """Return True if the required tree-sitter language package is installed."""
        return True

    @classmethod
    def matches(cls, path: Path) -> bool:
        """Return True when this adapter should handle *path*.

        Called only after the file extension already matched. Adapters that own
        an extension outright should keep the default behavior and return True.
        Adapters sharing a generic extension can override this hook and inspect
        path shape and/or file contents.
        """
        return True

    @abstractmethod
    def parse(self, path: Path, graph: PropertyGraph) -> Vertex:
        """Parse *path*, populate *graph*, and return the module vertex."""
        ...

    def finalize(self, graph: PropertyGraph) -> None:
        """Finalize graph-level relationships after all files are parsed.

        Most adapters do not need a post-pass. Adapters that resolve cross-file
        references can override this hook.
        """
        return None

finalize(graph)

Finalize graph-level relationships after all files are parsed.

Most adapters do not need a post-pass. Adapters that resolve cross-file references can override this hook.

Source code in src/trailhead/services/indexing/adapters/base.py
175
176
177
178
179
180
181
def finalize(self, graph: PropertyGraph) -> None:
    """Finalize graph-level relationships after all files are parsed.

    Most adapters do not need a post-pass. Adapters that resolve cross-file
    references can override this hook.
    """
    return None

is_available() classmethod

Return True if the required tree-sitter language package is installed.

Source code in src/trailhead/services/indexing/adapters/base.py
154
155
156
157
@classmethod
def is_available(cls) -> bool:
    """Return True if the required tree-sitter language package is installed."""
    return True

matches(path) classmethod

Return True when this adapter should handle path.

Called only after the file extension already matched. Adapters that own an extension outright should keep the default behavior and return True. Adapters sharing a generic extension can override this hook and inspect path shape and/or file contents.

Source code in src/trailhead/services/indexing/adapters/base.py
159
160
161
162
163
164
165
166
167
168
@classmethod
def matches(cls, path: Path) -> bool:
    """Return True when this adapter should handle *path*.

    Called only after the file extension already matched. Adapters that own
    an extension outright should keep the default behavior and return True.
    Adapters sharing a generic extension can override this hook and inspect
    path shape and/or file contents.
    """
    return True

parse(path, graph) abstractmethod

Parse path, populate graph, and return the module vertex.

Source code in src/trailhead/services/indexing/adapters/base.py
170
171
172
173
@abstractmethod
def parse(self, path: Path, graph: PropertyGraph) -> Vertex:
    """Parse *path*, populate *graph*, and return the module vertex."""
    ...

Register adapter for all its declared extensions.

Source code in src/trailhead/services/indexing/adapters/registry.py
15
16
17
18
19
20
21
22
23
def register(adapter: LanguageAdapter) -> None:
    """Register *adapter* for all its declared extensions."""
    for ext in adapter.extensions:
        _registry.setdefault(ext, []).append(adapter)
    logger.debug(
        "Registered %s for extensions: %s",
        type(adapter).__name__,
        ", ".join(sorted(adapter.extensions)),
    )

Property graph

In-memory TinkerPop-compatible property graph.

Source code in src/trailhead/services/indexing/graph.py
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
class PropertyGraph:
    """In-memory TinkerPop-compatible property graph."""

    def __init__(self) -> None:
        self._vertices: dict[str, Vertex] = {}
        self._edges: list[Edge] = []

    # ── mutation ──────────────────────────────────────────────────────────────

    def add_vertex(
        self,
        label: str,
        *,
        vertex_id: str | None = None,
        **properties: Any,
    ) -> Vertex:
        v = Vertex(
            id=vertex_id or str(uuid.uuid4()),
            label=label,
            properties=dict(properties),
        )
        self._vertices[v.id] = v
        return v

    def add_edge(
        self,
        label: str,
        out_v: Vertex,
        in_v: Vertex,
        *,
        edge_id: str | None = None,
        **properties: Any,
    ) -> Edge:
        e = Edge(
            id=edge_id or str(uuid.uuid4()),
            label=label,
            out_v=out_v,
            in_v=in_v,
            properties=dict(properties),
        )
        self._edges.append(e)
        return e

    # ── read ──────────────────────────────────────────────────────────────────

    def get_vertex(self, vertex_id: str) -> Vertex | None:
        return self._vertices.get(vertex_id)

    def vertices(self, label: str | None = None) -> list[Vertex]:
        if label is None:
            return list(self._vertices.values())
        return [v for v in self._vertices.values() if v.label == label]

    def edges(self, label: str | None = None) -> list[Edge]:
        if label is None:
            return list(self._edges)
        return [e for e in self._edges if e.label == label]

    def out_edges(self, vertex: Vertex, label: str | None = None) -> list[Edge]:
        return [
            e
            for e in self._edges
            if e.out_v.id == vertex.id and (label is None or e.label == label)
        ]

    def in_edges(self, vertex: Vertex, label: str | None = None) -> list[Edge]:
        return [
            e
            for e in self._edges
            if e.in_v.id == vertex.id and (label is None or e.label == label)
        ]

A graph vertex: a label plus arbitrary key/value properties.

Source code in src/trailhead/services/indexing/graph.py
17
18
19
20
21
22
23
24
25
26
27
@dataclass
class Vertex:
    """A graph vertex: a label plus arbitrary key/value properties."""

    id: str
    label: str
    properties: dict[str, Any] = field(default_factory=dict)

    def __repr__(self) -> str:
        name = self.properties.get("name", self.id)
        return f"v[{self.label}:{name}]"

A directed, labeled edge between two vertices, with optional properties.

Source code in src/trailhead/services/indexing/graph.py
30
31
32
33
34
35
36
37
38
39
40
41
@dataclass
class Edge:
    """A directed, labeled edge between two vertices, with optional properties."""

    id: str
    label: str
    out_v: Vertex
    in_v: Vertex
    properties: dict[str, Any] = field(default_factory=dict)

    def __repr__(self) -> str:
        return f"e[{self.out_v!r}-{self.label}->{self.in_v!r}]"

Indexing

Recursively index all supported source files found under root.

If graph is provided the vertices and edges are added to it in place and the same object is returned; otherwise a fresh PropertyGraph is created.

Source code in src/trailhead/services/indexing/walker.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def index_directory(root: Path, graph: PropertyGraph | None = None) -> PropertyGraph:
    """Recursively index all supported source files found under *root*.

    If *graph* is provided the vertices and edges are added to it in place and
    the same object is returned; otherwise a fresh PropertyGraph is created.
    """
    if graph is None:
        graph = PropertyGraph()

    files = discover_source_files(root)
    logger.info("Found %d file(s) to index under %s", len(files), root)

    failed: list[Path] = []
    for path in files:
        logger.debug("Indexing %s", path)
        try:
            parse_file(path, graph)
        except Exception:
            logger.warning("Failed to parse %s", path, exc_info=True)
            failed.append(path)

    if failed:
        logger.warning(
            "%d of %d file(s) could not be parsed and were skipped: %s",
            len(failed),
            len(files),
            ", ".join(p.name for p in failed),
        )

    finalize_graph(graph)

    return graph

Querying

Execute a SQL statement against a read-only connection and return column names and rows.

The connection is opened with SQLite's mode=ro URI flag so the engine itself enforces the read-only constraint — no string-prefix heuristic is needed or used.

Source code in src/trailhead/services/indexing/query.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def execute_sql_query(db_path: Path, sql: str) -> tuple[list[str], list[dict[str, Any]]]:
    """Execute a SQL statement against a read-only connection and return column names and rows.

    The connection is opened with SQLite's ``mode=ro`` URI flag so the engine
    itself enforces the read-only constraint — no string-prefix heuristic is
    needed or used.
    """
    ro_uri = f"{db_path.resolve().as_uri()}?mode=ro"
    with sqlite3.connect(ro_uri, uri=True) as conn:
        conn.row_factory = sqlite3.Row
        cursor = conn.execute(sql)
        columns = [description[0] for description in (cursor.description or [])]
        rows = [dict(row) for row in cursor.fetchall()]
    return columns, rows

Return the nearest stored vertices to query_text.

By default external import vertices are excluded from results since they carry no source location and are rarely useful in search output. Pass exclude_external=False to include them.

If vector is supplied it is used directly and the local embedding model is not loaded. This allows callers to delegate embedding to a running trailhead serve instance and avoid the cold-load penalty.

Source code in src/trailhead/services/indexing/query.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def find_similar_vertices(
    db_path: Path,
    query_text: str,
    *,
    model_name: str,
    cache_folder: str | None = None,
    k: int = 10,
    label: str | None = None,
    exclude_external: bool = True,
    vector: list[float] | None = None,
) -> list[dict[str, Any]]:
    """Return the nearest stored vertices to *query_text*.

    By default external import vertices are excluded from results since they
    carry no source location and are rarely useful in search output.  Pass
    ``exclude_external=False`` to include them.

    If *vector* is supplied it is used directly and the local embedding model
    is not loaded.  This allows callers to delegate embedding to a running
    ``trailhead serve`` instance and avoid the cold-load penalty.
    """
    if k < 1:
        raise ValueError("k must be at least 1")

    with sqlite3.connect(db_path) as conn:
        conn.row_factory = sqlite3.Row
        if not _load_sqlite_vector_extension(conn):
            raise RuntimeError("Failed to load the sqlite-vector extension.")

        dimension = _get_embedding_dimension(conn)
        if dimension is None:
            raise ValueError("No stored vertex embeddings found in the SQLite database.")

        _prepare_vector_search(conn, dimension)

        if vector is None:
            vector = generate_embedding(
                query_text,
                model_name=model_name,
                cache_folder=cache_folder,
            )
        query_blob = vector_to_blob(vector)

        clauses: list[str] = []
        params: list[Any] = [query_blob]
        if label:
            clauses.append("v.label = ?")
            params.append(label)
        if exclude_external:
            clauses.append("v.label != 'external'")
        where_clause = ("WHERE " + " AND ".join(clauses)) if clauses else ""

        # Filter while scanning, then keep the k nearest.  Scanning with
        # vector_full_scan(..., k) and filtering afterwards (the old way)
        # returned fewer than k rows whenever some of the k nearest were
        # filtered out, e.g. by --label or because they were externals.
        columns = """
          v.id AS vertex_id,
          v.label,
          json_extract(v.properties_json, '$.name') AS name,
          json_extract(v.properties_json, '$.path') AS path,
          json_extract(v.properties_json, '$.line') AS line,
          json_extract(v.properties_json, '$.docstring') AS docstring,
          json_extract(v.properties_json, '$.source') AS source,
          ve.model_name,
          nn.distance
        """
        sql = f"""
        SELECT {columns}
        FROM vector_full_scan_stream('vertex_embeddings', 'embedding', ?) AS nn
        JOIN vertex_embeddings ve ON ve.rowid = nn.rowid
        JOIN vertices v ON v.id = ve.vertex_id
        {where_clause}
        ORDER BY nn.distance
        LIMIT ?
        """
        try:
            cursor = conn.execute(sql, (*params, k))
        except sqlite3.OperationalError as exc:
            if "vector_full_scan_stream" not in str(exc):
                raise
            # An older sqlite-vector without the streaming scan: rank every
            # row, so filtering can't leave fewer than k.
            total = conn.execute("SELECT COUNT(*) FROM vertex_embeddings").fetchone()[0]
            cursor = conn.execute(
                sql.replace(
                    "vector_full_scan_stream('vertex_embeddings', 'embedding', ?)",
                    "vector_full_scan('vertex_embeddings', 'embedding', ?, ?)",
                ),
                (params[0], max(int(total), 1), *params[1:], k),
            )
        return [dict(row) for row in cursor.fetchall()]

Coverage

Replace the stored coverage with the contents of report.

root is the directory the coverage run used for relative paths; it defaults to the directory that holds the report.

Source code in src/trailhead/services/indexing/coverage.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def import_coverage(db_path: Path, report: Path, *, root: Path | None = None) -> CoverageImport:
    """Replace the stored coverage with the contents of *report*.

    *root* is the directory the coverage run used for relative paths; it
    defaults to the directory that holds the report.
    """
    report = report.resolve()
    root = (root or report.parent).resolve()
    fmt, per_file = parse_report(report.read_text(encoding="utf-8"), root)

    db_path.parent.mkdir(parents=True, exist_ok=True)
    with sqlite3.connect(db_path) as conn:
        conn.executescript(SCHEMA_SQL)
        _run_migrations(conn)
        indexed = {row[0] for row in conn.execute(
            "SELECT DISTINCT path FROM vertices WHERE label = 'module'")}
        unmatched = sorted(p for p in per_file if p not in indexed)
        if per_file and len(unmatched) == len(per_file):
            # Almost always a wrong root: keep the coverage already stored.
            raise CoverageMismatch(
                f"none of the {len(per_file)} files in the report are in the index "
                f"(first one: {unmatched[0]}); pass the directory the tests ran in "
                "as the root for relative paths",
                unmatched,
            )
        conn.execute("DELETE FROM line_coverage")
        conn.execute("DELETE FROM coverage_files")
        conn.executemany("INSERT INTO coverage_files(path) VALUES (?)",
                         [(path,) for path in per_file])
        conn.executemany(
            "INSERT INTO line_coverage(path, line, hits) VALUES (?, ?, ?)",
            [(path, number, hits)
             for path, entries in per_file.items()
             for number, hits in entries.items()],
        )
        now = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
        conn.executemany(
            "INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)",
            [(META_REPORT, str(report)), (META_FORMAT, fmt), (META_IMPORTED_AT, now)],
        )

    return CoverageImport(
        format=fmt,
        files_in_report=len(per_file),
        lines=sum(len(v) for v in per_file.values()),
        matched_files=len(per_file) - len(unmatched),
        unmatched_files=unmatched,
    )

Return (format, {absolute path: {line: hits}}) for a coverage report.

Relative paths in the report are resolved against root (for Cobertura, against each <source> first).

Source code in src/trailhead/services/indexing/coverage.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def parse_report(text: str, root: Path) -> tuple[str, dict[str, dict[int, int]]]:
    """Return ``(format, {absolute path: {line: hits}})`` for a coverage report.

    Relative paths in the report are resolved against *root* (for Cobertura,
    against each ``<source>`` first).
    """
    fmt = detect_format(text)
    lines: dict[str, dict[int, int]] = {}

    if fmt == "coverage.py-json":
        data = json.loads(text)
        files = data.get("files")
        if not isinstance(files, dict):
            raise ValueError("coverage.py JSON report has no 'files' object")
        for name, info in files.items():
            per_line = lines.setdefault(_resolve(name, [root]), {})
            for n in info.get("missing_lines", []):
                per_line.setdefault(int(n), 0)
            for n in info.get("executed_lines", []):
                per_line[int(n)] = 1

    elif fmt == "lcov":
        current: dict[int, int] | None = None
        for raw in text.splitlines():
            line = raw.strip()
            if line.startswith("SF:"):
                current = lines.setdefault(_resolve(line[3:], [root]), {})
            elif line.startswith("DA:") and current is not None:
                parts = line[3:].split(",")
                if len(parts) >= 2:
                    number, hits = int(parts[0]), int(float(parts[1]))
                    current[number] = current.get(number, 0) + hits
            elif line == "end_of_record":
                current = None

    else:
        tree = ET.fromstring(text)
        bases = [Path(s.text.strip()) for s in tree.iter("source") if s.text and s.text.strip()]
        bases = [b if b.is_absolute() else root / b for b in bases] + [root]
        for cls in tree.iter("class"):
            filename = cls.get("filename")
            if not filename:
                continue
            per_line = lines.setdefault(_resolve(filename, bases), {})
            for entry in cls.iter("line"):
                number, hits = entry.get("number"), entry.get("hits")
                if number is None or hits is None:
                    continue
                per_line[int(number)] = per_line.get(int(number), 0) + int(float(hits))

    return fmt, lines

Embeddings

Source code in src/trailhead/services/embeddings/generator.py
19
20
21
22
23
24
def generate_embedding(
    text: str, model_name: str, cache_folder: str | None = None
) -> list[float]:
    model = get_embedding_model(model_name, cache_folder=cache_folder)
    embedding = model.encode(text)
    return _normalize_embedding(embedding)

Generate embeddings for multiple texts with a single model load.

Source code in src/trailhead/services/embeddings/generator.py
27
28
29
30
31
32
33
34
35
36
def generate_embeddings(
    texts: Sequence[str],
    model_name: str,
    cache_folder: str | None = None,
) -> list[list[float]]:
    """Generate embeddings for multiple texts with a single model load."""
    model = get_embedding_model(model_name, cache_folder=cache_folder)
    embeddings = model.encode(list(texts))

    return [_normalize_embedding(embedding) for embedding in embeddings]