Metadata-Version: 2.5
Name: semcacher
Version: 0.3.0
Summary: A semantic cache for LLM calls: reuse answers to questions that mean the same thing, and track hit rate and money saved.
Project-URL: Homepage, https://github.com/sjapanjots/Semantic_Cache_LLM
Project-URL: Issues, https://github.com/sjapanjots/Semantic_Cache_LLM/issues
Project-URL: Changelog, https://github.com/sjapanjots/Semantic_Cache_LLM/blob/main/CHANGELOG.md
Author: Japanjot Singh
License: 
                                         Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
License-File: NOTICE
Keywords: anthropic,cache,claude,cost,embeddings,llm,openai,semantic-cache
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: numpy>=1.22
Provides-Extra: dev
Requires-Dist: anthropic>=0.40; extra == 'dev'
Requires-Dist: fakeredis>=2.20; extra == 'dev'
Requires-Dist: hnswlib>=0.8; extra == 'dev'
Requires-Dist: openai>=1.0; extra == 'dev'
Requires-Dist: opentelemetry-sdk>=1.20; extra == 'dev'
Requires-Dist: pgvector>=0.2; extra == 'dev'
Requires-Dist: prometheus-client>=0.17; extra == 'dev'
Requires-Dist: psycopg[binary]>=3.1; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: ruff>=0.4; extra == 'dev'
Provides-Extra: hnsw
Requires-Dist: hnswlib>=0.8; extra == 'hnsw'
Provides-Extra: local
Requires-Dist: sentence-transformers>=2.2; extra == 'local'
Provides-Extra: openai
Requires-Dist: openai>=1.0; extra == 'openai'
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.20; extra == 'otel'
Provides-Extra: postgres
Requires-Dist: pgvector>=0.2; extra == 'postgres'
Requires-Dist: psycopg[binary]>=3.1; extra == 'postgres'
Provides-Extra: prometheus
Requires-Dist: prometheus-client>=0.17; extra == 'prometheus'
Provides-Extra: redis
Requires-Dist: redis>=5; extra == 'redis'
Description-Content-Type: text/markdown

<p align="center">
  <img src="https://raw.githubusercontent.com/sjapanjots/Semantic_Cache_LLM/main/assets/logo.svg" alt="semcacher" width="480">
</p>

<p align="center">
  <b>A semantic cache for LLM calls.</b><br>
  If a new question means the same as an old one, return the saved answer.<br>
  Track your hit rate and how much money it saved.
</p>

<p align="center">
  <a href="https://github.com/sjapanjots/Semantic_Cache_LLM/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/sjapanjots/Semantic_Cache_LLM/actions/workflows/ci.yml/badge.svg"></a>
  <img alt="Python" src="https://img.shields.io/badge/python-3.10%2B-blue">
  <img alt="License" src="https://img.shields.io/badge/license-Apache--2.0-blue">
</p>

---

## Why

Users ask the same things in different words. An exact-match cache misses
*"How do I reverse a list in Python?"* vs *"python: how to reverse a list"*, so you pay
for the same answer twice. **semcacher** embeds each prompt, finds the closest one already
answered, and returns that answer when the two are similar enough. Every hit is counted
in tokens and dollars, so you can see what the cache is worth.

- **Drop-in**: wrap an `OpenAI` or `Anthropic` client, decorate a function, or call
  `get` / `set` yourself.
- **Shows savings**: hit rate, exact vs semantic hits, tokens saved, money saved and
  spent, broken down per model.
- **Safe defaults**: answers never cross models, namespaces, system prompts or
  conversation history. Truncated or refused responses are not cached.
- **Small**: the core needs only `numpy`. Neural embedders are optional extras.
- **Persistent**: one SQLite file holds entries and stats. TTL and LRU size limits
  are built in.

## Install

```bash
pip install semcacher                       # core (numpy only)
pip install "semcacher[local]"              # + sentence-transformers, runs locally
pip install "semcacher[openai]"             # + OpenAI embeddings
pip install "semcacher[redis]"              # + shared cache in Redis
pip install "semcacher[hnsw]"               # + fast search for very large caches
pip install "semcacher[postgres]"           # + cache in PostgreSQL (pgvector)
pip install "semcacher[prometheus]"         # + Prometheus metrics
pip install "semcacher[otel]"               # + OpenTelemetry metrics
```

You install `semcacher` and import `semcache`:

```python
from semcache import SemanticCache
```

From source:

```bash
pip install git+https://github.com/sjapanjots/Semantic_Cache_LLM
```

## Quickstart

```python
from semcache import SemanticCache, LLMResult

cache = SemanticCache(pricing={"demo-model": (2.50, 10.00)})  # USD per 1M input/output tokens

def call_llm(prompt):
    ...  # your real LLM call
    return LLMResult("answer", input_tokens=1200, output_tokens=400)

cache.get_or_call("How do I reverse a list in Python?", lambda: call_llm(...), model="demo-model")
cache.get_or_call("python: how to reverse a list",      lambda: call_llm(...), model="demo-model")  # cache hit

print(cache.stats)
```

Output of [`examples/quickstart.py`](examples/quickstart.py), which needs no API key:

```text
lookups                   6
hits                      3  (50.0%)
  exact                   1
  semantic                2
misses                    3
tokens saved          4,800
money saved         $0.0210
money spent         $0.0210
savings rate          50.0%
```

## Usage

### 1. Wrap your client (no other code changes)

```python
from anthropic import Anthropic
from semcache import SemanticCache, SentenceTransformerEmbedder
from semcache.integrations import wrap_anthropic

cache = SemanticCache(embedder=SentenceTransformerEmbedder(), path="cache.db")
client = wrap_anthropic(Anthropic(), cache)

client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "How should a Python dev learn Rust?"}],
)
```

`wrap_openai(OpenAI(), cache)` does the same for `client.chat.completions.create`.
Async clients (`AsyncAnthropic`, `AsyncOpenAI`) work too. On a hit you get back the
SDK's normal response object, rebuilt from the cache.

How requests are matched:

| Part of the request | Treatment |
|---|---|
| Last user message | Compared **by meaning** |
| Model | Must match exactly |
| System prompt, earlier turns, tools, temperature, max tokens, ... | Hashed; must match exactly |
| `timeout`, `extra_headers`, `user`, `metadata` | Ignored |
| `stream=True` | Cached too: a miss streams live and is saved at the end; a hit is replayed as a stream |
| Responses stopped by `max_tokens` / `refusal` / `length` / `content_filter` | Not cached |

**Streaming.** `stream=True` works with both wrappers, sync and async:

```python
with client.messages.create(model="claude-opus-5-5", max_tokens=1024, stream=True,
                            messages=[{"role": "user", "content": question}]) as stream:
    for event in stream:          # live from the API on a miss, replayed on a hit
        ...
```

On a miss you get the provider's stream unchanged, and the answer is saved once the
stream finishes normally; if you stop reading early, nothing is saved. On a hit the
saved answer is replayed as the provider's own event types (each content block's
text arrives in one event). Streamed and non-streamed requests share entries. For
OpenAI, pass `stream_options={"include_usage": True}` so savings can be counted.

### 2. Decorate a function

```python
@cache.cached(model="claude-sonnet-5-5")
def ask(prompt: str) -> LLMResult:
    response = my_llm(prompt)
    return LLMResult(response.text, input_tokens=response.in_tok, output_tokens=response.out_tok)

ask("How many days are in a leap year?")
ask("how many days does a leap year have")   # served from the cache
```

Works on `async def` functions too. Use `key=lambda *a, **kw: ...` to choose which
argument is the prompt.

### 3. Call `get` / `set` yourself

```python
answer = cache.get(prompt, model="claude-opus-5-5")
if answer is None:
    answer, usage = call_llm(prompt)
    cache.set(prompt, answer, model="claude-opus-5-5",
              input_tokens=usage.input, output_tokens=usage.output)
```

`cache.lookup(...)` returns a `CacheHit` with `.response`, `.similarity`, `.exact`,
`.cost_saved` and the stored `.entry`.

## Choosing an embedder and threshold

The threshold is the minimum cosine similarity for a semantic hit. Each embedder ships
a conservative default; tune it on your own traffic.

| Embedder | Install | Default threshold | Notes |
|---|---|---|---|
| `HashingEmbedder` (default) | core | 0.70 | Lexical (words and character n-grams). No model download. Catches rewording, not synonyms. |
| `SentenceTransformerEmbedder()` | `[local]` | 0.85 | Real semantic matching, runs on CPU. `all-MiniLM-L6-v2` by default. |
| `OpenAIEmbedder()` | `[openai]` | 0.90 | `text-embedding-3-small` by default. Costs a small amount per lookup. |
| `CallableEmbedder(fn, name)` | core | 0.85 | Bring any model: Voyage, Cohere, an in-house service... |

Too many wrong answers? Raise the threshold. Too few hits? Lower it, or switch to a
neural embedder. You can also override it per call: `cache.lookup(p, threshold=0.95)`.

### Calibrating the threshold from your own data

Instead of guessing, label some prompt pairs as same or different meaning and let
`calibrate` pick the threshold:

```python
from semcache import HashingEmbedder, SemanticCache, calibrate, load_pairs

pairs = load_pairs("examples/tuning_pairs.csv")   # CSV columns: a,b,same
result = calibrate(HashingEmbedder(), pairs)        # or target_precision=0.99
print(result.summary())
cache = SemanticCache(threshold=result.threshold)
```

```text
embedder   hashing-v2-1024-3
pairs      20 (10 same, 10 different)
recommend  threshold=0.7087  (best F0.5)

threshold  precision   recall  wrong hits    F0.5
   0.6725      87.5%    70.0%           1   0.833
   0.6800     100.0%    70.0%           0   0.921
   0.7087     100.0%    70.0%           0   0.921  <-
   0.7099     100.0%    60.0%           0   0.882
```

*Precision* is the share of hits that are correct; *recall* is the share of
same-meaning pairs that hit. By default the recommendation maximises F0.5, which
counts a wrong answer as worse than a miss. Pass `target_precision=0.99` to get the
loosest threshold that is still right 99% of the time. `result.mistakes()` lists the
pairs it gets wrong. Use the same embedder you'll use in the cache, and aim for at
least a few dozen pairs drawn from real traffic.

### Double-checking borderline matches with a cheap LLM

Some different questions look almost identical to an embedder: *"convert 10 miles to
km"* vs *"convert 20 miles to km"*. A verifier asks a small model whether the saved
answer really answers the new question before it is reused:

```python
from anthropic import Anthropic
from semcache import SemanticCache
from semcache.verifier import LLMVerifier, anthropic_judge

verifier = LLMVerifier(anthropic_judge(Anthropic()), verify_below=0.95)
cache = SemanticCache(verifier=verifier, threshold=0.6)
print(verifier.stats)   # checks, approved, rejected, judge tokens and cost
```

- Only semantic hits are checked; exact matches never are. `verify_below` skips the
  check for very close matches.
- Because the verifier filters out bad matches, you can lower the threshold and get
  more hits.
- `anthropic_judge` uses Claude Haiku 5.5 at low effort by default;
  `openai_judge(client, model)` and any `judge(system, user) -> str` function work too.
- Decisions are remembered per question and entry, so repeats cost nothing.
- If the judge fails or answers unclearly, the hit is rejected (`on_error="reject"`):
  an extra LLM call is cheaper than a wrong answer.

## Tracking savings

```python
s = cache.stats
s.hit_rate          # 0.42
s.cost_saved        # 18.73  (USD)
s.cost_spent        # 25.90
s.savings_rate      # 0.42   share of the would-be bill avoided
s.tokens_saved      # 3_912_000
s.by_model["claude-opus-5-5"].hit_rate
s.to_dict()         # for your metrics pipeline
```

Money saved is the price of the original call, credited every time its answer is
reused. Prices come from a `PriceBook`:

```python
from semcache import PriceBook

cache = SemanticCache(pricing={"gpt-4o-mini": (0.15, 0.60)})        # merged over defaults
cache = SemanticCache(pricing=PriceBook(default=(1.0, 3.0)))        # fallback for unknown models
cache.set(prompt, answer, cost=0.0123)                              # or give the exact cost
```

Claude list prices are bundled (run `semcache prices`). Prices change, so check your
provider's pricing page. Models without a price still count toward hit rate but add
$0 to savings.

### Dashboards: Prometheus and OpenTelemetry

`semcache.metrics` publishes the same numbers as `cache.stats` (lookups, exact and
semantic hits, misses, tokens saved, money saved and spent, hit ratio, entries, and
per-model versions) so you can graph and alert on them.

```python
# Prometheus, with prometheus_client
from prometheus_client import REGISTRY, start_http_server
from semcache.metrics import PrometheusCollector

REGISTRY.register(PrometheusCollector(cache))
start_http_server(9100)                      # scrape http://host:9100/metrics

# Prometheus, no extra packages: return this text from your own /metrics route
from semcache.metrics import prometheus_text
body = prometheus_text(cache)

# OpenTelemetry: reported through whatever MeterProvider your app configured
from semcache.metrics import register_opentelemetry
register_opentelemetry(cache)
```

Values are read live on every scrape or export; there is nothing to update by hand.
Main metric names: `semcache_hits_total{kind="exact|semantic"}`,
`semcache_cost_saved_usd_total`, `semcache_hit_ratio`,
`semcache_model_hits_total{model="..."}` (OpenTelemetry uses `semcache.hits` and so on).

## Persistence, expiry and size limits

```python
cache = SemanticCache(
    path="cache.db",        # SQLite file; entries and stats survive restarts
    ttl=7 * 24 * 3600,      # entries expire after a week
    max_entries=50_000,     # least recently used entries are evicted
    namespace="support-bot",
)
```

- Responses stored in SQLite must be JSON-serialisable. The client wrappers handle
  this for you.
- A cache file remembers which embedder built it and refuses to open with a
  different one, because their vectors aren't comparable.
- Use `with SemanticCache(...) as cache:` or call `cache.close()` so the latest stats
  are written.

### Sharing one cache between servers (Redis)

SQLite keeps the cache on one machine. To let several processes or servers reuse
each other's answers, keep it in Redis (or any Redis-compatible server such as
Valkey; no modules needed):

```python
from semcache import SemanticCache
from semcache.redis_store import RedisStore

cache = SemanticCache(store=RedisStore("redis://localhost:6379/0"))
```

- Every process sees the others' answers immediately.
- Stats are shared too: each process adds its own counts to the totals in Redis,
  so `cache.stats` shows the hit rate and money saved across all of them.
- `prefix="team-a:"` keeps several caches apart in one database.
- Search runs in each process: it downloads each vector once, then only fetches
  the list of entry ids per lookup. That is fast up to tens of thousands of
  entries per namespace.

### Keeping the cache in PostgreSQL (pgvector)

If you already run Postgres, keep the cache there: every server shares the same
answers and stats, and the similarity search runs in the database.

```python
from semcache import SemanticCache
from semcache.postgres_store import PostgresStore

cache = SemanticCache(store=PostgresStore("postgresql://user:pass@db:5432/app"))
```

- Needs the [pgvector](https://github.com/pgvector/pgvector) extension; the store runs
  `CREATE EXTENSION IF NOT EXISTS vector` (or create it once yourself).
- Creates `semcache_entries` (plus `_meta` and `_stats` tables) on the first write;
  `table="team_a_cache"` keeps several caches apart in one database.
- `index="hnsw"` adds a pgvector HNSW index for very large tables. Search stays exact by
  default, and a namespace the approximate search misses is searched exactly.
- Stats from all servers add up, as with Redis.

### Very large caches (HNSW index)

By default every lookup compares the question with every saved entry: exact, and fast
up to tens of thousands of entries per namespace. For more, use an HNSW index:

```python
cache = SemanticCache(path="cache.db", index="hnsw")        # or InMemoryStore(index="hnsw")
```

Measured on 100,000 entries (128-dim vectors, 4 CPU cores):

| | per lookup | finds the closest entry |
|---|---|---|
| exact (default) | 1.35 ms | always |
| `index="hnsw"` | 0.30 ms | 99.7% |

HNSW is approximate, but a missed neighbour can only cost a cache miss, never a wrong
answer: whatever it returns must still pass the similarity threshold. Tune it with
`index=lambda dim: HNSWIndex(dim, M=32, ef_search=256)`, or plug in any index with
`add` / `remove` / `search` (see `semcache.index`). A SQLite cache rebuilds its index
when it opens, in bulk (100,000 entries in about 12 s). `RedisStore` always searches
exactly.

## CLI

```bash
semcache stats --db cache.db          # hit rate, tokens and money saved
semcache stats --db cache.db --json
semcache list  --db cache.db          # most-hit entries
semcache prune --db cache.db --older-than 86400
semcache clear --db cache.db [--namespace support-bot] [--stats]
semcache prices                       # bundled price table
```

## How it works

```text
prompt ──► normalise ──► exact match in scope? ──yes──► HIT (similarity 1.0)
                              │ no
                              ▼
                           embed ──► nearest neighbour in scope ──► ≥ threshold? ──yes──► HIT
                                                                        │ no
                                                                        ▼
                                                                      MISS ──► call LLM ──► set()
```

A *scope* is `namespace + model`; the client wrappers add a hash of the rest of the
request. Search is an exact cosine scan over a NumPy matrix per scope, fast enough for
tens of thousands of entries per scope.

## When not to use it

- Answers that depend on time or live data ("what's the weather now"). Use a `ttl`,
  or don't cache those calls.
- Prompts where small wording changes matter, such as code with specific values or
  math with different numbers. Use a high threshold or a separate namespace.
- Personalised answers. Put a user or tenant id in `namespace` so answers never
  leak between users.

## Development

```bash
pip install -e ".[dev]"
pytest -q
ruff check . && ruff format --check .
```

See [CONTRIBUTING.md](CONTRIBUTING.md) and [CHANGELOG.md](CHANGELOG.md).

## Roadmap

- OpenAI Responses API in `wrap_openai`

## License

[Apache License 2.0](LICENSE). See [NOTICE](NOTICE): if you share a modified version,
keep the notices and mark the files you changed. Versions up to and including 0.1.0
were released under the MIT License.
