Skip to main content

trelix-langchain

LangChain retriever for trelix — semantic code search using Tree-sitter AST parsing, hybrid BM25+vector search, call-graph expansion, and streaming synthesis support.

Install

pip install trelix-langchain

Optional features live on core's extras, not the adapter's — trelix-langchain declares none of its own, so install it alongside the core extra you want.

For AWS Bedrock embeddings (Cohere or Titan):

pip install trelix-langchain "trelix[bedrock]"

For code-optimized embeddings, pick the backend you want:

pip install trelix-langchain "trelix[bge-code]"     # BGE-Code
pip install trelix-langchain "trelix[nomic-code]"   # Nomic-Code
pip install trelix-langchain "trelix[lance]"        # Lance vector backend

With knowledge graph support (NetworkX BFS retrieval leg):

pip install trelix-langchain 'trelix[knowledge-graph]'

Basic Usage

from trelix_langchain import TrelixRetriever

# First index your repo (one-time)
# trelix index /path/to/repo

retriever = TrelixRetriever(repo_path="/path/to/repo", k=10)
docs = retriever.invoke("how does authentication work?")

for doc in docs:
    print(doc.metadata["source"], doc.metadata["score"])
    print(doc.page_content[:200])

Each returned Document carries rich metadata:

Metadata key Example value
source "src/auth/middleware.py"
symbol "auth.middleware.require_login"
language "python"
kind "function"
lines "42-78"
score 0.91
retrieval_source "hybrid"

Graph-Enhanced Retrieval

Enable the knowledge graph as a 4th retrieval leg for architecture-aware queries:

from trelix_langchain import TrelixRetriever

# Standard hybrid retrieval (v2.1.0: all beast-mode flags default to false)
retriever = TrelixRetriever(repo_path="/path/to/repo", k=10)

# With graph-aware BFS (requires trelix[knowledge-graph])
retriever = TrelixRetriever(
    repo_path="/path/to/repo",
    k=10,
    graph_search_enabled=True,   # enables 4th BFS retrieval leg
    graph_search_depth=2,
)

# v2.1.0: Combine graph search with beast-mode retrieval legs
# (Enable via env vars BEFORE constructing retriever)
retriever = TrelixRetriever(
    repo_path="/path/to/repo",
    k=10,
    graph_search_enabled=True,
)

# Each Document.metadata includes graph source info
docs = retriever.invoke("how does auth relate to the data layer?")
for doc in docs:
    print(doc.metadata["retrieval_source"])  # "graph_search", "file_summary", "vector", "bm25", "pagerank"

When graph_search_enabled=True, the retriever merges results from multiple legs (v2.1.0 adds optional file-summary and PageRank):

Leg Source Typical share
vector semantic embedding similarity majority
bm25 keyword / BM25 full-text secondary
graph_expansion call-graph neighbourhood supplementary
graph_search BFS over NetworkX knowledge graph up to k//2
file_summary (v2.1.0+) index-time file summaries optional, cross-file context
pagerank (v2.1.0+) call-graph centrality boosting optional, hub-symbol promotion

Graph BFS surfaces structurally related symbols even when semantic similarity is low — useful for cross-cutting concerns like auth, logging, and rate-limiting that touch many modules.

Graph config options

Parameter Default Description
graph_search_enabled False Opt-in — zero overhead when off
graph_search_depth 2 BFS depth from seed nodes
graph_search_max_results 15 Cap on graph leg results

You can also set these via environment variables (v2.1.0+):

# Enable graph search and all v2.1.0 beast-mode legs
TRELIX_GRAPH_SEARCH_ENABLED=true \
TRELIX_RETRIEVAL_FILE_SUMMARY_LEG=true \
TRELIX_RETRIEVAL_PAGERANK_BOOST=true \
trelix index /path/to/repo

Prerequisite: build the knowledge graph before querying — trelix graph /path/to/repo. The graph is persisted in <repo>/.trelix/ and reused across retriever calls.

LangChain RAG Chain (LCEL)

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from trelix_langchain import TrelixRetriever

retriever = TrelixRetriever(repo_path="/path/to/repo", k=8)

prompt = ChatPromptTemplate.from_template(
    "Answer the question using only the code context below.\n\n"
    "Context:\n{context}\n\n"
    "Question: {question}"
)

def format_docs(docs):
    return "\n\n".join(
        f"# {d.metadata['source']} ({d.metadata['symbol']})\n{d.page_content}"
        for d in docs
    )

chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | ChatOpenAI(model="gpt-4o")
    | StrOutputParser()
)

answer = chain.invoke("How does the authentication middleware work?")
print(answer)

RetrievalQA (classic interface)

from langchain.chains import RetrievalQA
from langchain_openai import ChatOpenAI
from trelix_langchain import TrelixRetriever

retriever = TrelixRetriever(repo_path="/path/to/repo", k=10)
llm = ChatOpenAI(model="gpt-4o")

qa = RetrievalQA.from_chain_type(
    llm=llm,
    retriever=retriever,
    return_source_documents=True,
)

result = qa.invoke({"query": "Where is rate limiting applied?"})
print(result["result"])
for doc in result["source_documents"]:
    print(" -", doc.metadata["source"])

Configuration

Env var Default Description
TRELIX_EMBEDDER_PROVIDER local Embedding provider: local | local-code | bge-code | nomic-code | openai | azure | voyage | bedrock-cohere | bedrock-titan (lance is a store backend, TRELIX_STORE_BACKEND, not an embedder)
OPENAI_API_KEY — Required for openai provider
AZURE_API_KEY — Required for azure provider
AWS_ACCESS_KEY_ID — Required for Bedrock providers
AWS_SECRET_ACCESS_KEY — Required for Bedrock providers
AWS_REGION us-east-1 AWS region for Bedrock

You can also set the provider directly on the retriever instance:

retriever = TrelixRetriever(repo_path="/path/to/repo", provider="openai", k=10)

Provider Switching (v2.0.0+, updated v2.4.0)

# bge-code is EXPERIMENTAL: pooling unverified, no quality claim (see trelix docs/PROVIDERS.md)
TRELIX_EMBEDDER_PROVIDER=bge-code trelix index /path/to/repo

# Use Nomic-Code embeddings
TRELIX_EMBEDDER_PROVIDER=nomic-code trelix index /path/to/repo

# Use Bedrock Cohere embeddings (reuses AWS credentials)
TRELIX_EMBEDDER_PROVIDER=bedrock-cohere trelix index /path/to/repo

# Use Azure OpenAI embeddings
TRELIX_EMBEDDER_PROVIDER=azure trelix index /path/to/repo

# Use local sentence-transformers (no API key needed, works offline)
TRELIX_EMBEDDER_PROVIDER=local trelix index /path/to/repo

The index and the retriever must use the same provider — re-index whenever you switch.

Beast-Mode Retrieval (v2.1.0+)

trelix v2.1.0 adds five opt-in retrieval improvements — HyDE (hypothetical document expansion), FLARE (active retrieval), file-summary leg, PageRank boost, and telemetry — all activated via environment variables. No code changes needed:

from trelix_langchain import TrelixRetriever

# v2.1.0: Enable beast-mode features via env vars before constructing retriever
# Export any or all of these (all default to false):
# TRELIX_RETRIEVAL_HYDE_FALLBACK=true        # HyDE: expand queries with hypothetical docs
# TRELIX_RETRIEVAL_FILE_SUMMARY_LEG=true    # Add file-summary retrieval leg
# TRELIX_RETRIEVAL_PAGERANK_BOOST=true      # Boost symbols by PageRank centrality
# TRELIX_TELEMETRY_ENABLED=true             # Record per-query telemetry

retriever = TrelixRetriever(
    repo_path="/path/to/repo",
    provider="azure",  # or "local", "openai"
    k=10,
)
docs = retriever.invoke("how does the authentication system work?")

What's New in v2.1.0:

  • HyDE fallback: If semantic search scores are low, generate hypothetical docs and re-score
  • File-summary leg: Index-time file summaries as a 5th retrieval source (cross-file context)
  • PageRank boost: Upweight symbols in call-graph "hub" positions
  • Telemetry: Opt-in metrics on retrieval latency, source distribution, and cache hit rates
  • All features are zero-overhead when off — use env vars to opt in per deployment

Streaming Synthesis (v2.0.0+)

Streaming synthesis support for real-time code context generation:

from trelix_langchain import TrelixRetriever, StreamingSynthesizer
from langchain_openai import ChatOpenAI

retriever = TrelixRetriever(repo_path="/path/to/repo", k=8)
synthesizer = StreamingSynthesizer(
    llm=ChatOpenAI(model="gpt-4o"),
    retriever=retriever
)

# Streamed synthesis output
for chunk in synthesizer.synthesize_stream("How does the auth flow work?"):
    print(chunk, end="", flush=True)

GitHub PR Review (v2.4.0+)

Fetch a pull request diff from GitHub and run DiffReviewer directly through the retriever:

from trelix_langchain import TrelixRetriever

retriever = TrelixRetriever(repo_path="/path/to/repo", k=8)

# Retrieve context relevant to a PR diff
# Use the trelix CLI: trelix review --pr owner/repo#42
# Or post review comments: trelix review --pr owner/repo#42 --post-comments
# Requires GITHUB_TOKEN env var

Set GITHUB_TOKEN in your environment. The integration fetches all changed files in the PR, retrieves relevant code context for each diff hunk, and can optionally post a single batched review back to GitHub.

MCP Pagination (v2.4.0+)

The search_code MCP tool now returns a pagination envelope instead of a raw list. If you call trelix-mcp from LangChain tool wrappers, update your iteration:

# v2.4.0+ response shape from search_code MCP tool
response = search_code_tool.run({"query": "auth", "repo_path": "/repo"})
# response = {"results": [...], "next_cursor": 10, "total_available": 25}

for result in response["results"]:
    print(result)

# Paginate: pass next_cursor as cursor= in the next call

Multi-Query Expansion Observability (v2.4.0+)

When multi_query_enabled=True in your IndexConfig, the retriever now surfaces expansion telemetry via the ExpandResult dataclass:

from trelix_langchain import TrelixRetriever
from trelix.retrieval import MultiQueryExpander

expander = MultiQueryExpander(llm=your_llm)
expand_result = expander.expand("how does auth work?")
# expand_result.queries       — list of sub-queries generated
# expand_result.llm_used      — model name
# expand_result.elapsed_ms    — wall-clock time for expansion

Expansion metadata (expansion_used, expansion_variants, expansion_elapsed_ms) is persisted automatically to the query_telemetry table. Existing databases are upgraded automatically via an idempotent ALTER TABLE ADD COLUMN migration.

FederatedRetriever Cache (v2.4.0+)

When using FederatedRetriever across multiple repos, enable the TTL cache to avoid redundant retrievals within a debugging session:

from trelix.retrieval import FederatedRetriever

retriever = FederatedRetriever(registry=my_registry, cache_ttl=120.0)
# cache_ttl=0 disables caching
stats = retriever.cache_stats()   # {"hits": 42, "misses": 5, "size": 18}
retriever.clear_cache()           # force eviction

The cache is SHA-256-keyed, thread-safe, and scoped to the process lifetime. Expected ~90% hit rate for typical debugging-session query patterns.

Multi-Repo Watching (v2.4.0+)

Watch multiple repos simultaneously and keep their indexes live:

# CLI
trelix watch-all

# Watches all registered repos; shows per-repo stats on exit; Ctrl+C to stop
from trelix.watchers import MultiRepoWatcher

watcher = MultiRepoWatcher(repo_paths=["/repo/a", "/repo/b"])
await watcher.watch()  # uses watchfiles under the hood; hash guard prevents cascade re-index

Configuration (v2.4.0+)

In addition to the env vars above, v2.4.0 adds:

Env var Default Description
TRELIX_RETRIEVAL_FLARE_MAX_RETRIES 1 Max FLARE re-retrieval iterations, accepted range 1-3 (replaces TRELIX_RETRIEVAL_FLARE_MAX_ITER)
TRELIX_GRAPH_SEARCH_ENABLED false Enable graph BFS retrieval leg
GITHUB_TOKEN — Required for trelix review --pr GitHub integration

TRELIX_RETRIEVAL_FLARE_MAX_ITER is still accepted but emits a DeprecationWarning. It will be removed in v3.0.0.

Links

Release files for trelix-langchain 3.2.0

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

Source distribution (sdist)

Source distribution for trelix-langchain 3.2.0
File Size Uploaded
trelix_langchain-3.2.0.tar.gz 10.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for trelix-langchain 3.2.0
File Interpreter ABI Platform
trelix_langchain-3.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 18.4 kB

Release files / trelix_langchain-3.2.0.tar.gz

Download URL trelix_langchain-3.2.0.tar.gz
Size 10.0 kB
Tags Source
SHA-256 checksum
How to use checksums
2602cfe1441190e47210e4fae881d67176dda0b267a3f3ab7458072f4735727e
BLAKE2b-256 checksum
How to use checksums
c3e6ba1e6a4cd7a4eae3d1289ea729ae39c323220b659376e70c2902f4c226e0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Aug 22, 2026.

Transparency log

Release files / trelix_langchain-3.2.0-py3-none-any.whl

Download URL trelix_langchain-3.2.0-py3-none-any.whl
Size 8.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6fa7a15b0c04d13a243fff8a2f442500d235a08ee5b4c94305b6cc60f4758953
BLAKE2b-256 checksum
How to use checksums
384e842fd25dbe3dd813b1f233050b350513ea911f3c828c04b99c1fe97f4a7d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Aug 22, 2026.

Transparency log

Release history Release notifications | RSS feed

3.3.8

2 release files

3.3.7

2 release files

3.3.6

2 release files

3.3.5

2 release files

3.3.0

2 release files

3.2.5

2 release files

3.2.4

2 release files

3.2.3

2 release files

3.2.2

2 release files

3.2.1

2 release files

This release

3.2.0 This release

2 release files

3.1.7

2 release files

3.1.6

2 release files

3.1.5

2 release files

3.1.4

2 release files

3.1.3

2 release files

3.1.2

2 release files

2.4.0

2 release files

2.0.0

2 release files

1.1.0

2 release files

1.0.0

2 release files

0.7.1

2 release files

0.7.0

2 release files

0.5.0

2 release files

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