HomeDocumentation

Documentation

Compress combines LLM and CI optimization. Reduce context overhead, route models within your policy, and track inference spend. Use Bazel with a private Compress cache to reuse compatible build and test results across developers, agents, and CI.

Overview

Start with the inference API for LLM optimization, or use Compress Actions for CI. You can use either independently. For repositories configured with Bazel, follow the setup below to share compatible verification results.

1

Intelligent Routing

Automatically routes requests to the cheapest model that meets your quality threshold, using HLE (Humanity's Last Exam) scores as the benchmark.

2

Prompt Compression

Reduce repeated context when useful, and keep requests unchanged when compression would not help. Inspect measured token use and savings in the run record.

3

Cost Attribution

Tag requests by team, feature, environment, or integration. Get deterministic receipts and forecasts with zero guesswork.

4

Context Management

When conversations get too large for a model’s context window, LightReach externalizes oversized tool/file outputs intoartifacts (lossless) and can compact history (lossy) to keep the request within budget.

Compress CI

Work → Actions is the control plane for supported GitHub Actions workflows: discover repositories, inspect compatibility, enable checks, follow queued and running jobs, read retained logs and artifacts, and approve releases. Importing a workflow does not automatically enable it.

  • Prepared workers, dependency/build caches and CPU/RAM-aware placement reduce setup and capacity waste.
  • Concurrency policies supersede obsolete checks. Verification evidence is reusable only when Compress accepts its exact source, workflow and admitted runtime.
  • Successful trusted checks can trigger declared downstream workflows. Exact-source validation, required checks and environment approvals stay in force.

Inspect existing runs first. CI verifies published source, so uncommitted edits still need local checks. A green result for an older SHA does not verify a new candidate. Coding tools use the same workspace permissions and release approvals as their caller. Find repository-specific instructions under Actions settings → repository → Agent access.

Speed up CI with Bazel and Compress

Bazel tracks declared build and test inputs. Compress provides authorized access to a private remote cache for enrolled repositories. When the inputs, tools, configuration, and platform match, developers, agents, and CI can reuse cached action results. A cache miss runs the action normally.

  1. Use the repository's Bazel configuration. Start with checked-in build/test targets and a pinned .bazelversion. For local execution, install Bazelisk to download the pinned Bazel version. Installing Bazel alone does not convert an existing test suite; jobs without Bazel targets keep their current checks.
  2. Enable private cache access. Ask your workspace administrator to confirm repository enrollment and the supported runtime. For an enrolled repository, opt the relevant workflow or job into the cache using the setting below. This setting alone does not enroll a repository. Local runs need an existing authenticated workspace session and a cache-scoped Bazel credential helper; keep tokens outside test actions and command-line flags.
  3. Give developers and agents the same commands. Use the checked-in Bazel entry point and explicit targets. Add the guidance below to AGENTS.md or your agent's project instructions. In Actions settings, open the repository's Agent access tab for workspace-specific instructions.
  4. Check actual reuse. Keep Bazel's Build Event Protocol (BEP) and test XML receipts, and distinguish cached targets from fresh executions. Trusted cache writers can publish passing actions; a read-only session can consume them. A macOS result does not automatically replace a Linux CI action. If the matching runtime or local cache session is unavailable, use the repository's admitted Linux Bazel workflow through Compress Actions.
For an enrolled workflow or jobyaml
env:
  COMPRESS_CI_BAZEL_CACHE: private-v1

Copy into your agent's project instructions

AGENTS.md — Bazel guidancetext
For jobs already configured with Bazel, use the repository's pinned Bazel
entry point and explicit build/test targets. Use Bazelisk to obtain the pinned
version for local execution when needed.

Use plan_current_pr to find the exact candidate's normal reference, then obtain
its source-owned required jobs with plan_agent_tests. Open each returned
environment_groups entry separately with open_agent_test_environment and run
the original commands through execute_agent_test in that qualified warm Linux
environment. Preserve the named Bazel targets in the actual execution plan.
Close the environment and verify whole cleanup before judge_agent_tests checks
the trusted evidence without rerunning satisfied tests. Local and unqualified
cache results remain diagnostic.
Keep credentials outside test actions, source, logs, and command-line arguments.

Preserve Bazel BEP and test XML. Report cached versus executed targets; cached
case records do not mean those tests executed again. Do not run a second test
selector, recorder, or duplicate pytest command around Bazel targets.

If qualified agent execution is unavailable, report the missing qualification.
Do not fall back to central run_ci_targets, run_ci_tests or ensure_ci_jobs while
automatic suites are paused. Preserve the owner's pause and release safeguards.
For jobs without Bazel targets, retain the existing checks; installing Bazel
alone does not migrate a test suite.

Bazel caching changes verification work, not your production deployment architecture. Your required checks and release approvals still apply. Cache setup does not require another production server.

Quick Start

Installation

No SDK required. LightReach uses standard HTTP with your existing tools.

1. Create an account

Sign up at compress.lightreach.io/signup to get started with the Free tier.

2. Generate an API key

Navigate to Dashboard → API Keys and create a new key. Your key will look like:

lr_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

3. Connect your provider

Add your LLM provider key in Dashboard → Settings → LLM provider keys. Your provider bills model usage directly; the Compress subscription covers optimization, analytics, and your plan features. Choose an enabled model in Overview → Exact model for your first request.

First Request

Make a request to the /api/v2/complete endpoint using your connected provider. Set OPENAI_MODEL to an enabled model ID from your provider. Explicit model selection works without HLE benchmark data; automatic quality-based routing needs qualifying benchmark evidence.

example.pypython
import os
import requests

response = requests.post(
    "https://api.compress.lightreach.io/api/v2/complete",
    headers={
        "Authorization": "Bearer lr_your_api_key_here",
        "Content-Type": "application/json"
    },
    json={
        "messages": [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "Explain quantum computing briefly."}
        ],
        "llm_provider": "openai",
        "model": os.environ["OPENAI_MODEL"],
        "honor_requested_model": True,  # Start with an explicit enabled model
        "compress": True,   # Enable prompt compression
        "tags": {"team": "engineering", "environment": "production", "project": "onboarding"}
    }
)

data = response.json()
print("Response:", data["choices"][0]["message"]["content"])
print("Model used:", data.get("model_used"))
print("Provider used:", data.get("provider_used"))
print("Estimated cost: 
quot; + str(round(float(data.get("cost_estimate") or 0.0), 6)))

Cursor

What this is

A drop-in OpenAI base URL

Cursor speaks OpenAI. LightReach exposes a strict OpenAI-compatible API (including streaming SSE), so you can connect Cursor by setting a Base URL + API key - no extension, no SDK, no workflow changes.

Important
Cursor’s “OpenAI API key” should be a LightReach key (lr_…) - not an OpenAI/Anthropic/Google provider key.
Cursor Base URL
https://api.compress.lightreach.io/v1/cursor
Cursor will call GET /models and POST /chat/completions under that base.
What you get
Automatic attribution
Cursor traffic is tagged as integration=cursor, so spend splits cleanly between Cursor and API/SDK.
Admin-controlled quality
Cursor doesn’t pick quality. Admins set a fixed HLE ceiling for Cursor traffic in Dashboard → Settings → Tags → System tags → click the Cursor card. That integration ceiling takes precedence over your workspace global HLE ceiling for Cursor requests.
Tool calling pass-through
Cursor can use OpenAI-style tool calling. LightReach forwards tool schemas and returns tool_calls in OpenAI shape. Cursor executes tools locally in the IDE - we do not run Cursor tools server-side.
Workspace inference routing
Cursor sends model requests through Compress. Its files and tools run in the IDE. Customer provider keys stay in the dashboard and are never exposed to Cursor.
Compatibility-first routing
The Cursor base URL supports long agentic sessions by enabling input compression and applying your workspace’s compaction defaults when needed. For compatibility, message externalization into artifacts is not used on this surface (so Cursor won’t see internal tools like fetch_artifact).

Connect Cursor

LightReach exposes a strict OpenAI-compatible API so Cursor can use it as a drop-in base URL. Cursor traffic is automatically attributed as integration=cursor.

1. Generate a LightReach API key

In the dashboard, create an API key. You’ll paste it into Cursor as your “OpenAI API key”.

2. Set Cursor base URL

In Cursor settings (Models → OpenAI-compatible), set the Base URL to:

https://api.compress.lightreach.io/v1/cursor

3. Choose the model

Cursor will discover available models via GET /models. Use model id:

lightreach

If you see “model not found”, re-check this exact id and ensure your Base URL ends with /v1/cursor.

4. Verify it’s working

Open a new chat in Cursor and ask a simple question. In the LightReach dashboard, you should see the request attributed with integration=cursor within a few seconds.

Connect your provider key in Settings before sending model requests. Your provider bills usage directly. Choose an enabled exact model in Overview, or use automatic routing when qualifying benchmark evidence is available.

Quality policy

Cursor does not pick quality. Admins set a fixed HLE ceiling for Cursor traffic in Dashboard → Settings → Tags → System tags → click the Cursor card. This configures the integration=cursor policy and lets you control cost without asking developers to tune per-user model settings.

How routing works for Cursor
Cursor requests go through the OpenAI-compatible surface and don’t send desired_hle. LightReach applies your workspace's integration policy for Cursor and routes to the best available connected model that satisfies it.

Troubleshooting

401 Authentication error
Make sure Cursor’s API key is a LightReach key (lr_…) and not a provider key.
No requests showing in dashboard
Verify the Base URL ends with /v1/cursor. Requests should appear within ~10 seconds.
404 or “model not found”
Ensure the Base URL is exactly https://api.compress.lightreach.io/v1/cursor (or your self-hosted origin) and the model id is lightreach.
Streaming appears “stuck”
Cursor expects OpenAI-style SSE. If you’re self-hosting behind a proxy/CDN, make sure it doesn’t buffer SSE responses. For self-hosters only, you can also try enabling buffered Cursor streaming via OPENAI_COMPAT_CURSOR_BUFFERED_STREAM=1.

Claude Code

What this is

An Anthropic-compatible endpoint

Claude Code speaks the Anthropic Messages API. LightReach exposes a fully compatible endpoint (including streaming SSE and tool calling), so you can route Claude Code through LightReach with two environment variables - no wrapper, no proxy, no workflow changes.

Important
ANTHROPIC_AUTH_TOKEN should be a LightReach key (lr_…) - not an Anthropic API key.
Environment variables
export ANTHROPIC_BASE_URL=https://api.compress.lightreach.io/v1/claude
export ANTHROPIC_AUTH_TOKEN=lr_your_key_here
Claude Code will call GET /v1/models and POST /v1/messages under that base.
What you get
Automatic attribution
Claude Code traffic is tagged as integration=claude, so spend splits cleanly between Claude Code, Cursor, and API/SDK.
Full tool loop support
Claude Code runs multi-step tool loops - file reads, edits, shell commands. LightReach translates every turn between Anthropic and your upstream provider. Nothing breaks.
Workspace inference routing
Claude Code sends model requests through Compress. Its files and shell tools run on your machine. Customer provider keys stay in the dashboard and are never exposed to Claude Code.
Any model, one interface
Claude Code thinks it is talking to Claude. Requests can route to approved models from your connected providers based on your quality and cost settings.

Connect Claude Code

LightReach exposes an Anthropic-compatible Messages API so Claude Code can use it as a drop-in base URL. Claude Code traffic is automatically attributed as integration=claude.

1. Generate a LightReach API key

In the dashboard, create an API key. You'll use it as your ANTHROPIC_AUTH_TOKEN.

2. Set environment variables

Before running claude, export these in your terminal:

export ANTHROPIC_BASE_URL=https://api.compress.lightreach.io/v1/claude
export ANTHROPIC_AUTH_TOKEN=lr_your_key_here

You can add these to your shell profile (~/.zshrc or ~/.bashrc) to make them permanent.

3. Launch Claude Code

Run claude as usual. When prompted to select a model, choose lightreach - or use:

claude --model lightreach

4. Verify it's working

Ask Claude Code a simple question. In the LightReach dashboard, you should see the request attributed with integration=claude within a few seconds.

Connect your provider key in Settings before sending model requests. Your provider bills usage directly. Choose an enabled exact model in Overview, or use automatic routing when qualifying benchmark evidence is available.

Quality policy

Claude Code does not pick quality. Admins set a fixed HLE ceiling for Claude Code traffic in Dashboard → Settings → Tags → System tags → click the Claude Code card. This configures the integration=claude policy and lets you control cost without asking developers to change their workflow.

How routing works for Claude Code
Claude Code requests go through the Anthropic-compatible surface and don't send desired_hle. LightReach applies your workspace's integration policy for Claude Code and routes to the best available connected model that satisfies it.

Troubleshooting

Authentication error
Make sure ANTHROPIC_AUTH_TOKEN is a LightReach key (lr_…) and not an Anthropic API key.
"Model not found" or model selection error
Use claude --model lightreach or select lightreach from the model picker. Ensure ANTHROPIC_BASE_URL ends with /v1/claude.
No requests showing in dashboard
Verify both environment variables are set in the same shell session where you run claude. Run echo $ANTHROPIC_BASE_URL to confirm.
Subagents using wrong model
Claude Code may use different models for subagents. To pin everything to LightReach, also set CLAUDE_CODE_SUBAGENT_MODEL=lightreach and CLAUDE_CODE_EDIT_MODEL=lightreach.

API Reference

Base URL: https://api.compress.lightreach.io/api

Authentication

Authenticate with a LightReach API key (lr_…). Most clients use an Authorization Bearer header. We also accept X-API-Key for server-to-server usage.

Authorization: Bearer lr_your_api_key_here
X-API-Key: lr_your_api_key_here

OpenAI-compatible API

Use these endpoints when you want strict OpenAI client compatibility (Cursor, OpenAI SDKs, or any tool that speaks/v1/chat/completions).

This is the right choice for IDE products (Cursor, Claude Code, Windsurf) because they generally integrate by setting an OpenAI-style Base URL and letting the IDE run tools locally on the developer machine.

Cursor (recommended)
Base URL: https://api.compress.lightreach.io/v1/cursor
Endpoints: GET /models, POST /chat/completions
Generic OpenAI clients
Base URL: https://api.compress.lightreach.io/v1 (no forced integration tag)
Endpoints: GET /models, POST /chat/completions

Example

curl -sS https://api.compress.lightreach.io/v1/cursor/chat/completions \
  -H "Authorization: Bearer lr_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "lightreach",
    "messages": [{"role":"user","content":"Write a concise commit message for a refactor."}],
    "stream": true
  }'
Compatibility note
The generic OpenAI-compatible surface (/v1) runs with prompt compression disabled and does not request compressed output. The Cursor surface (/v1/cursor) enables input compression and applies your workspace’s compaction defaults when needed (without message externalization into artifacts). If you want compression stats + token savings receipts, use POST /api/v2/complete.
POST

/v2/complete

Send a chat completion request with automatic model routing, optional compression, and full cost tracking.

Use this endpoint from your codebase (HTTP / Python / Node) when you want OpenAI-style response fields plus LightReach-native metadata (compression stats, routing transparency, and cost receipts). For IDE products like Cursor/Claude Code/Windsurf, use the OpenAI-compatible endpoints instead.

Request Body

messagesarrayrequired

Array of message objects with role ("system", "user", "assistant") and content (string).

desired_hlenumber

Desired HLE floor (0 to 100) for this request (minimum acceptable quality). Lower values allow cheaper models; higher values require more capable (and expensive) models. Workspace/tag/integration policy can clamp your requested floor down for cost control. If omitted, uses your workspace defaults.

llm_providerstring

Constrain routing to a specific provider (for example: "openai", "anthropic", "google", "xai", "fireworks", "novita", "baseten", "nebius", "deepseek", "mistral"). Omit for cross-provider optimization.

compressboolean

Enable prompt compression. Default: true

compaction_policystring

Lossy compaction preset when your request would exceed the model’s context window. Options: "off", "balanced" (default), "aggressive". Tool/file outputs may still be externalized losslessly into artifacts.

temperaturenumber

Sampling temperature (0-2). Default: provider default.

max_tokensnumber

Maximum tokens in the response.

tagsobject

Key-value pairs for cost attribution. Example: {"team": "ml", "feature": "chatbot"}

enable_toolsboolean

Opt-in tool calling. Default: false. When true, LightReach forwards yourtools / tool_choice to the upstream provider so the model can emittool_calls in the response.

toolsarray

Optional tool definitions in OpenAI function-tool schema (only used when enable_tools=true).

tool_choicestring | object

Optional tool selection policy (only used when enable_tools=true).

max_history_messagesnumber

Truncate the provided messages to at most this many messages (default: 50). Helpful when sending long histories.

Tool calling note
Compress forwards tool schemas and returns tool_calls for your application to execute. Inference requests do not execute shell commands, edit files or start a server-side agent loop.

Response

{
  "id": "chatcmpl-1741400000000",
  "object": "chat.completion",
  "created": 1741400000,
  "model": "gpt-4o-mini",
  "choices": [
    {
      "index": 0,
      "message": {"role": "assistant", "content": "Quantum computing uses quantum mechanics..."},
      "finish_reason": "stop"
    }
  ],
  "usage": {"prompt_tokens": 320, "completion_tokens": 120, "total_tokens": 440},
  "content": "Quantum computing uses quantum mechanics...",
  "compression_stats": {
    "compression_enabled": true,
    "original_tokens": 450,
    "compressed_tokens": 320,
    "token_savings": 130,
    "compression_ratio": 0.711,
    "token_accounting_note": "token_savings is input-side only (original - compressed). Output tokens are reported separately in llm_stats."
  },
  "llm_stats": {
    "provider": "openai",
    "model": "gpt-4o-mini",
    "input_tokens": 320,
    "output_tokens": 120,
    "total_tokens": 440,
    "finish_reason": "stop"
  },
  "warnings": [],
  "model_used": "gpt-4o-mini",
  "provider_used": "openai",
  "cost_estimate": 0.00042,
  "routing_info": {
    "selected_model": "gpt-4o-mini",
    "selected_provider": "openai",
    "requested_hle": 25,
    "effective_hle": 25,
    "hle_source": "request",
    "hle_clamped": false
  },
  "tool_calls": null,
  "lightreach": {
    "latency_ms": 812
  }
}

Error Handling

The API uses standard HTTP status codes. Errors return a JSON body with a detail field.

CodeMeaning
400Invalid request (missing fields, bad format)
401Invalid or missing API key
403Feature not available on your plan
429Rate limit or spend limit exceeded
502Upstream provider error

Features

Intelligent Routing

The routing system automatically selects the most cost-effective model that meets your quality requirements. It uses HLE (Humanity's Last Exam) scores as a standardized benchmark for model capability.

What is HLE?

Humanity's Last Exam is a benchmark of 2,500 expert-level questions across 100+ subjects, designed to measure frontier AI capabilities. Current state-of-the-art models score around 40%. A desired_hle of 25 is a common starting point for “capable enough” models at low cost.

Universe-constrained selection

Routes through your connected provider accounts. Your provider bills model usage directly; no model credits are included in the Compress subscription.

HLE cascading

Your requested quality floor can be clamped by workspace policy. Effective HLE is min(desired_hle, tag_ceiling, integration/global_ceiling) (when those ceilings are configured).

Provider constraint

Optionally constrain to a single provider if you need consistent behavior or have provider-specific requirements.

Prompt Compression

The greedy compression algorithm identifies and replaces repeated patterns with shorter references. Compression is lossless. The LLM receives instructions to expand the references, preserving full semantic meaning.

20-40%

Typical token reduction on verbose prompts

<50ms

Processing time for 10KB of text

Compression works best on prompts with repeated content, such as system prompts with examples, RAG contexts with similar documents, or multi-turn conversations with repeated context.

Context windows & compaction

Long-running chats and tool outputs can exceed a model’s context window. LightReach separates this into two mechanisms:

Workspace defaults live in Dashboard → Settings → Context management defaults, and requests can override per-call via compaction_policy.

Artifacts + capsules (lossless)

Oversized tool/file outputs are stored as artifacts and replaced in-context by small, deterministic capsules that include an excerpt and a handle. Models can retrieve bounded previews via fetch_artifact.

Compaction (lossy)

If the request is still over budget, LightReach can compact history by preserving system/developer prefixes, the latest user request, a pinned summary, and an explicit retrieval index of artifact handles. Policies let you trade strictness vs aggressiveness.

When should you change policy?
Use balanced unless you’re building a strict integration that must never change message structure (off), or you routinely run very long tool-heavy sessions (aggressive).

Cost Attribution

Every request is tracked with deterministic cost calculation based on real-time pricing data. Use tags to attribute costs to teams, features, environments, or integrations.

# Tag requests for attribution
response = requests.post(
    "https://api.compress.lightreach.io/api/v2/complete",
    headers={"Authorization": "Bearer " + api_key},
    json={
        "messages": [...],
        "tags": {
            "team": "ml-platform",
            "feature": "recommendations",
            "env": "production",
            "experiment": "v2-ranking"
        }
    }
)

# View costs grouped by tags in the dashboard

Plans & Limits

LLM optimization is included with no monthly platform fee: up to $1,000 in routed provider spend and 5 million tokens saved per month, with 5 invited teammates. Your provider bills model usage directly. Qualified hosted CI is $0.09 per allocated vCPU-hour ($0.003/minute at two vCPUs), metered by the second from setup through cleanup. A first eligible subscription includes a one-time $3 compute credit valid for 7 days; excess usage and usage after expiry are billed monthly. Card required. Manage billing in workspace Settings. Existing paid agreements retain their terms.

PlanPriceRouted Spend CapacityTeam Size
Included workspace$0/mo$1,000/mo routed; 5M tokens saved/mo5 invited teammates
Hosted CI$0.09 / allocated vCPU-hourPaid compute usage; no monthly minimumNo per-seat compute fee

Included LLM optimization has budgets and analytics within its allowances. Conversation retention and larger limits require a separate agreement. Workflow compatibility and resource limits apply to CI. View full plan comparison →

Security

Encryption

All traffic uses HTTPS/TLS. Customer provider API keys are encrypted at rest using Fernet (symmetric authenticated encryption) backed by API_KEY_ENCRYPTION_KEY. Passwords use bcrypt with 12 rounds.

Data retention

By default, LightReach stores request metadata and a short prompt preview for analytics. Full conversation logging is opt-in on paid plans, with configurable retention (Pro: 30 days; Scale/Enterprise: 30/60/90 days). Request-level analytics retention is tiered (Free: 14 days; paid: 365 days).

Access control

JWT-based authentication with automatic refresh. Role-based access for teams (Owner, Admin, Member, Viewer). Tag-scoped visibility for fine-grained data access.

Compliance

GDPR and CCPA compliant. Data export and full account deletion available on request.

Ready to start?

Create a free account and make your first request in minutes.