/fe-app-toolkit:lakebase-semantic-cachefrom fe-app-toolkit
Adding semantic caching to a Databricks App, reducing duplicate LLM calls, pgvector caching
Ships in fe-app-toolkit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Semantic caching layer for Databricks Apps using Lakebase PostgreSQL and pgvector. Reduces LLM costs by returning cached answers for semantically similar queries.
https://github.com/databricks-field-eng/lakebase-semantic-cache-for-chat-agents.gitpip install -e . (from cloned repo)Use this library when you need to:
ChatOrchestrator pipelineCREATE EXTENSION IF NOT EXISTS vectordatabricks-gte-large-en)The cache resolves its database connection in this order:
from semantic_cache import SemanticCache
cache = SemanticCache(
endpoint_name="my-lakebase-endpoint", # or lakebase_instance="my-instance"
embedding_endpoint="databricks-gte-large-en",
similarity_threshold=0.92, # 0.0-1.0, higher = stricter matching
default_ttl_hours=24,
)
# Initialize tables (run once)
cache.init()
# Lookup
result = cache.lookup(query="What is the price of product X?", owner_id="user-123")
if result:
print(f"Cache hit! Score: {result.similarity}")
print(result.answer)
# Store
cache.store(
query="What is the price of product X?",
answer="The price is $9.99 based on...",
owner_id="user-123",
context_tags={"source": "genie", "dataset": "beverages"},
)
# Invalidate entries by filter (returns count deleted)
deleted = cache.invalidate(namespace="default", owner_id="user-123")
# Clear all entries for an owner
cache.clear(owner_id="user-123")
# Get hit/miss statistics
stats = cache.stats(owner_id="user-123")
print(f"Hit rate: {stats.hit_rate}%")
# Clean up expired entries
cache.cleanup_expired()
SemanticCache(
embedding_endpoint: str = "databricks-gte-large-en",
similarity_threshold: float = 0.92,
default_ttl_hours: float = 24.0,
resolve_fn: Optional[Callable] = None, # Custom connection resolver
lakebase_instance: Optional[str] = None, # Provisioned Lakebase instance name
endpoint_name: Optional[str] = None, # Autoscaling Lakebase endpoint
track_stats: bool = True,
)
| Method | Signature | Description |
|---|---|---|
init() | init() -> None | Creates tables and pgvector index. Safe to call multiple times. |
lookup() | lookup(query: str, owner_id: str, namespace: str = "default", context: Any = None, context_tags: Dict = None, broad: bool = False) -> Optional[CacheHit] | Returns CacheHit (.answer, .similarity, .query_text, .metadata, .created_at, .hit_count) if similarity >= threshold, else None. |
store() | store(query: str, answer: str, owner_id: str, namespace: str = "default", context: Any = None, context_tags: Dict = None, metadata: Dict = None, ttl_hours: float = None) -> None | Stores query/answer pair. |
invalidate() | invalidate(namespace: str = None, owner_id: str = None, context_tags: Dict = None) -> int | Deletes entries matching the given filters. Returns count deleted. |
clear() | clear(owner_id: str = "default") -> int | Deletes all entries for an owner. Returns count deleted. |
stats() | stats(owner_id: str = "default") -> CacheStats | Returns CacheStats dataclass with .total_entries, .hits, .misses, .stores, .hit_rate, .avg_similarity. |
cleanup_expired() | cleanup_expired() -> int | Removes entries past their TTL. Returns count removed. |
| Variable | Required | Default | Description |
|---|---|---|---|
ENDPOINT_NAME | One of these | -- | Autoscaling Lakebase endpoint name |
LAKEBASE_INSTANCE | is required | -- | Provisioned Lakebase instance name |
PGHOST | (or direct PG) | -- | PostgreSQL host (overrides endpoint/instance) |
PGUSER | -- | PostgreSQL user | |
PGPASSWORD | -- | PostgreSQL password | |
PGPORT | No | 5432 | PostgreSQL port |
PGDATABASE | No | databricks_postgres | Database name |
PGSSLMODE | No | require | SSL mode |
The semantic cache plugs directly into the chat-app-utilities ChatOrchestrator:
from semantic_cache import SemanticCache
from chat_app_utilities import ChatOrchestrator
cache = SemanticCache(
endpoint_name="my-endpoint",
embedding_endpoint="databricks-gte-large-en",
similarity_threshold=0.92,
)
orchestrator = ChatOrchestrator(
fm_endpoint="databricks-claude-sonnet-4-5",
system_prompt_builder=lambda s: "You are helpful.",
cache=cache,
cache_owner_fn=lambda: get_current_user_id(),
workspace_client_fn=get_workspace_client,
)
When integrated, Phase 2 of the pipeline checks the cache before invoking any sources or the FM endpoint.
The cache creates an HNSW index (pgvector v0.8.0+) for fast approximate nearest neighbor search. On older pgvector versions, it falls back to Python-side cosine similarity calculation.
SQL prerequisite (run once on your Lakebase instance):
CREATE EXTENSION IF NOT EXISTS vector;
All cache operations are scoped by owner_id. This provides tenant isolation without separate tables:
clear() method only deletes entries for the specified ownerSee references/integration-guide.md for step-by-step setup instructions and troubleshooting.
CREATE EXTENSION IF NOT EXISTS vector -- the cache will fail silently on lookups without pgvector.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub sarah-hord-db/vibe --plugin fe-app-toolkit4 skills in this plugin
/agent-memory-servicePersistent memory for AI agents, MCP memory service, cross-conversation agent memory on Databricks/chat-app-utilitiesAdding admin monitoring, config CRUD, chat pipeline with Genie/KA sources, FastAPI router factories for Databricks Apps/configurable-react-templateBuilding a Databricks App frontend, adding UI features (admin, chat, reports, branding), scaffolding a React app for DatabricksOther plugins' skills for the same job