-
-
Notifications
You must be signed in to change notification settings - Fork 630
Add Semantic Caching and CrewAI Config #4548
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rudransh-shrivastava
wants to merge
12
commits into
OWASP:feature/nestbot-ai-assistant
Choose a base branch
from
rudransh-shrivastava:feature/nestbot-semantic-cache
base: feature/nestbot-ai-assistant
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 9 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
d83ab72
add semantic caching and crewai config
rudransh-shrivastava c0133af
Merge branch 'feature/nestbot-ai-assistant' into feature/nestbot-sema…
rudransh-shrivastava 78c80d6
bot comments
rudransh-shrivastava 1521f59
add tests
rudransh-shrivastava 5cf2d6b
fix sonarqube issues
rudransh-shrivastava 6c9137c
fix sonarqube issues
rudransh-shrivastava 68335dc
do not cache community channel queries
rudransh-shrivastava 55534aa
fix spell check
rudransh-shrivastava 7c05bd5
update code
rudransh-shrivastava 24c77f6
update code
rudransh-shrivastava 1183e55
add docstrings
rudransh-shrivastava 2107768
Merge branch 'feature/nestbot-ai-assistant' into feature/nestbot-sema…
rudransh-shrivastava File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| """CrewAI assistant configuration.""" | ||
|
|
||
| from dataclasses import dataclass | ||
|
|
||
|
|
||
| @dataclass | ||
| class CrewAIConfig: | ||
| """CrewAI assistant configuration.""" | ||
|
|
||
| semantic_cache_enabled: bool = True | ||
| semantic_cache_similarity_threshold: float = 0.95 | ||
| semantic_cache_ttl_seconds: int = 86400 # 24 hours |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| # Generated by Django 6.0.3 on 2026-04-13 14:06 | ||
|
|
||
| import pgvector.django.vector | ||
| from django.db import migrations, models | ||
|
|
||
|
|
||
| class Migration(migrations.Migration): | ||
| dependencies = [ | ||
| ("ai", "0010_alter_context_unique_together"), | ||
| ] | ||
|
|
||
| operations = [ | ||
| migrations.CreateModel( | ||
| name="SemanticCache", | ||
| fields=[ | ||
| ( | ||
| "id", | ||
| models.BigAutoField( | ||
| auto_created=True, primary_key=True, serialize=False, verbose_name="ID" | ||
| ), | ||
| ), | ||
| ("nest_created_at", models.DateTimeField(auto_now_add=True)), | ||
| ("nest_updated_at", models.DateTimeField(auto_now=True)), | ||
| ("confidence", models.FloatField(default=0.0, verbose_name="Confidence")), | ||
| ( | ||
| "intent", | ||
| models.CharField(blank=True, default="", max_length=50, verbose_name="Intent"), | ||
| ), | ||
| ( | ||
| "query_embedding", | ||
| pgvector.django.vector.VectorField( | ||
| dimensions=1536, verbose_name="Query Embedding" | ||
| ), | ||
| ), | ||
| ("query_text", models.TextField(verbose_name="Query Text")), | ||
| ("response_text", models.TextField(verbose_name="Response Text")), | ||
| ], | ||
| options={ | ||
| "verbose_name": "Semantic Cache", | ||
| "db_table": "ai_semantic_cache", | ||
| }, | ||
| ), | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| from .chunk import Chunk | ||
| from .semantic_cache import SemanticCache |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| """AI app semantic cache model.""" | ||
|
|
||
| import logging | ||
| from datetime import UTC, datetime, timedelta | ||
|
|
||
| from django.db import models | ||
| from pgvector.django import VectorField | ||
| from pgvector.django.functions import CosineDistance | ||
|
|
||
| from apps.ai.models.chunk import EMBEDDING_DIMENSIONS | ||
| from apps.common.models import TimestampedModel | ||
| from apps.common.utils import truncate | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| # TODO(rudransh-shrivastava): Add Cache Invalidation cron job. | ||
| class SemanticCache(TimestampedModel): | ||
| """Semantic cache model for storing query-response pairs with embeddings.""" | ||
|
|
||
| class Meta: | ||
| """Model options.""" | ||
|
|
||
| db_table = "ai_semantic_cache" | ||
| verbose_name = "Semantic Cache" | ||
|
|
||
| confidence = models.FloatField(verbose_name="Confidence", default=0.0) | ||
| intent = models.CharField(verbose_name="Intent", blank=True, default="", max_length=50) | ||
| query_embedding = VectorField(verbose_name="Query Embedding", dimensions=EMBEDDING_DIMENSIONS) | ||
| query_text = models.TextField(verbose_name="Query Text") | ||
| response_text = models.TextField(verbose_name="Response Text") | ||
|
|
||
| def __str__(self): | ||
| """Human readable representation.""" | ||
| return f"SemanticCache {self.id}: {truncate(self.query_text, 50)}" | ||
|
|
||
| @staticmethod | ||
| def get_cached_response( | ||
| query: str, | ||
| *, | ||
| similarity_threshold: float = 0.95, | ||
| ttl_seconds: int = 86400, | ||
| ) -> str | None: | ||
| """Look up semantically similar cached response. | ||
|
|
||
| Args: | ||
| query: User query text. | ||
| similarity_threshold: Minimum cosine similarity (0.0-1.0). | ||
| ttl_seconds: Maximum age of cached entries in seconds. | ||
|
|
||
| Returns: | ||
| Cached response string if found, None otherwise. | ||
|
|
||
| """ | ||
| from apps.ai.embeddings.factory import get_embedder # noqa: PLC0415 | ||
|
|
||
| ttl_cutoff = datetime.now(UTC) - timedelta(seconds=ttl_seconds) | ||
| max_distance = 1.0 - similarity_threshold | ||
|
|
||
| result = ( | ||
| SemanticCache.objects.filter(nest_created_at__gte=ttl_cutoff) | ||
| .annotate( | ||
| distance=CosineDistance("query_embedding", get_embedder().embed_query(query)) | ||
| ) | ||
| .filter(distance__lte=max_distance) | ||
| .order_by("distance") | ||
| .first() | ||
| ) | ||
|
|
||
| if result is not None: | ||
| logger.info( | ||
| "Semantic cache hit", | ||
| extra={ | ||
| "cache_id": result.id, | ||
| "distance": float(result.distance), | ||
| "query_preview": query[:100], | ||
| }, | ||
| ) | ||
| return result.response_text | ||
|
|
||
| return None | ||
|
|
||
| @staticmethod | ||
| def store_response( | ||
| query: str, | ||
| response: str, | ||
| intent: str = "", | ||
| confidence: float = 0.0, | ||
| ) -> "SemanticCache": | ||
| """Store query-response pair in semantic cache. | ||
|
|
||
| Args: | ||
| query: Original query text. | ||
| response: Generated response text. | ||
| intent: Classified intent for the query. | ||
| confidence: Router confidence score. | ||
|
|
||
| Returns: | ||
| Created SemanticCache instance. | ||
|
|
||
| """ | ||
| from apps.ai.embeddings.factory import get_embedder # noqa: PLC0415 | ||
|
|
||
| entry = SemanticCache( | ||
| query_text=query, | ||
| query_embedding=get_embedder().embed_query(query), | ||
| response_text=response, | ||
| intent=intent, | ||
| confidence=confidence, | ||
| ) | ||
| entry.save() | ||
|
|
||
| logger.info( | ||
| "Semantic cache stored", | ||
| extra={ | ||
| "cache_id": entry.id, | ||
| "intent": intent, | ||
| "query_preview": query[:100], | ||
| }, | ||
| ) | ||
| return entry | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| """Semantic cache service for AI query responses.""" | ||
|
|
||
| from apps.ai.common.crewai_config import CrewAIConfig | ||
| from apps.ai.models.semantic_cache import SemanticCache | ||
|
|
||
| _config = CrewAIConfig() | ||
|
|
||
|
|
||
| def get_cached_response(query: str) -> str | None: | ||
| """Look up semantically similar cached response. | ||
|
|
||
| Args: | ||
| query: User query text. | ||
|
|
||
| Returns: | ||
| Cached response string if found within similarity threshold and TTL, | ||
| None otherwise. | ||
|
|
||
| """ | ||
| if not _config.semantic_cache_enabled: | ||
| return None | ||
|
|
||
| return SemanticCache.get_cached_response( | ||
| query, | ||
| similarity_threshold=_config.semantic_cache_similarity_threshold, | ||
| ttl_seconds=_config.semantic_cache_ttl_seconds, | ||
| ) | ||
|
|
||
|
|
||
| def store_cached_response( | ||
| query: str, | ||
| response: str, | ||
| intent: str = "", | ||
| confidence: float = 0.0, | ||
| ) -> SemanticCache | None: | ||
| """Store query-response pair in semantic cache. | ||
|
|
||
| Args: | ||
| query: Original query text. | ||
| response: Generated response text. | ||
| intent: Classified intent for the query. | ||
| confidence: Router confidence score. | ||
|
|
||
| Returns: | ||
| Created SemanticCache instance. | ||
|
|
||
| """ | ||
| if not _config.semantic_cache_enabled: | ||
| return None | ||
|
|
||
| return SemanticCache.store_response( | ||
| query=query, | ||
| response=response, | ||
| intent=intent, | ||
| confidence=confidence, | ||
|
rudransh-shrivastava marked this conversation as resolved.
|
||
| ) | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| """Tests for CrewAI configuration.""" | ||
|
|
||
| import math | ||
|
|
||
| from apps.ai.common.crewai_config import CrewAIConfig | ||
|
|
||
|
|
||
| class TestCrewAIConfig: | ||
| def test_default_values(self): | ||
| config = CrewAIConfig() | ||
|
|
||
| assert config.semantic_cache_enabled is True | ||
| assert math.isclose(config.semantic_cache_similarity_threshold, 0.95) | ||
| assert config.semantic_cache_ttl_seconds == 86400 | ||
|
|
||
| def test_custom_values(self): | ||
| config = CrewAIConfig( | ||
| semantic_cache_enabled=False, | ||
| semantic_cache_similarity_threshold=0.8, | ||
| semantic_cache_ttl_seconds=3600, | ||
| ) | ||
|
|
||
| assert config.semantic_cache_enabled is False | ||
| assert math.isclose(config.semantic_cache_similarity_threshold, 0.8) | ||
| assert config.semantic_cache_ttl_seconds == 3600 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
intentandconfidenceare optional metadata, might also make sense to storechannel_idfor future filtering.