-
Notifications
You must be signed in to change notification settings - Fork 70
[RHDHPAI-1143] Implement referenced_documents caching #643
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
Changes from 3 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,13 @@ | ||
| """PostgreSQL cache implementation.""" | ||
|
|
||
| import json | ||
| import psycopg2 | ||
|
|
||
| from cache.cache import Cache | ||
| from cache.cache_error import CacheError | ||
| from models.cache_entry import CacheEntry, ConversationData | ||
| from models.cache_entry import CacheEntry | ||
| from models.config import PostgreSQLDatabaseConfiguration | ||
| from models.responses import ConversationData, ReferencedDocument | ||
| from log import get_logger | ||
| from utils.connection_decorator import connection | ||
|
|
||
|
|
@@ -18,17 +20,18 @@ class PostgresCache(Cache): | |
| The cache itself lives stored in following table: | ||
|
|
||
| ``` | ||
| Column | Type | Nullable | | ||
| -----------------+--------------------------------+----------+ | ||
| user_id | text | not null | | ||
| conversation_id | text | not null | | ||
| created_at | timestamp without time zone | not null | | ||
| started_at | text | | | ||
| completed_at | text | | | ||
| query | text | | | ||
| response | text | | | ||
| provider | text | | | ||
| model | text | | | ||
| Column | Type | Nullable | | ||
| -----------------------+--------------------------------+----------+ | ||
| user_id | text | not null | | ||
| conversation_id | text | not null | | ||
| created_at | timestamp without time zone | not null | | ||
| started_at | text | | | ||
| completed_at | text | | | ||
| query | text | | | ||
| response | text | | | ||
| provider | text | | | ||
| model | text | | | ||
| referenced_documents | jsonb | | | ||
| Indexes: | ||
| "cache_pkey" PRIMARY KEY, btree (user_id, conversation_id, created_at) | ||
| "timestamps" btree (created_at) | ||
|
|
@@ -37,15 +40,16 @@ class PostgresCache(Cache): | |
|
|
||
| CREATE_CACHE_TABLE = """ | ||
| CREATE TABLE IF NOT EXISTS cache ( | ||
| user_id text NOT NULL, | ||
| conversation_id text NOT NULL, | ||
| created_at timestamp NOT NULL, | ||
| started_at text, | ||
| completed_at text, | ||
| query text, | ||
| response text, | ||
| provider text, | ||
| model text, | ||
| user_id text NOT NULL, | ||
| conversation_id text NOT NULL, | ||
| created_at timestamp NOT NULL, | ||
| started_at text, | ||
| completed_at text, | ||
| query text, | ||
| response text, | ||
| provider text, | ||
| model text, | ||
| referenced_documents jsonb, | ||
| PRIMARY KEY(user_id, conversation_id, created_at) | ||
| ); | ||
| """ | ||
|
Comment on lines
41
to
55
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add migration for the new referenced_documents column.
Add migration logic in def initialize_cache(self) -> None:
"""Initialize cache - clean it up etc."""
if self.connection is None:
logger.error("Cache is disconnected")
raise CacheError("Initialize_cache: cache is disconnected")
# cursor as context manager is not used there on purpose
# any CREATE statement can raise it's own exception
# and it should not interfere with other statements
cursor = self.connection.cursor()
logger.info("Initializing table for cache")
cursor.execute(PostgresCache.CREATE_CACHE_TABLE)
+
+ # Ensure referenced_documents column exists on upgrades
+ try:
+ cursor.execute("""
+ SELECT column_name
+ FROM information_schema.columns
+ WHERE table_name='cache' AND column_name='referenced_documents'
+ """)
+ if not cursor.fetchone():
+ logger.info("Adding missing 'referenced_documents' column to cache")
+ cursor.execute(
+ "ALTER TABLE cache ADD COLUMN referenced_documents jsonb"
+ )
+ except Exception as e:
+ logger.error("Failed to ensure referenced_documents column: %s", e)
+ raise
logger.info("Initializing table for conversations")
cursor.execute(PostgresCache.CREATE_CONVERSATIONS_TABLE)
🤖 Prompt for AI Agents |
||
|
|
@@ -66,16 +70,16 @@ class PostgresCache(Cache): | |
| """ | ||
|
|
||
| SELECT_CONVERSATION_HISTORY_STATEMENT = """ | ||
| SELECT query, response, provider, model, started_at, completed_at | ||
| SELECT query, response, provider, model, started_at, completed_at, referenced_documents | ||
| FROM cache | ||
| WHERE user_id=%s AND conversation_id=%s | ||
| ORDER BY created_at | ||
| """ | ||
|
|
||
| INSERT_CONVERSATION_HISTORY_STATEMENT = """ | ||
| INSERT INTO cache(user_id, conversation_id, created_at, started_at, completed_at, | ||
| query, response, provider, model) | ||
| VALUES (%s, %s, CURRENT_TIMESTAMP, %s, %s, %s, %s, %s, %s) | ||
| query, response, provider, model, referenced_documents) | ||
| VALUES (%s, %s, CURRENT_TIMESTAMP, %s, %s, %s, %s, %s, %s, %s) | ||
| """ | ||
|
|
||
| QUERY_CACHE_SIZE = """ | ||
|
|
@@ -211,13 +215,19 @@ def get( | |
|
|
||
| result = [] | ||
| for conversation_entry in conversation_entries: | ||
| # Parse it back into an LLMResponse object | ||
| docs_data = conversation_entry[6] | ||
| docs_obj = None | ||
| if docs_data: | ||
| docs_obj = [ReferencedDocument.model_validate(doc) for doc in docs_data] | ||
| cache_entry = CacheEntry( | ||
| query=conversation_entry[0], | ||
| response=conversation_entry[1], | ||
| provider=conversation_entry[2], | ||
| model=conversation_entry[3], | ||
| started_at=conversation_entry[4], | ||
| completed_at=conversation_entry[5], | ||
| referenced_documents=docs_obj, | ||
| ) | ||
| result.append(cache_entry) | ||
|
|
||
|
|
@@ -245,6 +255,11 @@ def insert_or_append( | |
| raise CacheError("insert_or_append: cache is disconnected") | ||
|
|
||
| try: | ||
| referenced_documents_json = None | ||
| if cache_entry.referenced_documents: | ||
| docs_as_dicts = [doc.model_dump(mode='json') for doc in cache_entry.referenced_documents] | ||
| referenced_documents_json = json.dumps(docs_as_dicts) | ||
|
|
||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # the whole operation is run in one transaction | ||
| with self.connection.cursor() as cursor: | ||
| cursor.execute( | ||
|
|
@@ -258,6 +273,7 @@ def insert_or_append( | |
| cache_entry.response, | ||
| cache_entry.provider, | ||
| cache_entry.model, | ||
| referenced_documents_json, | ||
| ), | ||
| ) | ||
|
|
||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.