Skip to content

Commit d8110f1

Browse files
Merge pull request #135 from udaykiran243/feat/issue-37-ai-caching
Implement AI response caching with SQLite backend
2 parents d0a6c30 + 78cec25 commit d8110f1

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

‎app.py‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import os
88
from datetime import datetime
99
from ai_service import generate_book_note, get_ai_recommendations, get_book_mood_tags_safe, generate_chat_response, llm_service
10-
from models import db, User, Book, ShelfItem, register_user, login_user
10+
from models import db, User, Book, ShelfItem, BookNote, register_user, login_user
1111
from collections import defaultdict, deque
1212
from math import ceil
1313
from time import time
@@ -260,7 +260,24 @@ def handle_generate_note():
260260
title = data.get('title', '')
261261
author = data.get('author', '')
262262

263+
# Check cache
264+
cached_note = BookNote.query.filter_by(book_title=title, book_author=author).first()
265+
if cached_note:
266+
print(f"Cache hit for {title} by {author}")
267+
return jsonify({"vibe": cached_note.content})
268+
263269
vibe = generate_book_note(description, title, author)
270+
271+
# Save to cache
272+
try:
273+
if vibe and title and author: # Ensure we have valid data to cache
274+
new_note = BookNote(book_title=title, book_author=author, content=vibe)
275+
db.session.add(new_note)
276+
db.session.commit()
277+
except Exception as e:
278+
print(f"Failed to cache note: {e}")
279+
db.session.rollback()
280+
264281
return jsonify({"vibe": vibe})
265282

266283
except Exception as e:

‎models.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,17 @@ def to_dict(self):
6868
"created_at": self.created_at.isoformat()
6969
}
7070

71+
class BookNote(db.Model):
72+
id = db.Column(db.Integer, primary_key=True)
73+
book_title = db.Column(db.String(255), nullable=False)
74+
book_author = db.Column(db.String(255), nullable=False)
75+
content = db.Column(db.Text, nullable=False)
76+
created_at = db.Column(db.DateTime, default=datetime.utcnow)
77+
78+
__table_args__ = (
79+
db.Index('idx_book_note_title_author', 'book_title', 'book_author'),
80+
)
81+
7182
def register_user(username, email, password):
7283
user = User(username=username, email=email)
7384
user.set_password(password)

0 commit comments

Comments
 (0)