# API Key Management Source: https://opencompress.mintlify.app/api-reference/api-keys Create, list, and revoke API keys programmatically. ## Dashboard The easiest way to manage API keys is through the [dashboard](https://www.opencompress.ai/dashboard). You can create, view, and revoke keys with a single click. ## REST API API keys can also be managed via REST endpoints. These endpoints require Clerk session authentication (not API key auth). ### List keys ``` GET /api/keys ``` Returns all API keys for the authenticated user. ```json theme={null} [ { "id": "clx123...", "name": "Production", "keyPrefix": "sk-occ-dUioZ7ag", "mode": "router", "isActive": true, "lastUsedAt": "2026-02-28T10:30:00Z", "createdAt": "2026-02-27T08:00:00Z" } ] ``` ### Create key ``` POST /api/keys ``` ```json theme={null} { "name": "Production", "mode": "router" } ``` For BYOK mode: ```json theme={null} { "name": "My OpenAI Key", "mode": "byok", "upstreamBaseUrl": "https://api.openai.com/v1", "upstreamApiKey": "sk-..." } ``` **Response** includes the full key (shown only once): ```json theme={null} { "id": "clx456...", "fullKey": "sk-occ-abc123def456...", "keyPrefix": "sk-occ-abc123de" } ``` The `fullKey` is returned only in the create response. Store it immediately — you cannot retrieve it later. ### Revoke key ``` DELETE /api/keys/:id ``` Soft-deletes the key. It becomes inactive immediately and can no longer authenticate requests. # Authentication Source: https://opencompress.mintlify.app/api-reference/authentication How to authenticate with the OpenCompress API. ## API keys All API requests require authentication via a Bearer token in the `Authorization` header: ``` Authorization: Bearer sk-occ-your-key-here ``` API keys start with the prefix `sk-occ-` followed by a cryptographically random string. ## Getting a key 1. Sign in at [opencompress.ai/dashboard](https://www.opencompress.ai/dashboard) 2. Navigate to the **API Keys** section 3. Click **Create Key** 4. Choose a mode (Router or BYOK) 5. Copy the key immediately — **it's shown only once** ## Key security Your API key is shown only once when created. Store it securely. If you lose it, revoke the old key and create a new one. Best practices: * Store keys in environment variables, never in code * Use different keys for development and production * Revoke keys immediately if compromised * Each key has independent rate limits and usage tracking ## Key modes | Mode | Description | | ---------- | ------------------------------------------------------------------------------------------- | | **Router** | OpenCompress routes to the LLM via OpenRouter. You pay us for everything. | | **BYOK** | Bring your own LLM key. You pay your provider directly; we charge only the compression fee. | See [BYOK Mode](/features/byok-mode) for setup details. ## Key management * **Maximum keys:** 5 active keys per account * **Revoke:** Delete a key in the dashboard. Takes effect immediately. * **Last used:** Dashboard shows when each key was last used # Chat Completions Source: https://opencompress.mintlify.app/api-reference/chat-completions POST /v1/chat/completions — Create a compressed chat completion. ## Endpoint ``` POST https://www.opencompress.ai/api/v1/chat/completions ``` ## Headers | Header | Required | Description | | --------------- | -------- | ----------------------------- | | `Authorization` | Yes | `Bearer sk-occ-your-key-here` | | `Content-Type` | Yes | `application/json` | ## Request body Model identifier. See [Supported Models](/features/supported-models) for the full list. Examples: `gpt-4o`, `claude-sonnet-4-6`, `gemini-2.5-pro` Array of message objects. Each message has a `role` and `content`. Supported roles: `system`, `user`, `assistant` If `true`, returns a stream of server-sent events. Sampling temperature (0-2). Passed through to the model. Maximum tokens to generate. Passed through to the model. Nucleus sampling parameter. Passed through to the model. Stop sequences. Passed through to the model. All standard OpenAI parameters (`frequency_penalty`, `presence_penalty`, `logprobs`, `tools`, `tool_choice`, etc.) are passed through to the upstream model. ## Response Unique identifier for this completion. Always `"chat.completion"`. Unix timestamp of when the completion was created. The model used, matching your request. Array of completion choices. Index of this choice. The assistant's message with `role` and `content`. Why generation stopped: `"stop"`, `"length"`, `"tool_calls"`. Token usage statistics. Number of tokens in the compressed prompt. Number of tokens in the response. Total tokens (prompt + completion). ## Example ```python Python theme={null} from openai import OpenAI client = OpenAI( base_url="https://www.opencompress.ai/api/v1", api_key="sk-occ-your-key-here", ) response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "You are a concise technical writer."}, {"role": "user", "content": "Explain how JWT authentication works."}, ], temperature=0.7, max_tokens=500, ) print(response.choices[0].message.content) ``` ```bash cURL theme={null} curl https://www.opencompress.ai/api/v1/chat/completions \ -H "Authorization: Bearer sk-occ-your-key-here" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o", "messages": [ {"role": "system", "content": "You are a concise technical writer."}, {"role": "user", "content": "Explain how JWT authentication works."} ], "temperature": 0.7, "max_tokens": 500 }' ``` # Errors Source: https://opencompress.mintlify.app/api-reference/errors HTTP status codes and error response format. ## Error format All errors follow this structure: ```json theme={null} { "error": { "message": "Human-readable error description", "type": "error_type" } } ``` ## Status codes | Code | Type | Description | | ----- | ------------------ | ------------------------------ | | `401` | `auth_error` | Invalid or missing API key | | `402` | `billing_error` | Insufficient balance | | `429` | `rate_limit_error` | Too many requests | | `502` | `upstream_error` | LLM provider returned an error | | `500` | `internal_error` | Server error | ## Common errors and solutions ### 401 — Invalid API key ```json theme={null} {"error": {"message": "Invalid API key", "type": "auth_error"}} ``` **Solutions:** * Check that your key starts with `sk-occ-` * Ensure the `Authorization` header format is `Bearer sk-occ-...` * Verify the key hasn't been revoked in your dashboard ### 402 — Insufficient balance ```json theme={null} {"error": {"message": "Insufficient balance", "type": "billing_error"}} ``` **Solution:** Add funds in the [dashboard](https://www.opencompress.ai/dashboard). ### 429 — Rate limit exceeded ```json theme={null} {"error": {"message": "Rate limit exceeded", "type": "rate_limit_error"}} ``` **Solution:** Wait and retry with exponential backoff. Default limit is 60 requests/minute per key. ### 502 — Upstream error ```json theme={null} {"error": {"message": "Upstream error: ...", "type": "upstream_error"}} ``` **Solutions:** * Check if the model name is correct * The LLM provider may be experiencing downtime * For BYOK: verify your upstream API key is valid # Models Source: https://opencompress.mintlify.app/api-reference/models Model identifiers and pricing for all supported models. ## Model identifiers Use these exact strings as the `model` parameter in your API requests. ### Tier 1: Flagship | Model | Provider | Input / 1M | Output / 1M | Best for | | ------------------- | --------- | ---------- | ----------- | -------------------- | | `gpt-4o` | OpenAI | \$2.50 | \$10.00 | General purpose | | `claude-sonnet-4-6` | Anthropic | \$3.00 | \$15.00 | Coding, analysis | | `gemini-2.5-pro` | Google | \$1.25 | \$10.00 | Long context | | `gpt-4.1` | OpenAI | \$2.00 | \$8.00 | Coding, instructions | ### Tier 2: Cost-efficient | Model | Provider | Input / 1M | Output / 1M | Best for | | --------------------------- | --------- | ---------- | ----------- | ----------- | | `gpt-4o-mini` | OpenAI | \$0.15 | \$0.60 | High volume | | `gpt-4.1-mini` | OpenAI | \$0.40 | \$1.60 | Balanced | | `claude-haiku-4-5-20251001` | Anthropic | \$0.80 | \$4.00 | Fast tasks | | `gemini-2.5-flash` | Google | \$0.15 | \$0.60 | Speed | ### Tier 3: Budget | Model | Provider | Input / 1M | Output / 1M | Best for | | ----------------------------- | -------- | ---------- | ----------- | -------------- | | `gpt-4.1-nano` | OpenAI | \$0.10 | \$0.40 | Classification | | `meta-llama/llama-4-scout` | Meta | \$0.15 | \$0.40 | Open source | | `meta-llama/llama-4-maverick` | Meta | \$0.20 | \$0.60 | Open source | ### Tier 4: Reasoning | Model | Provider | Input / 1M | Output / 1M | Best for | | -------------------------------- | --------- | ---------- | ----------- | ----------------- | | `claude-opus-4-6` | Anthropic | \$15.00 | \$75.00 | Complex reasoning | | `gpt-4-turbo` | OpenAI | \$10.00 | \$30.00 | Legacy | | `deepseek/deepseek-r1` | DeepSeek | \$0.50 | \$2.00 | Chain-of-thought | | `deepseek/deepseek-chat-v3-0324` | DeepSeek | \$0.50 | \$1.50 | General | ## Unknown models If you use a model not in our pricing table, we apply a default rate of $1.00/1M input and $3.00/1M output for savings calculations. The request still works — it's routed through OpenRouter normally. # API Overview Source: https://opencompress.mintlify.app/api-reference/overview OpenAI-compatible REST API with transparent prompt compression. ## Base URL ``` https://www.opencompress.ai/api/v1 ``` ## Authentication All requests require a Bearer token: ``` Authorization: Bearer sk-occ-your-key-here ``` Get your API key from the [dashboard](https://www.opencompress.ai/dashboard). ## Compatibility The OpenCompress API is **fully compatible** with the [OpenAI Chat Completions API](https://platform.openai.com/docs/api-reference/chat). Any SDK, library, or tool that works with OpenAI will work with OpenCompress by changing the base URL. ## Available endpoints | Method | Endpoint | Description | | ------ | ---------------------- | ------------------------------------------- | | `POST` | `/v1/chat/completions` | Create a chat completion (with compression) | ## Request format ```json theme={null} { "model": "gpt-4o-mini", "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Your prompt here."} ], "stream": false } ``` ## Response format ```json theme={null} { "id": "gen-abc123", "object": "chat.completion", "created": 1772341560, "model": "gpt-4o-mini", "choices": [ { "index": 0, "finish_reason": "stop", "message": { "role": "assistant", "content": "Response content here." } } ], "usage": { "prompt_tokens": 18, "completion_tokens": 145, "total_tokens": 163 } } ``` Token counts in `usage` reflect the **compressed** token counts — what the model actually processed. This is what you're billed for. # How Billing Works Source: https://opencompress.mintlify.app/billing/how-billing-works Per-request billing with full transparency. ## Per-request billing Every API call is billed individually. After each request completes, we: 1. **Measure** the original and compressed token counts 2. **Calculate** the cost difference (savings) 3. **Charge** the actual LLM cost + 20% of savings (router mode) or just the 20% fee (BYOK) 4. **Deduct** from your prepaid balance 5. **Log** the full breakdown in your dashboard ## Billing formula ``` original_cost = original_input_tokens × input_price + estimated_original_output × output_price actual_cost = compressed_input_tokens × input_price + actual_output_tokens × output_price savings = max(0, original_cost - actual_cost) fee = savings × 0.20 # Router mode total_charged = actual_cost + fee # BYOK mode total_charged = fee ``` ## What you see in the dashboard Each request in your usage history shows: | Field | Description | | ---------------- | ---------------------------- | | Model | The model used | | Input tokens | Original → compressed | | Output tokens | Actual tokens generated | | Compression rate | % of input tokens saved | | Savings | Dollar amount saved | | Charged | Amount deducted from balance | ## Balance protection * If your balance reaches \$0, API requests return `402 Insufficient balance` * We never charge more than your available balance * No surprise charges — you control how much you deposit ## Monitoring usage Track your spending in real time: * **Dashboard:** [opencompress.ai/dashboard](https://www.opencompress.ai/dashboard) shows balance, monthly stats, and per-request logs * **API:** Usage data is included in the `usage` field of every response # Manage Balance Source: https://opencompress.mintlify.app/billing/manage-balance Add funds and monitor your account balance. ## Add funds 1. Go to [opencompress.ai/dashboard](https://www.opencompress.ai/dashboard) 2. Click **Add Funds** in the balance section 3. Choose a preset amount ($10, $50, $100, $500, \$1,000) or enter a custom amount 4. Complete payment via Stripe 5. Balance is credited immediately ## Check balance Your current balance is displayed at the top of the dashboard. It updates in real time as you make API calls. ## Low balance When your balance reaches \$0: * API requests return HTTP `402` with `"Insufficient balance"` * No data is lost — just add more funds and continue * In-flight streaming requests will complete (we don't cut off mid-stream) ## Usage history The dashboard shows your complete usage history: * Per-request breakdown (model, tokens, savings, cost) * Monthly aggregates (total calls, tokens saved, money saved) * Compression rate trends over time # Pricing Source: https://opencompress.mintlify.app/billing/pricing Pay only for what we save you. No savings, no fee. ## How pricing works OpenCompress uses a **pay-for-savings** model. We charge **20% of the money we save you**. If compression doesn't save you anything on a particular request, there's no additional fee. ``` Your cost = LLM cost (on compressed tokens) + 20% × savings ``` ## Example Say you send a 10,000-token prompt that we compress to 6,000 tokens using GPT-4o (\$2.50/1M input tokens): | | Tokens | Cost | | ---------------------- | ------------ | ------------------ | | Without OpenCompress | 10,000 input | \$0.0250 | | With OpenCompress | 6,000 input | \$0.0150 | | **Savings** | 4,000 tokens | **\$0.0100** | | OpenCompress fee (20%) | | \$0.0020 | | **Your total cost** | | **\$0.0170** | | **Net savings** | | **\$0.0080 (32%)** | You save **32%** on this call. We earn \$0.002. Everyone wins. ## Router vs BYOK pricing **You pay us:** LLM cost + 20% fee We handle the LLM provider. Simple, no setup. **You pay us:** 20% fee only You pay your LLM provider directly. We only charge the compression fee. ## Billing details * **Minimum deposit:** \$10 * **Deposit options:** $10, $50, $100, $500, \$1,000, or custom amount * **Payment:** Stripe (credit card) * **Balance:** Prepaid, deducted per request * **Refunds:** Available for unused balance ## Output savings When we compress your input, the model's output also tends to be shorter. We estimate output savings conservatively: ``` output_savings = input_compression_rate × 0.5 ``` This means a 40% input compression results in an estimated 20% shorter output. Both input and output savings are factored into your total savings calculation. # BYOK Mode Source: https://opencompress.mintlify.app/features/byok-mode Bring Your Own Key — use your existing LLM API key with OpenCompress. ## What is BYOK? **Bring Your Own Key (BYOK)** mode lets you use your existing API key from any LLM provider (OpenAI, Anthropic, etc.) while still getting OpenCompress's compression benefits. ## How it works ``` Your App → OpenCompress (compress) → Your Provider (with your key) → Response ``` In BYOK mode: 1. Your prompts are compressed by OpenCompress 2. The compressed request is forwarded to **your provider** using **your API key** 3. You pay your provider directly at their rates 4. OpenCompress charges **only 20% of the savings** as a fee ## Setup When creating an API key in the [dashboard](https://www.opencompress.ai/dashboard), select **BYOK mode** and provide: | Field | Description | Example | | ----------------- | ---------------------------- | --------------------------- | | Upstream Base URL | Your provider's API base URL | `https://api.openai.com/v1` | | Upstream API Key | Your provider's API key | `sk-...` | ## Pricing comparison | | Router Mode | BYOK Mode | | ----------------- | ----------------------------- | ------------------- | | Who pays the LLM? | OpenCompress (via OpenRouter) | You (your provider) | | LLM cost | Included in your charge | You pay directly | | Compression fee | 20% of savings | 20% of savings | | Total you pay us | LLM cost + fee | Fee only | BYOK is ideal if you already have negotiated rates, enterprise agreements, or credits with an LLM provider. You get compression savings on top of your existing deal. ## Supported providers Any OpenAI-compatible API endpoint works with BYOK: | Provider | Base URL | | --------------------- | ------------------------------------------------------------------------- | | OpenAI | `https://api.openai.com/v1` | | Anthropic (via proxy) | Anthropic's OpenAI-compatible endpoint | | Azure OpenAI | `https://your-resource.openai.azure.com/openai/deployments/your-model/v1` | | Together AI | `https://api.together.xyz/v1` | | Groq | `https://api.groq.com/openai/v1` | | Any OpenAI-compatible | Your custom base URL | ## Security * Your upstream API key is stored encrypted and only used for forwarding requests * OpenCompress never logs your upstream key in plaintext * You can revoke your OpenCompress key at any time to stop forwarding # Compression Engine Source: https://opencompress.mintlify.app/features/compression-engine Technical deep-dive into the OpenCompress compression pipeline. ## Architecture The compression engine runs a two-stage pipeline on every user message in your request: ``` User Message → Stage 1: Dictionary Aliasing → Stage 2: Semantic Pruning → Compressed Message ``` System messages and assistant messages are passed through unmodified. ## Stage 1: Dictionary Aliasing Repeated multi-token phrases are identified and replaced with compact aliases: ``` Before: "The retrieval-augmented generation system uses retrieval-augmented generation to..." After: "§A=retrieval-augmented generation. The §A system uses §A to..." ``` **When it helps most:** * System prompts with repeated terminology * RAG contexts with recurring entity names * Tool schemas with verbose type annotations * Multi-turn conversations with repeated context ## Stage 2: Semantic Pruning A distilled classifier (trained on 105K+ real agent conversations) scores each token by semantic importance. Tokens below the threshold are removed: ``` Before: "Could you please provide me with a detailed and comprehensive explanation of..." After: "Explain..." ``` The classifier preserves: * Named entities and technical terms * Logical connectors that affect meaning * Numerical values and specific references * Code and structured data **Training data:** 105K agent conversations across coding, analysis, writing, and tool-use domains. Quality is validated by cosine similarity between original and compressed embeddings. ## Compression rates by content type | Content Type | Typical Compression | Notes | | ----------------------------- | ------------------- | ----------------------------------- | | Natural language instructions | 40-55% | Highest savings | | RAG / retrieved documents | 35-50% | Good savings, preserves facts | | Conversation history | 30-45% | Repeated patterns compress well | | Code blocks | 10-20% | Minimal compression (already dense) | | JSON / structured data | 15-25% | Some key name shortening | ## Quality validation Every compression is scored: * **Cosine similarity** between original and compressed embeddings * If similarity drops below 0.85, the original is sent unmodified * Quality scores are logged and visible in your dashboard Compression never modifies the model's response. We only compress your input — the model generates its response normally from the compressed prompt. # Rate Limits Source: https://opencompress.mintlify.app/features/rate-limits API rate limits and how to handle them. ## Default limits | Plan | Requests per minute | Concurrent requests | | --------- | ------------------- | ------------------- | | Free tier | 60 | 10 | Rate limits are applied per API key. If you need higher limits, contact us. ## Rate limit headers When you approach or exceed limits, responses include: | Header | Description | | ----------------------- | ------------------------------------- | | `X-RateLimit-Limit` | Maximum requests per minute | | `X-RateLimit-Remaining` | Remaining requests in current window | | `X-RateLimit-Reset` | Unix timestamp when the window resets | ## Handling rate limits When rate limited, you'll receive a `429` status code: ```json theme={null} { "error": { "message": "Rate limit exceeded", "type": "rate_limit_error" } } ``` ### Recommended retry strategy ```python theme={null} import time from openai import OpenAI, RateLimitError client = OpenAI( base_url="https://www.opencompress.ai/api/v1", api_key="sk-occ-your-key-here", ) def call_with_retry(messages, max_retries=3): for attempt in range(max_retries): try: return client.chat.completions.create( model="gpt-4o-mini", messages=messages, ) except RateLimitError: wait = 2 ** attempt # exponential backoff time.sleep(wait) raise Exception("Max retries exceeded") ``` The OpenAI SDK has built-in retry logic. By default, it retries rate-limited requests with exponential backoff. # Supported Models Source: https://opencompress.mintlify.app/features/supported-models All LLM models available through OpenCompress. ## Router mode In router mode, OpenCompress routes your request through OpenRouter, giving you access to hundreds of models. Here are the most popular: ### OpenAI | Model | Input (per 1M tokens) | Output (per 1M tokens) | | -------------- | --------------------- | ---------------------- | | `gpt-4o` | \$2.50 | \$10.00 | | `gpt-4o-mini` | \$0.15 | \$0.60 | | `gpt-4-turbo` | \$10.00 | \$30.00 | | `gpt-4.1` | \$2.00 | \$8.00 | | `gpt-4.1-mini` | \$0.40 | \$1.60 | | `gpt-4.1-nano` | \$0.10 | \$0.40 | ### Anthropic | Model | Input (per 1M tokens) | Output (per 1M tokens) | | --------------------------- | --------------------- | ---------------------- | | `claude-opus-4-6` | \$15.00 | \$75.00 | | `claude-sonnet-4-6` | \$3.00 | \$15.00 | | `claude-haiku-4-5-20251001` | \$0.80 | \$4.00 | ### Google | Model | Input (per 1M tokens) | Output (per 1M tokens) | | ------------------ | --------------------- | ---------------------- | | `gemini-2.5-pro` | \$1.25 | \$10.00 | | `gemini-2.5-flash` | \$0.15 | \$0.60 | ### Meta | Model | Input (per 1M tokens) | Output (per 1M tokens) | | ----------------------------- | --------------------- | ---------------------- | | `meta-llama/llama-4-maverick` | \$0.20 | \$0.60 | | `meta-llama/llama-4-scout` | \$0.15 | \$0.40 | ### DeepSeek | Model | Input (per 1M tokens) | Output (per 1M tokens) | | -------------------------------- | --------------------- | ---------------------- | | `deepseek/deepseek-chat-v3-0324` | \$0.50 | \$1.50 | | `deepseek/deepseek-r1` | \$0.50 | \$2.00 | Prices shown are the base LLM cost before compression savings. With OpenCompress, your effective cost is lower because fewer tokens are sent. ## BYOK mode In BYOK mode, you can use **any model from any provider**. Just provide your own API key and base URL. See [BYOK Mode](/features/byok-mode) for details. ## Model not listed? If a model is available on OpenRouter, it works with OpenCompress. Use the exact model identifier from OpenRouter's model list. # How It Works Source: https://opencompress.mintlify.app/how-it-works Five compression layers that compound to reduce token usage by 30-40%. ## The compression pipeline OpenCompress applies a multi-layer compression pipeline to your input prompts. Each layer targets a different source of token waste, and they compound — the output of one feeds into the next. ``` Raw Prompt → Input Pruning → Dictionary Aliasing → Compressed Prompt → LLM ``` ## Layer 1: Input Pruning **What it does:** Removes tokens the model doesn't need to read. A distilled classifier trained on 105K+ agent conversation samples scores each token by semantic importance. Low-importance tokens — filler words, redundant connectors, verbose formatting — are removed while preserving meaning. | Metric | Value | | ----------------- | ----------------------------- | | Token reduction | 40-60% | | Quality retention | 95%+ cosine similarity | | Speed | 4-12x faster than LLMLingua-2 | ## Layer 2: Dictionary Aliasing **What it does:** Replaces repeated phrases with compact aliases. Common multi-token phrases are mapped to short aliases (e.g., `§A1`). A dictionary header is prepended to the prompt so the model can decode them. This is especially effective for: * System prompts with repeated instructions * RAG contexts with recurring entity names * Tool call schemas with verbose type definitions ## Layer 3: Output Estimation **What it does:** Estimates output savings from compressed input. When input is compressed, the model's output also tends to be shorter — it mirrors the density of the input. We estimate output savings proportional to input compression: ``` output_savings_rate = input_compression_rate × 0.5 ``` This means if we compress your input by 40%, we estimate your output is \~20% shorter than it would have been. ## Quality guarantee Every compression is validated by cosine similarity between the original and compressed prompts. If compression would degrade quality below threshold, the original prompt is sent unmodified and you pay standard rates with no fee. Try the [Playground](https://www.opencompress.ai/playground) to see compression applied to your actual prompts in real time, with side-by-side quality comparison. # cURL Source: https://opencompress.mintlify.app/integration/curl Test the OpenCompress API from your terminal. ## Basic request ```bash theme={null} curl https://www.opencompress.ai/api/v1/chat/completions \ -H "Authorization: Bearer sk-occ-your-key-here" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o-mini", "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is prompt compression and why does it matter?"} ] }' ``` ## Streaming ```bash theme={null} curl https://www.opencompress.ai/api/v1/chat/completions \ -H "Authorization: Bearer sk-occ-your-key-here" \ -H "Content-Type: application/json" \ -N \ -d '{ "model": "gpt-4o", "messages": [ {"role": "user", "content": "Write a short story about AI."} ], "stream": true }' ``` ## Specify a different model ```bash theme={null} curl https://www.opencompress.ai/api/v1/chat/completions \ -H "Authorization: Bearer sk-occ-your-key-here" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-sonnet-4-6", "messages": [ {"role": "user", "content": "Compare REST and GraphQL."} ] }' ``` ## Response format ```json theme={null} { "id": "gen-abc123", "object": "chat.completion", "created": 1772341560, "model": "gpt-4o-mini", "choices": [ { "index": 0, "finish_reason": "stop", "message": { "role": "assistant", "content": "Prompt compression is..." } } ], "usage": { "prompt_tokens": 18, "completion_tokens": 145, "total_tokens": 163 } } ``` The response format is identical to the OpenAI Chat Completions API. Any tool that parses OpenAI responses will work unchanged. # LangChain Source: https://opencompress.mintlify.app/integration/langchain Use OpenCompress with LangChain for compressed agent and chain workflows. ## Python LangChain's `ChatOpenAI` class accepts a custom `base_url`, making integration seamless. ```bash theme={null} pip install langchain-openai ``` ```python theme={null} from langchain_openai import ChatOpenAI llm = ChatOpenAI( base_url="https://www.opencompress.ai/api/v1", api_key="sk-occ-your-key-here", model="gpt-4o", ) response = llm.invoke("Explain the benefits of prompt compression.") print(response.content) ``` ## With chains ```python theme={null} from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI llm = ChatOpenAI( base_url="https://www.opencompress.ai/api/v1", api_key="sk-occ-your-key-here", model="gpt-4o", ) prompt = ChatPromptTemplate.from_messages([ ("system", "You are a technical writer. Be concise and clear."), ("user", "Write documentation for: {topic}"), ]) chain = prompt | llm response = chain.invoke({"topic": "REST API authentication"}) print(response.content) ``` ## With agents ```python theme={null} from langchain_openai import ChatOpenAI from langchain.agents import create_tool_calling_agent, AgentExecutor from langchain_core.prompts import ChatPromptTemplate llm = ChatOpenAI( base_url="https://www.opencompress.ai/api/v1", api_key="sk-occ-your-key-here", model="gpt-4o", ) # Your tools and agent setup work exactly the same # OpenCompress compresses the input before each LLM call ``` ## TypeScript ```typescript theme={null} import { ChatOpenAI } from "@langchain/openai"; const llm = new ChatOpenAI({ configuration: { baseURL: "https://www.opencompress.ai/api/v1", }, apiKey: "sk-occ-your-key-here", model: "gpt-4o", }); const response = await llm.invoke("Explain prompt compression."); console.log(response.content); ``` Agent workflows benefit the most from compression. System prompts, tool schemas, and conversation history all contain significant token waste that OpenCompress removes. # OpenAI SDK Source: https://opencompress.mintlify.app/integration/openai-sdk Use the official OpenAI Python or TypeScript SDK with OpenCompress. OpenCompress is fully compatible with the OpenAI SDK. Change `base_url` and `api_key` — everything else stays the same. ## Python ```bash theme={null} pip install openai ``` ```python theme={null} from openai import OpenAI client = OpenAI( base_url="https://www.opencompress.ai/api/v1", api_key="sk-occ-your-key-here", ) # Non-streaming response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "You are a senior software engineer."}, {"role": "user", "content": "Review this code and suggest improvements..."}, ], ) print(response.choices[0].message.content) print(f"Tokens used: {response.usage.total_tokens}") ``` ## TypeScript / Node.js ```bash theme={null} npm install openai ``` ```typescript theme={null} import OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://www.opencompress.ai/api/v1", apiKey: "sk-occ-your-key-here", }); const response = await client.chat.completions.create({ model: "claude-sonnet-4-6", messages: [ { role: "system", content: "You are a senior software engineer." }, { role: "user", content: "Review this code and suggest improvements..." }, ], }); console.log(response.choices[0].message.content); ``` ## Streaming ```python Python theme={null} stream = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Write a haiku about compression."}], stream=True, ) for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="") ``` ```typescript TypeScript theme={null} const stream = await client.chat.completions.create({ model: "gpt-4o", messages: [{ role: "user", content: "Write a haiku about compression." }], stream: true, }); for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content; if (content) process.stdout.write(content); } ``` Streaming works identically to the OpenAI API. Compression happens before the stream starts — there is no additional latency during token generation. ## Switching between models You can use any supported model by changing the `model` parameter. No other code changes needed. ```python theme={null} # OpenAI client.chat.completions.create(model="gpt-4o", ...) # Anthropic client.chat.completions.create(model="claude-sonnet-4-6", ...) # Google client.chat.completions.create(model="gemini-2.5-pro", ...) # Meta (via OpenRouter) client.chat.completions.create(model="meta-llama/llama-4-maverick", ...) ``` # Python (requests) Source: https://opencompress.mintlify.app/integration/python-sdk Call the OpenCompress API directly with Python requests. If you prefer not to use the OpenAI SDK, you can call the API directly. ## Basic usage ```python theme={null} import requests response = requests.post( "https://www.opencompress.ai/api/v1/chat/completions", headers={ "Authorization": "Bearer sk-occ-your-key-here", "Content-Type": "application/json", }, json={ "model": "gpt-4o-mini", "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is prompt compression?"}, ], }, ) data = response.json() print(data["choices"][0]["message"]["content"]) ``` ## Streaming with requests ```python theme={null} import requests import json response = requests.post( "https://www.opencompress.ai/api/v1/chat/completions", headers={ "Authorization": "Bearer sk-occ-your-key-here", "Content-Type": "application/json", }, json={ "model": "gpt-4o", "messages": [{"role": "user", "content": "Explain black holes."}], "stream": True, }, stream=True, ) for line in response.iter_lines(): if line: text = line.decode("utf-8") if text.startswith("data: ") and text != "data: [DONE]": chunk = json.loads(text[6:]) content = chunk["choices"][0].get("delta", {}).get("content", "") if content: print(content, end="", flush=True) ``` ## Async with httpx ```python theme={null} import httpx async def compress_and_call(): async with httpx.AsyncClient() as client: response = await client.post( "https://www.opencompress.ai/api/v1/chat/completions", headers={ "Authorization": "Bearer sk-occ-your-key-here", "Content-Type": "application/json", }, json={ "model": "gpt-4o-mini", "messages": [ {"role": "user", "content": "Summarize the latest AI news."}, ], }, ) return response.json() ``` # Streaming Source: https://opencompress.mintlify.app/integration/streaming Real-time streaming responses with server-sent events. ## How streaming works OpenCompress supports streaming via server-sent events (SSE), identical to the OpenAI API. Set `"stream": true` in your request body. **Important:** Compression happens *before* the stream starts. The compression step adds a small fixed latency (\~100-300ms), but once streaming begins, tokens arrive at the same speed as a direct API call. ``` Compression (100-300ms) → Stream starts → Tokens arrive at full speed ``` ## Request ```bash theme={null} curl https://www.opencompress.ai/api/v1/chat/completions \ -H "Authorization: Bearer sk-occ-your-key-here" \ -H "Content-Type: application/json" \ -N \ -d '{ "model": "gpt-4o", "messages": [{"role": "user", "content": "Tell me a story."}], "stream": true }' ``` ## Response format Each SSE event contains a JSON chunk: ``` data: {"id":"gen-abc","object":"chat.completion.chunk","created":1772341560,"model":"gpt-4o","choices":[{"index":0,"delta":{"content":"Once"},"finish_reason":null}]} data: {"id":"gen-abc","object":"chat.completion.chunk","created":1772341560,"model":"gpt-4o","choices":[{"index":0,"delta":{"content":" upon"},"finish_reason":null}]} data: {"id":"gen-abc","object":"chat.completion.chunk","created":1772341560,"model":"gpt-4o","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":12,"completion_tokens":85,"total_tokens":97}} data: [DONE] ``` The final chunk includes `usage` data with token counts. Billing is calculated after the stream completes. ## SDK examples ```python Python theme={null} from openai import OpenAI client = OpenAI( base_url="https://www.opencompress.ai/api/v1", api_key="sk-occ-your-key-here", ) stream = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Tell me a story."}], stream=True, ) for chunk in stream: content = chunk.choices[0].delta.content if content: print(content, end="", flush=True) ``` ```typescript TypeScript theme={null} import OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://www.opencompress.ai/api/v1", apiKey: "sk-occ-your-key-here", }); const stream = await client.chat.completions.create({ model: "gpt-4o", messages: [{ role: "user", content: "Tell me a story." }], stream: true, }); for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content; if (content) process.stdout.write(content); } ``` # Introduction Source: https://opencompress.mintlify.app/introduction The compression layer between your app and any LLM. Save 30-40% on every API call. ## What is OpenCompress? OpenCompress is a **drop-in middleware** that sits between your application and any LLM provider. It compresses your prompts before they reach the model, reducing token usage by 30-40% while preserving output quality. Get running in under 2 minutes. Change two lines of code. Understand the five-layer compression pipeline. Full OpenAI-compatible endpoint documentation. Pay-for-savings model. No savings = no charge. ## Why OpenCompress? Every LLM call you make contains **token waste** — filler words, redundant context, verbose formatting that models don't need. OpenCompress removes this waste before the request hits your provider. Fully compatible with OpenAI's Chat Completions API. Works with any SDK. GPT-4o, Claude, Gemini, Llama, DeepSeek — we compress for all of them. We charge 20% of what we save you. If we don't save you money, you pay nothing extra. Change `base_url` and `api_key`. Everything else stays the same. ## How much can you save? | Use Case | Typical Compression | Monthly Savings (at \$10K spend) | | ------------------------------------ | ---------------------- | -------------------------------- | | RAG / retrieval-augmented generation | 40-55% input reduction | $2,400 - $3,300 | | Agent tool calls | 30-45% input reduction | $1,800 - $2,700 | | Chat with long context | 35-50% input reduction | $2,100 - $3,000 | | Code generation | 25-35% input reduction | $1,500 - $2,100 | Savings vary by prompt structure. Prompts with more natural language and repeated patterns compress best. Try it in the [Playground](https://www.opencompress.ai/playground) with your actual prompts. # Quick Start Source: https://opencompress.mintlify.app/quickstart Start compressing LLM calls in under 2 minutes. Two lines of code. ## Get your API key Sign up at [opencompress.ai/dashboard](https://www.opencompress.ai/dashboard). Deposit credits via Stripe. Start with \$10 to test. Go to the API Keys section and create a new key. Copy it — it's shown only once. Your API key starts with `sk-occ-` and works like any other LLM API key. ## Integration OpenCompress is a **drop-in replacement** for any OpenAI-compatible endpoint. Change two values: | Setting | Before | After | | -------- | --------------------------- | ------------------------------------ | | Base URL | `https://api.openai.com/v1` | `https://www.opencompress.ai/api/v1` | | API Key | `sk-...` (OpenAI) | `sk-occ-...` (OpenCompress) | Everything else — model names, message format, streaming, tool calls — stays identical. *** ## Code examples ```python Python (OpenAI SDK) theme={null} from openai import OpenAI client = OpenAI( base_url="https://www.opencompress.ai/api/v1", api_key="sk-occ-your-key-here", ) response = client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Explain quantum computing in simple terms."}, ], ) print(response.choices[0].message.content) ``` ```typescript TypeScript (OpenAI SDK) theme={null} import OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://www.opencompress.ai/api/v1", apiKey: "sk-occ-your-key-here", }); const response = await client.chat.completions.create({ model: "gpt-4o-mini", messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Explain quantum computing in simple terms." }, ], }); console.log(response.choices[0].message.content); ``` ```bash cURL theme={null} curl https://www.opencompress.ai/api/v1/chat/completions \ -H "Authorization: Bearer sk-occ-your-key-here" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o-mini", "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Explain quantum computing in simple terms."} ] }' ``` Your prompts are compressed transparently before reaching the model. The response you receive is identical in format to a direct OpenAI API call. ## What happens behind the scenes ``` Your App OpenCompress LLM Provider │ │ │ │─── POST /chat/completions ─│ │ │ (original prompt) │ │ │ │── compress prompt ──┐ │ │ │ │ │ │ │◄─ compressed ───────┘ │ │ │ │ │ │─── forward compressed ────────►│ │ │ │ │ │◄── response ──────────────────│ │◄── response ───────────────│ │ │ │ │ │ │── calculate savings │ │ │── deduct balance │ ``` ## Supported models OpenCompress works with any model available on OpenRouter: GPT-4o, GPT-4o-mini, GPT-4.1, GPT-4.1-mini, GPT-4.1-nano Claude Opus 4.6, Claude Sonnet 4.6, Claude Haiku 4.5 Gemini 2.5 Pro, Gemini 2.5 Flash Llama 4 Maverick, Llama 4 Scout DeepSeek V3, DeepSeek R1 Use your own API key with any provider ## Next steps Understand the compression pipeline Use your own LLM API key