{
  "schema_version": 2,
  "id": "develop/ai/redisvl/user_guide/how_to_guides/semantic_cache_observability",
  "title": "Tune the Semantic Cache with Telemetry",
  "url": "https://redis.io/docs/latest/develop/ai/redisvl/user_guide/how_to_guides/semantic_cache_observability/",
  "summary": "",
  "aliases": [
    "/integrate/redisvl/user_guide/how_to_guides/15_semantic_cache_observability"
  ],
  "tags": [],
  "last_updated": "2026-11-19T09:14:02+01:00",
  "page_type": "content",
  "content_hash": "4bebc240e94ce72fd52916d94684e0a0d1bfa603e73c6af20f44b57e1e00afe7",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "This notebook runs a small FAQ cache, sends it a mix of lookups and reads back the telemetry RedisVL emits through [OpenTelemetry](https://opentelemetry.io/): a trace for every lookup, a hit rate, and the distance of the nearest match on every lookup, hits and misses alike. The last part uses those distances to weigh a change to `distance_threshold`.\n\n[Observe the Semantic Cache with OpenTelemetry](https://redis.io/docs/latest/observability) is the reference for every span, metric and attribute used here."
    },
    {
      "id": "prerequisites",
      "title": "Prerequisites",
      "role": "content",
      "text": "- RedisVL with the `otel` extra, the OpenTelemetry SDK and sentence-transformers: `pip install \"redisvl[otel]\" \"opentelemetry-sdk>=1.32\" sentence-transformers`\n- For the local stack only: the OTLP exporter, `pip install opentelemetry-exporter-otlp-proto-http`, and redis-py 7.4 or later for its command metrics\n- A running Redis instance ([Redis 8+](https://redis.io/downloads/) or [Redis Cloud](https://redis.io/cloud)) at `localhost:6379`, or set `REDIS_URL`\n\nTo see the same telemetry in Grafana, start the local stack described in the guide's [Explore with a local stack](observability.md#explore-with-a-local-stack) section, and set `OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318` before you start Jupyter. Without it, everything stays in memory."
    },
    {
      "id": "what-youll-learn",
      "title": "What you'll learn",
      "role": "content",
      "text": "- How an application configures OpenTelemetry, and why RedisVL needs nothing more\n- What one cache lookup looks like as a trace\n- How to read the hit rate and the distance distribution from the metrics\n- How to use those distances to judge a threshold change, and where they stop being enough"
    },
    {
      "id": "configure-opentelemetry",
      "title": "Configure OpenTelemetry",
      "role": "configuration",
      "text": "RedisVL depends only on the OpenTelemetry API. The application owns the SDK: it sets a tracer provider and a meter provider once, at start-up, and every instrumented library picks them up.\n\nHere both providers keep their data in memory, so the notebook can read it back. When `OTEL_EXPORTER_OTLP_ENDPOINT` is set, they also export it over OTLP, and redis-py's own command metrics are turned on so the dashboard can show search and TTL refresh latency.\n\n\n[code example]\n\n    Keeping telemetry in memory only"
    },
    {
      "id": "build-an-faq-cache",
      "title": "Build an FAQ cache",
      "role": "content",
      "text": "The cache uses `redis/langcache-embed-v2`, an embedding model trained for semantic caching, the default threshold of 0.1 in cosine distance, and a one-hour TTL, which every hit refreshes. Nothing in this cell is specific to OpenTelemetry: the cache reports to whichever providers the application set.\n\n\n[code example]\n\n    Stored 5 entries"
    },
    {
      "id": "send-a-mix-of-lookups",
      "title": "Send a mix of lookups",
      "role": "content",
      "text": "The lookups fall into three groups: rewordings of a stored question, which you would want served from the cache; different questions that happen to sit close to a stored one, which you would not; and unrelated questions.\n\n\n[code example]\n\n`check` returns the matching entries, or an empty list, but never the distance that decided it. RedisVL reports that distance through telemetry instead: each lookup's `retrieval` span carries `redisvl.cache.distance`, the nearest candidate's distance, on misses as well as hits. Matching each lookup span with its retrieval span recovers it:\n\n\n[code example]\n\n    lookup                                     kind                 result distance\n    How can I reset my password?               paraphrase           hit    0.025\n    Which city is the capital of France?       paraphrase           hit    0.074\n    What's the capital city of France?         paraphrase           hit    0.077\n    Can I exchange an item after 30 days?      different question   miss   0.113\n    How many days does shipping take?          paraphrase           miss   0.126\n    What hours are you open?                   paraphrase           miss   0.137\n    I forgot my password, how do I reset it?   paraphrase           miss   0.142\n    Can I return an item after 60 days?        different question   miss   0.144\n    How do I delete my account?                unrelated            miss   0.521\n    Recommend a good book                      unrelated            miss   0.632\n    What's the weather like today?             unrelated            miss   0.645\n\n\nThree paraphrases hit. Three more miss by a small margin, at a distance not far above 0.1, and the two different questions sit in the same band. The unrelated lookups are far away. Remember that pattern: it is what the threshold section below is about."
    },
    {
      "id": "read-one-trace",
      "title": "Read one trace",
      "role": "content",
      "text": "A **trace** is the record of one operation, made of **spans**: timed steps, each with a name, a parent and attributes. Every `check` produces a `semantic_cache.check` span with two children, one for embedding the prompt and one for the vector search:\n\n\n[code example]\n\n    semantic_cache.check  [INTERNAL]  19.93 ms\n        redisvl.cache.name = faq_cache\n        redisvl.cache.result = hit\n        embeddings redis/langcache-embed-v2  [CLIENT]  13.06 ms\n            gen_ai.operation.name = embeddings\n            gen_ai.provider.name = hf\n            gen_ai.request.model = redis/langcache-embed-v2\n            gen_ai.embeddings.dimension.count = 768\n        retrieval faq_cache  [CLIENT]  2.46 ms\n            gen_ai.operation.name = retrieval\n            gen_ai.data_source.id = faq_cache\n            gen_ai.retrieval.top_k = 1\n            db.system.name = redis\n            db.collection.name = faq_cache\n            db.operation.name = FT.SEARCH\n            redisvl.cache.distance_threshold = 0.1\n            redisvl.cache.distance = 0.0253240466118\n\n\nEmbedding the prompt usually dominates: here it runs a local model, and with a hosted provider it is a network call. The span records no prompt text. RedisVL captures prompts only when you opt in, as the guide's [Privacy](observability.md#privacy-and-content-capture) section describes."
    },
    {
      "id": "read-the-metrics",
      "title": "Read the metrics",
      "role": "content",
      "text": "Traces describe single operations; **metrics** aggregate them. RedisVL records two histograms for the cache:\n\n- `redisvl.semantic_cache.operation.duration`, one point per operation, split by `redisvl.cache.operation` and, for lookups, by `redisvl.cache.result`. Its `check` count is the number of lookups, so it also gives the hit rate.\n- `redisvl.semantic_cache.distance`, the nearest distance of every lookup, in buckets.\n\nA real application exports these every minute or so; here the in-memory reader collects them on demand.\n\n\n[code example]\n\n    3 hits, 8 misses: hit rate 27%\n\n\nThe distance histogram counts lookups per bucket. Bucket boundaries are 0.01 apart up to 0.1, then coarser up to 2, the largest cosine distance. Printing the misses' non-empty buckets shows where they fall:\n\n\n[code example]\n\n    0.100 to 0.125  #  1\n    0.125 to 0.150  ####  4\n    0.500 to 0.750  ###  3"
    },
    {
      "id": "weigh-a-threshold-change",
      "title": "Weigh a threshold change",
      "role": "content",
      "text": "The histogram answers a \"what if\" question directly: how many of today's misses would a looser threshold have served? Because each bucket is a count, the share of misses at or below a candidate threshold is the sum of the buckets up to it, divided by all the misses that recorded a distance. A miss with no candidate at all, such as one whose filter excluded every entry, records none. The candidate must be a bucket boundary.\n\n\n[code example]\n\n    threshold 0.125: 12% of misses would hit\n    threshold 0.15: 62% of misses would hit\n    threshold 0.2: 62% of misses would hit\n\n\nA looser threshold would serve more lookups, but the metric cannot say whether those matches would be right. This notebook knows which lookups are which, so it can show what loosening to 0.15 would actually serve:\n\n\n[code example]\n\n    0.113  different question   Can I exchange an item after 30 days?\n    0.126  paraphrase           How many days does shipping take?\n    0.137  paraphrase           What hours are you open?\n    0.142  paraphrase           I forgot my password, how do I reset it?\n    0.144  different question   Can I return an item after 60 days?\n\n\nThe paraphrases are wins. The two different questions are not: each would receive the answer to a question nobody asked. Someone asking about a return after 60 days would be told yes, although the window closes at 45.\n\nIn production you do not have the `kind` column. To see which prompts sit near the threshold, turn on content capture for a while, which puts the prompt on each retrieval span, and inspect the traces in that band before moving the threshold. The guide's [Tune the distance threshold](observability.md#tune-the-distance-threshold) section covers this, and the PromQL to run against a real backend."
    },
    {
      "id": "send-traffic-to-the-dashboard",
      "title": "Send traffic to the dashboard",
      "role": "content",
      "text": "This cell only applies when you are exporting to the local stack. It sends a steady stream of the same lookups for three minutes so the dashboard has something to draw, then flushes. Open Grafana at http://localhost:3000 while it runs.\n\n\n[code example]\n\n    Set OTEL_EXPORTER_OTLP_ENDPOINT before starting Jupyter, then rerun the notebook to export."
    },
    {
      "id": "clean-up",
      "title": "Clean up",
      "role": "content",
      "text": "[code example]"
    }
  ],
  "examples": [
    {
      "id": "configure-opentelemetry-ex0",
      "language": "python",
      "code": "import os\n\nfrom opentelemetry import metrics, trace\nfrom opentelemetry.sdk.metrics import MeterProvider\nfrom opentelemetry.sdk.metrics.export import (\n    InMemoryMetricReader,\n    PeriodicExportingMetricReader,\n)\nfrom opentelemetry.sdk.resources import Resource\nfrom opentelemetry.sdk.trace import TracerProvider\nfrom opentelemetry.sdk.trace.export import BatchSpanProcessor, SimpleSpanProcessor\nfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import (\n    InMemorySpanExporter,\n)\n\n# The service name identifies this process in every backend.\nresource = Resource.create({\"service.name\": \"redisvl-semantic-cache-example\"})\n\nspans = InMemorySpanExporter()\ntracer_provider = TracerProvider(resource=resource)\ntracer_provider.add_span_processor(SimpleSpanProcessor(spans))\n\nreader = InMemoryMetricReader()\nmetric_readers = [reader]\n\nexport_otlp = \"OTEL_EXPORTER_OTLP_ENDPOINT\" in os.environ\nif export_otlp:\n    from opentelemetry.exporter.otlp.proto.http.metric_exporter import (\n        OTLPMetricExporter,\n    )\n    from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter\n\n    tracer_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))\n    metric_readers.append(\n        PeriodicExportingMetricReader(OTLPMetricExporter(), export_interval_millis=10_000)\n    )\n\ntrace.set_tracer_provider(tracer_provider)\nmeter_provider = MeterProvider(resource=resource, metric_readers=metric_readers)\nmetrics.set_meter_provider(meter_provider)\n\nif export_otlp:\n    from redis.observability import MetricGroup, OTelConfig, get_observability_instance\n\n    get_observability_instance().init(\n        OTelConfig(\n            metric_groups=[\n                MetricGroup.CONNECTION_BASIC,\n                MetricGroup.RESILIENCY,\n                MetricGroup.COMMAND,\n            ]\n        )\n    )\n\nprint(\"Exporting over OTLP\" if export_otlp else \"Keeping telemetry in memory only\")",
      "section_id": "configure-opentelemetry"
    },
    {
      "id": "build-an-faq-cache-ex0",
      "language": "python",
      "code": "from redisvl.extensions.cache.llm import SemanticCache\nfrom redisvl.utils.vectorize import HFTextVectorizer\n\nos.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n\nvectorizer = HFTextVectorizer(\n    model=\"redis/langcache-embed-v2\",\n    cache_folder=os.getenv(\"SENTENCE_TRANSFORMERS_HOME\"),\n)\ncache = SemanticCache(\n    name=\"faq_cache\",\n    vectorizer=vectorizer,\n    distance_threshold=0.1,\n    ttl=3600,\n    redis_url=os.getenv(\"REDIS_URL\", \"redis://localhost:6379\"),\n    overwrite=True,\n)\n\nfaq = {\n    \"What is the capital of France?\": \"Paris.\",\n    \"How do I reset my password?\": \"Choose 'Forgot password' on the sign-in page.\",\n    \"What are your opening hours?\": \"9am to 6pm, Monday to Saturday.\",\n    \"How long does shipping take?\": \"Three to five working days.\",\n    \"Can I return an item after 30 days?\": \"Yes, returns are accepted up to 45 days after delivery.\",\n}\nfor prompt, response in faq.items():\n    cache.store(prompt=prompt, response=response)\n\nprint(f\"Stored {len(faq)} entries\")",
      "section_id": "build-an-faq-cache"
    },
    {
      "id": "send-a-mix-of-lookups-ex0",
      "language": "python",
      "code": "lookups = {\n    \"How can I reset my password?\": \"paraphrase\",\n    \"Which city is the capital of France?\": \"paraphrase\",\n    \"What's the capital city of France?\": \"paraphrase\",\n    \"What hours are you open?\": \"paraphrase\",\n    \"How many days does shipping take?\": \"paraphrase\",\n    \"I forgot my password, how do I reset it?\": \"paraphrase\",\n    \"Can I exchange an item after 30 days?\": \"different question\",\n    \"Can I return an item after 60 days?\": \"different question\",\n    \"What's the weather like today?\": \"unrelated\",\n    \"Recommend a good book\": \"unrelated\",\n    \"How do I delete my account?\": \"unrelated\",\n}\n\nspans.clear()\nfor prompt in lookups:\n    cache.check(prompt=prompt)",
      "section_id": "send-a-mix-of-lookups"
    },
    {
      "id": "send-a-mix-of-lookups-ex1",
      "language": "python",
      "code": "def lookup_rows(finished):\n    by_trace = {}\n    for span in finished:\n        by_trace.setdefault(span.context.trace_id, {})[span.name.split(\" \")[0]] = span\n    checks = [s for s in finished if s.name == \"semantic_cache.check\"]\n    for prompt, check in zip(lookups, sorted(checks, key=lambda s: s.start_time)):\n        retrieval = by_trace[check.context.trace_id][\"retrieval\"]\n        yield (\n            prompt,\n            lookups[prompt],\n            check.attributes[\"redisvl.cache.result\"],\n            retrieval.attributes[\"redisvl.cache.distance\"],\n        )\n\n\nrows = list(lookup_rows(spans.get_finished_spans()))\nprint(f\"{'lookup':42} {'kind':20} {'result':6} distance\")\nfor prompt, kind, result, distance in sorted(rows, key=lambda row: row[3]):\n    print(f\"{prompt:42} {kind:20} {result:6} {distance:.3f}\")",
      "section_id": "send-a-mix-of-lookups"
    },
    {
      "id": "read-one-trace-ex0",
      "language": "python",
      "code": "def print_trace(finished, trace_id):\n    members = sorted(\n        (s for s in finished if s.context.trace_id == trace_id),\n        key=lambda s: s.start_time,\n    )\n    for span in members:\n        depth = 0 if span.parent is None else 1\n        duration_ms = (span.end_time - span.start_time) / 1e6\n        print(f\"{'    ' * depth}{span.name}  [{span.kind.name}]  {duration_ms:.2f} ms\")\n        for key, value in span.attributes.items():\n            print(f\"{'    ' * depth}    {key} = {value}\")\n\n\nfinished = spans.get_finished_spans()\nfirst_check = min(\n    (s for s in finished if s.name == \"semantic_cache.check\"), key=lambda s: s.start_time\n)\nprint_trace(finished, first_check.context.trace_id)",
      "section_id": "read-one-trace"
    },
    {
      "id": "read-the-metrics-ex0",
      "language": "python",
      "code": "def histogram_points(name):\n    data = reader.get_metrics_data()\n    for resource_metrics in data.resource_metrics:\n        for scope_metrics in resource_metrics.scope_metrics:\n            for metric in scope_metrics.metrics:\n                if metric.name == name:\n                    yield from metric.data.data_points\n\n\nlookups_by_result = {\n    point.attributes[\"redisvl.cache.result\"]: point.count\n    for point in histogram_points(\"redisvl.semantic_cache.operation.duration\")\n    if point.attributes[\"redisvl.cache.operation\"] == \"check\"\n}\nhits, misses = lookups_by_result.get(\"hit\", 0), lookups_by_result.get(\"miss\", 0)\nprint(f\"{hits} hits, {misses} misses: hit rate {hits / (hits + misses):.0%}\")",
      "section_id": "read-the-metrics"
    },
    {
      "id": "read-the-metrics-ex1",
      "language": "python",
      "code": "distances = {\n    point.attributes[\"redisvl.cache.result\"]: point\n    for point in histogram_points(\"redisvl.semantic_cache.distance\")\n}\nmiss_distances = distances[\"miss\"]\nlower = 0.0\nfor upper, count in zip(miss_distances.explicit_bounds, miss_distances.bucket_counts):\n    if count:\n        print(f\"{lower:.3f} to {upper:.3f}  {'#' * count}  {count}\")\n    lower = upper",
      "section_id": "read-the-metrics"
    },
    {
      "id": "weigh-a-threshold-change-ex0",
      "language": "python",
      "code": "def share_of_misses_within(threshold):\n    within = sum(\n        count\n        for upper, count in zip(miss_distances.explicit_bounds, miss_distances.bucket_counts)\n        if upper <= threshold\n    )\n    return within / miss_distances.count\n\n\nfor candidate in (0.125, 0.15, 0.2):\n    print(f\"threshold {candidate}: {share_of_misses_within(candidate):.0%} of misses would hit\")",
      "section_id": "weigh-a-threshold-change"
    },
    {
      "id": "weigh-a-threshold-change-ex1",
      "language": "python",
      "code": "for prompt, kind, result, distance in sorted(rows, key=lambda row: row[3]):\n    if result == \"miss\" and distance <= 0.15:\n        print(f\"{distance:.3f}  {kind:20} {prompt}\")",
      "section_id": "weigh-a-threshold-change"
    },
    {
      "id": "send-traffic-to-the-dashboard-ex0",
      "language": "python",
      "code": "# NBVAL_SKIP\nimport random\nimport time\n\nif export_otlp:\n    deadline = time.monotonic() + 180\n    while time.monotonic() < deadline:\n        cache.check(prompt=random.choice(list(lookups)))\n        time.sleep(0.2)\n    tracer_provider.force_flush()\n    meter_provider.force_flush()\n    print(\"Done. Open http://localhost:3000\")\nelse:\n    print(\"Set OTEL_EXPORTER_OTLP_ENDPOINT before starting Jupyter, then rerun the notebook to export.\")",
      "section_id": "send-traffic-to-the-dashboard"
    },
    {
      "id": "clean-up-ex0",
      "language": "python",
      "code": "cache.delete()\ntracer_provider.shutdown()\nmeter_provider.shutdown()",
      "section_id": "clean-up"
    }
  ]
}
