chore: migrate config paths to XDG base directory and add hit_count tracking to api_cache

This commit is contained in:
2025-11-05 14:34:23 +00:00
parent 9f155db7c2
commit ab9c29467c
32 changed files with 2598 additions and 340 deletions
+31 -5
View File
@@ -22,7 +22,8 @@ class APICache:
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
model TEXT,
token_count INTEGER
token_count INTEGER,
hit_count INTEGER DEFAULT 0
)
"""
)
@@ -31,7 +32,14 @@ class APICache:
CREATE INDEX IF NOT EXISTS idx_expires_at ON api_cache(expires_at)
"""
)
conn.commit()
# Check if hit_count column exists, add if not
cursor.execute("PRAGMA table_info(api_cache)")
columns = [row[1] for row in cursor.fetchall()]
if "hit_count" not in columns:
cursor.execute("ALTER TABLE api_cache ADD COLUMN hit_count INTEGER DEFAULT 0")
conn.commit()
conn.close()
def _generate_cache_key(
@@ -64,10 +72,21 @@ class APICache:
)
row = cursor.fetchone()
conn.close()
if row:
# Increment hit count
cursor.execute(
"""
UPDATE api_cache SET hit_count = hit_count + 1
WHERE cache_key = ?
""",
(cache_key,),
)
conn.commit()
conn.close()
return json.loads(row[0])
conn.close()
return None
def set(
@@ -90,8 +109,8 @@ class APICache:
cursor.execute(
"""
INSERT OR REPLACE INTO api_cache
(cache_key, response_data, created_at, expires_at, model, token_count)
VALUES (?, ?, ?, ?, ?, ?)
(cache_key, response_data, created_at, expires_at, model, token_count, hit_count)
VALUES (?, ?, ?, ?, ?, ?, 0)
""",
(
cache_key,
@@ -149,6 +168,12 @@ class APICache:
)
total_tokens = cursor.fetchone()[0] or 0
cursor.execute(
"SELECT SUM(hit_count) FROM api_cache WHERE expires_at > ?",
(current_time,),
)
total_hits = cursor.fetchone()[0] or 0
conn.close()
return {
@@ -156,4 +181,5 @@ class APICache:
"valid_entries": valid_entries,
"expired_entries": total_entries - valid_entries,
"total_cached_tokens": total_tokens,
"total_cache_hits": total_hits,
}
+7
View File
@@ -13,6 +13,13 @@ class ToolCache:
"db_get",
"db_query",
"index_directory",
"http_fetch",
"web_search",
"web_search_news",
"search_knowledge",
"get_knowledge_entry",
"get_knowledge_by_category",
"get_knowledge_statistics",
}
def __init__(self, db_path: str, ttl_seconds: int = 300):